|
2 | 2 |
|
3 | 3 | (function() { |
4 | 4 |
|
5 | | -function routerDecorator(<%= filters.uirouter ? '$stateProvider' : '$provide' %>) { |
6 | | - var authDecorator = function(<%= filters.uirouter ? 'state' : 'route' %>) { |
7 | | - var auth = <%= filters.uirouter ? 'state' : 'route' %>.authenticate; |
8 | | - if (auth) { |
9 | | - <%= filters.uirouter ? 'state' : 'route' %>.resolve = <%= filters.uirouter ? 'state' : 'route' %>.resolve || {}; |
10 | | - <%= filters.uirouter ? 'state' : 'route' %>.resolve.user = function(<%= filters.uirouter ? '$state' : '$location' %>, $q, Auth) { |
11 | | - return Auth.getCurrentUser(true) |
12 | | - .then(function(user) { |
13 | | - if ((typeof auth !== 'string' && user._id) || |
14 | | - (typeof auth === 'string' && Auth.hasRole(auth))) { |
15 | | - return user; |
16 | | - }<% if (filters.ngroute) { %> |
17 | | - $location.path((user._id) ? '/' : '/login');<% } if (filters.uirouter) { %> |
18 | | - $state.go((user._id) ? 'main' : 'login');<% } %> |
19 | | - return $q.reject('not authorized'); |
20 | | - }); |
21 | | - }; |
22 | | - } |
23 | | - };<% if (filters.ngroute) { %> |
24 | | - |
25 | | - $provide.decorator('$route', function($delegate) { |
26 | | - for (var r in $delegate.routes) { |
27 | | - authDecorator($delegate.routes[r]); |
28 | | - } |
29 | | - return $delegate; |
30 | | - });<% } if (filters.uirouter) { %> |
| 5 | +angular.module('<%= scriptAppName %>.auth') |
| 6 | + .run(function($rootScope<% if (filters.ngroute) { %>, $location<% } if (filters.uirouter) { %>, $state<% } %>, Auth) { |
| 7 | + // Redirect to login if route requires auth and the user is not logged in, or doesn't have required role |
| 8 | + $rootScope.$on(<% if (filters.ngroute) { %>'$routeChangeStart'<% } %><% if (filters.uirouter) { %>'$stateChangeStart'<% } %>, function(event, next) { |
| 9 | + if(!next.authenticate) { |
| 10 | + return; |
| 11 | + } |
31 | 12 |
|
32 | | - $stateProvider.decorator('authenticate', function(state) { |
33 | | - authDecorator(state); |
34 | | - return state.authenticate; |
35 | | - });<% } %> |
36 | | -} |
| 13 | + let query = typeof next.authenticate === 'string' ? Auth.hasRole : Auth.isLoggedIn; |
37 | 14 |
|
38 | | -angular.module('<%= scriptAppName %>.auth') |
39 | | - .config(routerDecorator); |
| 15 | + query(1,2).then(good => { |
| 16 | + if(!good) { |
| 17 | + event.preventDefault(); |
| 18 | + Auth.isLoggedIn().then(is => {<% if (filters.ngroute) { %> |
| 19 | + $location.path(is ? '/' : '/login');<% } if (filters.uirouter) { %> |
| 20 | + $state.go(is ? 'main' : 'login');<% } %> |
| 21 | + }); |
| 22 | + } |
| 23 | + }); |
| 24 | + }); |
| 25 | + }); |
40 | 26 |
|
41 | 27 | })(); |
0 commit comments