Skip to content

Instantly share code, notes, and snippets.

@xcambar xcambar/LICENSE
Last active Nov 20, 2015

Embed
What would you like to do?
Authenticated routing using AngularJS
/* Copyright (c) 2015 - Xavier Cambar <@ xcambar_gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
authRouteProvider.$inject = ['$routeProvider'];
function authRouteProvider ($routeProvider) {
/**
* Creates a controller bound to the route, or wraps the controller in param
* so the authentication check is run before the original controller is executed
* @param currentController
* @return {Function} The wrapper controller
*/
function redirectCtrlFactory (currentController) {
_ctrl.$inject = ['currentUser__', 'userRole__', '$location'];
if (currentController) {
var currentCtrlDependencies = currentController.$inject || [];
_ctrl.$inject = currentCtrlDependencies.concat(['currentUser__', 'userRole__', '$location']);
}
function _ctrl () {
var args = Array.prototype.slice.call(arguments);
var argv = arguments.length;
if (args[argv - 3].credentials() !== args[argv - 2]) {
return args[argv - 1].path('/');
}
if (currentController) {
while (args.length !== currentCtrlDependencies.length) {
args.pop();
}
return currentController.apply(this, args);
}
}
return _ctrl;
}
var _currentUserRole;
/**
* Returns the promise of a userProfile instance
*/
userProfileResolver.$inject = ['userProfile'];
function userProfileResolver (userProfile) {
return userProfile;
}
/**
* New methods available in authRouteProvider
* @type {Object}
* @private
*/
var _ext = {
/**
* The routes defined after a call to only(...) will be available only to
* users with the specified credentials
* @param role
* @return {authRouteProvider}
*/
'only': function (role) {
_currentUserRole = role;
return this;
},
/**
* The routes defined after a call to all() will be available to
* all the users
* @param role
* @return {authRouteProvider}
*/
'all': function () {
_currentUserRole = null;
return this;
},
/**
* Wraps the original $routeProvider.when method in order to
* specify a controller and 2 dependencies, so the authentication
* check can be done at runtime
* @param {String} role
* @return {authRouteProvider}
*/
'when': function () {
var conf = arguments[1] || {};
var _userRole = _currentUserRole;
conf.resolve = conf.resolve || {};
if (_userRole) {
conf.resolve['currentUser__'] = userProfileResolver;
conf.resolve['userRole__'] = function () { return _userRole; };
conf.controller = redirectCtrlFactory(conf.controller);
}
return $routeProvider.when.call(this, arguments[0], conf);
}
};
return angular.extend({}, $routeProvider, _ext);
}
angular.module('xc.authRouteProvider', []).provider('authRoute', authRouteProvider);
Copyright (c) 2015 - Xavier Cambar <@ xcambar_gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
/* Copyright (c) 2015 - Xavier Cambar <@ xcambar_gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// How to use the whole thing:
angular.module('example.routeConfig', ['xc.authRouteProvider'])
.config(['authRouteProvider', '$locationProvider', 'userProfileProvider', function (authRouteProvider, $locationProvider, userProfileProvider) {
authRouteProvider.
all().
when('/', {templateUrl: "/static/templates/home.html"}).
when('/logout').
when('/profile', {templateUrl: "/static/templates/currentUser/edit.html"}).
otherwise({redirectTo: '/'})
;
authRouteProvider.
only('admin').
when('/user', {templateUrl: "/static/templates/user/list.html", controller: UserCtrl}).
when('/user/add', {templateUrl: "/static/templates/user/add.html"}).
when('/user/edit/:userId', {templateUrl: "/static/templates/user/edit.html"})
;
}
]);
/* Copyright (c) 2015 - Xavier Cambar <@ xcambar_gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
'use strict';
/**
* A very simple model to represent your authenticated user.
* The sole requirement for the model is to be able to define
* a UserProfile::credentials() method, so the router can access
* the property defining the credentials of the loggedin user.
* @param data
* @constructor
*/
function UserProfile (data) {
var _resource;
this.populate = function (data) {
angular.extend(this, data);
};
if (data) {
this.populate(data);
}
}
/**
* An example of methods you can add to your model
* @return {String}
*/
UserProfile.prototype.getFullName = function () {
return [this.firstName, this.lastName].join(' ');
};
/**
* The only required method. Here, it returns a String,
* but it could as well return a complex Object
* @return {String}
*/
UserProfile.prototype.credentials = function () {
return this.role;
};
function userProfileProvider () {
/**
* Returns a promise of the UserProfile instance to be, for when the $http call is finished
*/
this.$get = ['profileResource', 'userProfileModel', '$q', function (profileResource, userProfileModel, $q) {
var deferred = $q.defer();
profileResource.success(function (data) {
var resolved = data;
if (userProfileModel) {
resolved = new userProfileModel(data);
}
return deferred.resolve(resolved);
});
return deferred.promise;
}];
}
angular.module('xc.loggedInUser', [])
.provider('userProfile', userProfileProvider)
.constant('userProfileModel', UserProfile)
.factory('profileResource', ['$http', function ($http) {
return $http({method: 'GET', url:'/api/profile'})
.error(function (data, status, headers, config) {
console.log(data);
});
}]);
@ghost

This comment has been minimized.

Copy link

ghost commented Jul 23, 2013

Nice - very useful :)

@scribblet

This comment has been minimized.

Copy link

scribblet commented Aug 29, 2013

Any ideas how this could be modified to incorporate something like ui-router and $state/$stateProvider?

@kalisjoshua

This comment has been minimized.

Copy link

kalisjoshua commented Jan 31, 2014

This seems great. How difficult would this be to alter for ui-router? I haven't been doing Angular long enough to be able to translate this to ui-router myself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.