Skip to content

Feature: auth module #1309

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Sep 16, 2015
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion app/generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,10 @@ export default class Generator extends Base {
if(this.filters.socketio) angModules.push("'btford.socket-io'");
if(this.filters.uirouter) angModules.push("'ui.router'");
if(this.filters.uibootstrap) angModules.push("'ui.bootstrap'");
if(this.filters.auth) angModules.push("'validation.match'");
if(this.filters.auth) {
angModules.unshift(`'${this.scriptAppName}.auth'`);
angModules.push("'validation.match'");
}

this.angularModules = '\n ' + angModules.join(',\n ') +'\n';
}
Expand Down
7 changes: 7 additions & 0 deletions app/templates/Gruntfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -658,6 +658,13 @@ module.exports = function (grunt) {
filePath = filePath.replace('/.tmp/', '');
return '<script src="' + filePath + '"></script>';
},
sort: function(a, b) {
var module = /\.module\.js$/;
var aMod = module.test(a);
var bMod = module.test(b);
// inject *.module.js first
return (aMod === bMod) ? 0 : (aMod ? -1 : 1);
},
starttag: '<!-- injector:js -->',
endtag: '<!-- endinjector -->'
},
Expand Down
6 changes: 4 additions & 2 deletions app/templates/client/app/admin(auth)/admin(js).js
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ angular.module('<%= scriptAppName %>')
$routeProvider
.when('/admin', {
templateUrl: 'app/admin/admin.html',
controller: 'AdminCtrl'
controller: 'AdminCtrl',
authenticate: 'admin'
});
});<% } %><% if (filters.uirouter) { %>.config(function($stateProvider) {
$stateProvider
.state('admin', {
url: '/admin',
templateUrl: 'app/admin/admin.html',
controller: 'AdminCtrl'
controller: 'AdminCtrl',
authenticate: 'admin'
});
});<% } %>
56 changes: 5 additions & 51 deletions app/templates/client/app/app(js).js
Original file line number Diff line number Diff line change
@@ -1,59 +1,13 @@
'use strict';

angular.module('<%= scriptAppName %>', [<%- angularModules %>])
<% if (filters.ngroute) { %>.config(function($routeProvider, $locationProvider<% if (filters.auth) { %>, $httpProvider<% } %>) {
.config(function(<% if (filters.ngroute) { %>$routeProvider<% } if (filters.uirouter) { %>$urlRouterProvider<% } %>, $locationProvider) {<% if (filters.ngroute) { %>
$routeProvider
.otherwise({
redirectTo: '/'
});

$locationProvider.html5Mode(true);<% if (filters.auth) { %>
$httpProvider.interceptors.push('authInterceptor');<% } %>
})<% } if (filters.uirouter) { %>.config(function($stateProvider, $urlRouterProvider, $locationProvider<% if (filters.auth) { %>, $httpProvider<% } %>) {
});<% } if (filters.uirouter) { %>
$urlRouterProvider
.otherwise('/');

$locationProvider.html5Mode(true);<% if (filters.auth) { %>
$httpProvider.interceptors.push('authInterceptor');<% } %>
})<% } if (filters.auth) { %>

.factory('authInterceptor', function($rootScope, $q, $cookies<% if (filters.ngroute) { %>, $location<% } if (filters.uirouter) { %>, $injector<% } %>) {
<% if (filters.uirouter) { %>var state;
<% } %>return {
// Add authorization token to headers
request: function(config) {
config.headers = config.headers || {};
if ($cookies.get('token')) {
config.headers.Authorization = 'Bearer ' + $cookies.get('token');
}
return config;
},

// Intercept 401s and redirect you to login
responseError: function(response) {
if (response.status === 401) {
<% if (filters.ngroute) { %>$location.path('/login');<% } if (filters.uirouter) { %>(state || (state = $injector.get('$state'))).go('login');<% } %>
// remove any stale tokens
$cookies.remove('token');
return $q.reject(response);
}
else {
return $q.reject(response);
}
}
};
})
.otherwise('/');<% } %>

.run(function($rootScope<% if (filters.ngroute) { %>, $location<% } if (filters.uirouter) { %>, $state<% } %>, Auth) {
// Redirect to login if route requires auth and the user is not logged in
$rootScope.$on(<% if (filters.ngroute) { %>'$routeChangeStart'<% } %><% if (filters.uirouter) { %>'$stateChangeStart'<% } %>, function(event, next) {
if (next.authenticate) {
Auth.isLoggedIn(function(loggedIn) {
if (!loggedIn) {
event.preventDefault();
<% if (filters.ngroute) { %>$location.path('/login');<% } if (filters.uirouter) { %>$state.go('login');<% } %>
}
});
}
});
})<% } %>;
$locationProvider.html5Mode(true);
});
57 changes: 29 additions & 28 deletions app/templates/client/app/main/main.controller(js).js
Original file line number Diff line number Diff line change
@@ -1,33 +1,34 @@
'use strict';

(function() {

function MainController($scope, $http<% if (filters.socketio) { %>, socket<% } %>) {
var self = this;
this.awesomeThings = [];

$http.get('/api/things').then(function(response) {
self.awesomeThings = response.data;<% if (filters.socketio) { %>
socket.syncUpdates('thing', self.awesomeThings);<% } %>
});
<% if (filters.models) { %>
this.addThing = function() {
if (self.newThing === '') {
return;
}
$http.post('/api/things', { name: self.newThing });
self.newThing = '';
};

this.deleteThing = function(thing) {
$http.delete('/api/things/' + thing._id);
};<% } %><% if (filters.socketio) { %>

$scope.$on('$destroy', function() {
socket.unsyncUpdates('thing');
});<% } %>
}

angular.module('<%= scriptAppName %>')
.controller('MainController', MainController);
function MainController($scope, $http<% if (filters.socketio) { %>, socket<% } %>) {
var self = this;
this.awesomeThings = [];

$http.get('/api/things').then(function(response) {
self.awesomeThings = response.data;<% if (filters.socketio) { %>
socket.syncUpdates('thing', self.awesomeThings);<% } %>
});<% if (filters.models) { %>

this.addThing = function() {
if (self.newThing === '') {
return;
}
$http.post('/api/things', { name: self.newThing });
self.newThing = '';
};

this.deleteThing = function(thing) {
$http.delete('/api/things/' + thing._id);
};<% } if (filters.socketio) { %>

$scope.$on('$destroy', function() {
socket.unsyncUpdates('thing');
});<% } %>
}

angular.module('<%= scriptAppName %>')
.controller('MainController', MainController);

})();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should keep this tabbed the way it was. The IIFE shouldn't mess with our code's formatting.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure...

11 changes: 11 additions & 0 deletions app/templates/client/components/auth(auth)/auth.module(js).js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
'use strict';

angular.module('<%= scriptAppName %>.auth', [
'<%= scriptAppName %>.constants',
'ngCookies'<% if (filters.ngroute) { %>,
'ngRoute'<% } if (filters.uirouter) { %>,
'ui.router'<% } %>
])
.config(function($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
});
70 changes: 49 additions & 21 deletions app/templates/client/components/auth(auth)/auth.service(js).js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
'use strict';

angular.module('<%= scriptAppName %>')
.factory('Auth', function Auth($http, User, $cookies, $q) {
(function() {

function AuthService($location, $http, $cookies, $q, appConfig, User) {
/**
* Return a callback or noop function
*
Expand All @@ -12,13 +13,14 @@ angular.module('<%= scriptAppName %>')
return (angular.isFunction(cb)) ? cb : angular.noop;
},

currentUser = {};
currentUser = {},
userRoles = appConfig.userRoles || [];

if ($cookies.get('token')) {
if ($cookies.get('token') && $location.path() !== '/logout') {
currentUser = User.get();
}

return {
var Auth = {

/**
* Authenticate user and save token
Expand All @@ -42,10 +44,10 @@ angular.module('<%= scriptAppName %>')
return user;
})
.catch(function(err) {
this.logout();
Auth.logout();
safeCb(callback)(err.data);
return $q.reject(err.data);
}.bind(this));
});
},

/**
Expand All @@ -71,9 +73,9 @@ angular.module('<%= scriptAppName %>')
return safeCb(callback)(null, user);
},
function(err) {
this.logout();
Auth.logout();
return safeCb(callback)(err);
}.bind(this)).$promise;
}).$promise;
},

/**
Expand Down Expand Up @@ -107,7 +109,8 @@ angular.module('<%= scriptAppName %>')
return currentUser;
}

var value = (currentUser.hasOwnProperty('$promise')) ? currentUser.$promise : currentUser;
var value = (currentUser.hasOwnProperty('$promise')) ?
currentUser.$promise : currentUser;
return $q.when(value)
.then(function(user) {
safeCb(callback)(user);
Expand All @@ -130,7 +133,7 @@ angular.module('<%= scriptAppName %>')
return currentUser.hasOwnProperty('role');
}

return this.getCurrentUser(null)
return Auth.getCurrentUser(null)
.then(function(user) {
var is = user.hasOwnProperty('role');
safeCb(callback)(is);
Expand All @@ -139,25 +142,43 @@ angular.module('<%= scriptAppName %>')
},

/**
* Check if a user is an admin
* Check if a user has a specified role or higher
* (synchronous|asynchronous)
*
* @param {Function|*} callback - optional, function(is)
* @param {String} role - the role to check against
* @param {Function|*} callback - optional, function(has)
* @return {Bool|Promise}
*/
isAdmin: function(callback) {
if (arguments.length === 0) {
return currentUser.role === 'admin';
hasRole: function(role, callback) {
var hasRole = function(r, h) {
return userRoles.indexOf(r) >= userRoles.indexOf(h);
};

if (arguments.length < 2) {
return hasRole(currentUser.role, role);
}

return this.getCurrentUser(null)
return Auth.getCurrentUser(null)
.then(function(user) {
var is = user.role === 'admin';
safeCb(callback)(is);
return is;
var has = (user.hasOwnProperty('role')) ?
hasRole(user.role, role) : false;
safeCb(callback)(has);
return has;
});
},

/**
* Check if a user is an admin
* (synchronous|asynchronous)
*
* @param {Function|*} callback - optional, function(is)
* @return {Bool|Promise}
*/
isAdmin: function() {
return Auth.hasRole
.apply(Auth, [].concat.apply(['admin'], arguments));
},

/**
* Get auth token
*
Expand All @@ -167,4 +188,11 @@ angular.module('<%= scriptAppName %>')
return $cookies.get('token');
}
};
});

return Auth;
}

angular.module('<%= scriptAppName %>.auth')
.factory('Auth', AuthService);

})();
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
'use strict';

(function() {

function authInterceptor($rootScope, $q, $cookies<% if (filters.ngroute) { %>, $location<% } if (filters.uirouter) { %>, $injector<% } %>) {
<% if (filters.uirouter) { %>var state;
<% } %>return {
// Add authorization token to headers
request: function(config) {
config.headers = config.headers || {};
if ($cookies.get('token')) {
config.headers.Authorization = 'Bearer ' + $cookies.get('token');
}
return config;
},

// Intercept 401s and redirect you to login
responseError: function(response) {
if (response.status === 401) {
<% if (filters.ngroute) { %>$location.path('/login');<% } if (filters.uirouter) { %>(state || (state = $injector.get('$state'))).go('login');<% } %>
// remove any stale tokens
$cookies.remove('token');
return $q.reject(response);
}
else {
return $q.reject(response);
}
}
};
}

angular.module('<%= scriptAppName %>.auth')
.factory('authInterceptor', authInterceptor);

})();
Loading