-
Notifications
You must be signed in to change notification settings - Fork 212
/
Copy pathpermission.mdl.js
55 lines (50 loc) · 2.5 KB
/
permission.mdl.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
(function () {
'use strict';
angular.module('permission', ['ui.router'])
.run(['$rootScope', 'Permission', '$state', function ($rootScope, Permission, $state) {
$rootScope.$on('$stateChangeStart',
function (event, toState, toParams, fromState, fromParams) {
// If there are permissions set then prevent default and attempt to authorize
var permissions;
if (toState.data && toState.data.permissions) {
permissions = toState.data.permissions;
} else if (toState.permissions) {
/**
* This way of defining permissions will be depracated in v1. Should use
* `data` key instead
*/
console.log('Deprecation Warning: permissions should be set inside the `data` key ');
console.log('Setting permissions for a state outside `data` will be depracated in' +
' version 1');
permissions = toState.permissions;
}
if (permissions) {
event.preventDefault();
Permission.authorize(permissions, toParams).then(function () {
// If authorized, use call state.go without triggering the event.
// Then trigger $stateChangeSuccess manually to resume the rest of the process
// Note: This is a pseudo-hacky fix which should be fixed in future ui-router versions
if (!$rootScope.$broadcast('$stateChangeStart', toState.name, toParams, fromState.name, fromParams).defaultPrevented) {
$rootScope.$broadcast('$stateChangePermissionAccepted', toState, toParams);
$state.go(toState.name, toParams, {notify: false}).then(function() {
$rootScope
.$broadcast('$stateChangeSuccess', toState, toParams, fromState, fromParams);
});
}
}, function () {
if (!$rootScope.$broadcast('$stateChangeStart', toState.name, toParams, fromState.name, fromParams).defaultPrevented) {
$rootScope.$broadcast('$stateChangePermissionDenied', toState, toParams);
// If not authorized, redirect to wherever the route has defined, if defined at all
var redirectTo = permissions.redirectTo;
if (redirectTo) {
$state.go(redirectTo, toParams, {notify: false}).then(function() {
$rootScope
.$broadcast('$stateChangeSuccess', toState, toParams, fromState, fromParams);
});
}
}
});
}
});
}]);
}());