|
2 | 2 |
|
3 | 3 | (function() { |
4 | 4 |
|
5 | | - function AuthService($http, User, $cookies, $q) { |
| 5 | + function AuthService($http, $cookies, $q, appConfig, User) { |
6 | 6 | /** |
7 | 7 | * Return a callback or noop function |
8 | 8 | * |
|
13 | 13 | return (angular.isFunction(cb)) ? cb : angular.noop; |
14 | 14 | }, |
15 | 15 |
|
16 | | - currentUser = {}; |
| 16 | + currentUser = {}, |
| 17 | + userRoles = appConfig.userRoles || []; |
17 | 18 |
|
18 | 19 | if ($cookies.get('token')) { |
19 | 20 | currentUser = User.get(); |
|
108 | 109 | return currentUser; |
109 | 110 | } |
110 | 111 |
|
111 | | - var value = (currentUser.hasOwnProperty('$promise')) ? currentUser.$promise : currentUser; |
| 112 | + var value = (currentUser.hasOwnProperty('$promise')) ? |
| 113 | + currentUser.$promise : currentUser; |
112 | 114 | return $q.when(value) |
113 | 115 | .then(function(user) { |
114 | 116 | safeCb(callback)(user); |
|
140 | 142 | }, |
141 | 143 |
|
142 | 144 | /** |
143 | | - * Check if a user is an admin |
| 145 | + * Check if a user has a specified role or higher |
144 | 146 | * (synchronous|asynchronous) |
145 | 147 | * |
146 | | - * @param {Function|*} callback - optional, function(is) |
| 148 | + * @param {String} role - the role to check against |
| 149 | + * @param {Function|*} callback - optional, function(has) |
147 | 150 | * @return {Bool|Promise} |
148 | 151 | */ |
149 | | - isAdmin: function(callback) { |
150 | | - if (arguments.length === 0) { |
151 | | - return currentUser.role === 'admin'; |
| 152 | + hasRole: function(role, callback) { |
| 153 | + var hasRole = function(r, h) { |
| 154 | + return userRoles.indexOf(r) >= userRoles.indexOf(h); |
| 155 | + }; |
| 156 | + |
| 157 | + if (arguments.length < 2) { |
| 158 | + return hasRole(currentUser.role, role); |
152 | 159 | } |
153 | 160 |
|
154 | 161 | return Auth.getCurrentUser(null) |
155 | 162 | .then(function(user) { |
156 | | - var is = user.role === 'admin'; |
157 | | - safeCb(callback)(is); |
158 | | - return is; |
| 163 | + var has = (user.hasOwnProperty('role')) ? |
| 164 | + hasRole(user.role, role) : false; |
| 165 | + safeCb(callback)(has); |
| 166 | + return has; |
159 | 167 | }); |
160 | 168 | }, |
161 | 169 |
|
| 170 | + /** |
| 171 | + * Check if a user is an admin |
| 172 | + * (synchronous|asynchronous) |
| 173 | + * |
| 174 | + * @param {Function|*} callback - optional, function(is) |
| 175 | + * @return {Bool|Promise} |
| 176 | + */ |
| 177 | + isAdmin: function() { |
| 178 | + return Auth.hasRole |
| 179 | + .apply(Auth, [].concat.apply(['admin'], arguments)); |
| 180 | + }, |
| 181 | + |
162 | 182 | /** |
163 | 183 | * Get auth token |
164 | 184 | * |
|
0 commit comments