4 angular.module('motion.auth', []).factory('Auth', AuthService);
7 function AuthService($mdDialog, $cookies, $q, $window, $document, api) {
12 getCurrentUser: getCurrentUser,
13 getPermissions: getPermissions,
14 hasChildrenPermissions: hasChildrenPermissions,
15 hasModulePermissions: hasModulePermissions,
16 hasModulesPermissions: hasModulesPermissions,
18 hasPermission: hasPermission,
19 hasResourcePermission: hasResourcePermission,
20 hasSectionPermissions: hasSectionPermissions,
21 hasSectionsPermissions: hasSectionsPermissions,
24 isLoggedIn: isLoggedIn,
25 isTelephone: isTelephone,
29 parseCrudPermissions: parseCrudPermissions,
30 queueLogin: queueLogin,
31 reloadPermissions: reloadPermissions,
32 removeCookies: removeCookies,
33 retrieveUser: retrieveUser,
34 setCurrentUser: setCurrentUser,
35 getAuthenticationType: getAuthenticationType,
42 * Gets the authorization token
43 * @return {Object} Authorization token
46 return $cookies.get('motion.token');
50 * Gets the currently logged in user
51 * @return {Object} The currently logged in user
53 function getCurrentUser() {
54 return motionCurrentUser;
58 * Sets the currently logged in user
59 * @param {Object} user - The currently logged in user
61 function setCurrentUser(user) {
62 motionCurrentUser = _.merge(motionCurrentUser, user);
66 * Adds an agent to the queues
67 * @param {Object} intrf - The agent interface
68 * @return {Object} Updated user
70 function queueLogin(intrf) {
71 return $q(function(resolve, reject) {
74 id: motionCurrentUser.id,
78 .$promise.then(function(user) {
81 .catch(function(err) {
88 * Removes an agent from the queues
90 function queueLogout() {
91 return $q(function(resolve, reject) {
94 id: motionCurrentUser.id,
97 .$promise.then(function() {
100 .catch(function(err) {
107 * Sets the user's online status if the role is 'admin' or 'user'
108 * @return {Object} Updated user
110 function setOnlineStatus(status) {
111 return $q(function(resolve, reject) {
114 lastLoginAt: status ? moment().format('YYYY-MM-DD HH:mm:ss') : undefined
118 id: motionCurrentUser.id
122 .$promise.then(function(user) {
125 .catch(function(err) {
132 * Authenticate user and save token
133 * @param {Object} user - The user which requires authentication
136 function login(user) {
137 return $q(function(resolve, reject) {
140 .$promise.then(function(res) {
141 console.log("RES", res.token);
142 $cookies.put('motion.token', res.token, {
147 return api.user.get({
151 .then(function(user) {
152 motionCurrentUser = user;
153 motionCurrentUser.lastLoginAt = moment().format('YYYY-MM-DD HH:mm:ss');
154 setAuthenticationType('LOCAL_LOGIN');
157 if (isAgent() && motionCurrentUser.showWebBar === 1 && motionCurrentUser.hotdesk) {
158 return $mdDialog.show({
159 controller: 'HotDeskDialogController',
161 templateUrl: 'app/auth/services/hotdesk/dialog.html',
162 parent: angular.element($document.body),
163 clickOutsideToClose: false,
165 telephones: function(apiResolver) {
166 return apiResolver.resolve('user@get', {
167 fields: 'id,fullname,name,internal',
176 .then(function(intrf) {
177 if (isAgent() && motionCurrentUser.showWebBar !== 0) {
178 return queueLogin(intrf);
179 } else if (isAdmin() || isUser()) {
180 return setOnlineStatus(true);
185 .then(function(updatedUser) {
186 motionCurrentUser = _.assign(motionCurrentUser, updatedUser);
189 .catch(function(err) {
196 * Removes authentication cookies and local storage data
198 function removeCookies() {
199 $cookies.remove('motion.token');
200 if (motionCurrentUser) {
201 $window.localStorage.removeItem('motion.user:' + motionCurrentUser.id);
202 $window.localStorage.removeItem('motion.authenticationtype');
204 motionCurrentUser = null;
209 * Delete access token and user info
210 * @param {Boolean} logoutBySomeoneElse Flag to discriminate who initiated the logout
212 function logout(logoutBySomeoneElse) {
213 return $q(function(resolve, reject) {
214 if (logoutBySomeoneElse) {
220 if (isAgent() && motionCurrentUser.showWebBar !== 0) {
221 return queueLogout();
222 } else if (isAdmin() || isUser()) {
223 return setOnlineStatus(false);
232 .catch(function(err) {
240 * Checks if a user is logged by retrieving the authentication token
243 function isLoggedIn() {
244 return getToken() ? true : false;
248 * Checks if an user is an 'agent'
252 return motionCurrentUser.role === 'agent';
256 * Checks if an user is an 'admin'
260 return motionCurrentUser.role === 'admin';
264 * Checks if an user is an 'user'
268 return motionCurrentUser.role === 'user';
272 * Checks if an user is a 'telephone'
275 function isTelephone() {
276 return motionCurrentUser.role === 'telephone';
280 * Retrieves the current logged in user
283 function retrieveUser() {
284 return $q(function(resolve, reject) {
287 .$promise.then(function(user) {
288 if (user.role === 'user') {
289 return getPermissions(user.userProfileId).then(function(permissions) {
290 user.permissions = permissions;
297 .then(function(user) {
298 motionCurrentUser = user;
299 resolve(motionCurrentUser);
301 .catch(function(err) {
308 * Checks if a user has a specified role
309 * @param {String} role - The role to check against
312 function hasRole(role) {
313 return motionCurrentUser ? motionCurrentUser.role === role : false;
317 * Check if a user has a specified permissions
318 * @param {String} id - The section id to verify
321 function hasPermission(id) {
322 return motionCurrentUser ? _.includes(motionCurrentUser.permissions, id) : false;
326 * Get permissions from User Profile
327 * @param {Integer} userProfileId - The id of the User Profile to
329 function getPermissions(userProfileId) {
330 var permissions = [];
332 return $q(function(resolve, reject) {
333 if (!userProfileId) {
334 resolve(permissions);
337 return api.userProfile
341 .$promise.then(function(sections) {
342 for (var i = 0; i < sections.length; i++) {
343 var item = sections[i];
344 permissions.push(item.sectionId);
345 if (item.subsections) {
346 permissions = _.concat(permissions, item.subsections);
352 .then(function(permissions) {
353 resolve(permissions);
355 .catch(function(err) {
356 reject('Error retrieving user profile permissions', err);
362 * Determine if a section should be visible because of the visibility of one of its subsections
363 * @param {Array} ids The list of subsections ids
365 function hasChildrenPermissions(ids) {
366 if (!ids) return false;
368 return _.some(ids, function(id) {
369 return hasPermission(id);
374 * Reload permissions for the current user on a page reload
377 function reloadPermissions() {
378 return $q(function(resolve, reject) {
379 getPermissions(motionCurrentUser.userProfileId)
380 .then(function(permissions) {
381 motionCurrentUser.permissions = permissions;
384 .catch(function(err) {
391 * Parse the crud permissions
392 * @param {String} crudPermissions The crud permissions as stored on the database (red : Read | Edit | Delete)
394 function parseCrudPermissions(crudPermissions) {
402 if (!crudPermissions) {
410 readOnly: _.includes(crudPermissions, 'r') && crudPermissions.length === 1 ? true : false,
411 canEdit: _.includes(crudPermissions, 'e') ? true : false,
412 canDelete: _.includes(crudPermissions, 'd') ? true : false
419 * Check if the user has valid permission on a specific resource
420 * @param {Number} sectionId The id of the parent section
421 * @param {Number} resourceId The id of the resource to check
423 function hasResourcePermission(sectionId, resourceId) {
424 return $q(function(resolve, reject) {
425 return api.userProfileSection
427 userProfileId: motionCurrentUser.userProfileId,
430 .$promise.then(function(entities) {
431 var section = entities.rows[0];
432 // If AutoAssociation is enabled it means that all resources are available
433 if (section.autoAssociation) return resolve();
434 // Checking if the current section does not require single resource association
435 var navigationItem = msNavigationService.getActiveItem().node;
436 if (navigationItem.permissions && navigationItem.permissions.association === false) return resolve();
437 // Retrieving sections's associated resources
438 return api.userProfileResource
440 sectionId: section.id,
443 .$promise.then(function(entities) {
444 var resources = entities.rows;
445 _.some(resources, ['resourceId', resourceId]) ? resolve() : reject();
448 .catch(function(err) {
449 reject('Error retrieving user profile permissions', err);
455 * Check if the user has valid permission on a section
456 * @param {Integer} id The section id
458 function hasSectionPermissions(id) {
459 return $q(function(resolve, reject) {
461 return reloadPermissions()
463 if (_.includes(motionCurrentUser.permissions, id)) {
468 .catch(function(err) {
475 * Check if the user has valid permission on all the sections specified
476 * @param {Array} sections The ids of the sections
477 * @return {Object} Object with each section as key
479 function hasSectionsPermissions(sections) {
480 return $q(function(resolve, reject) {
484 sections.forEach(function(key) {
489 return reloadPermissions()
491 sections.forEach(function(id) {
492 if (_.includes(motionCurrentUser.permissions, id)) {
498 .catch(function(err) {
506 * Check if the user has valid permissions on at least one section of a module
507 * @param {String} category The category name
509 function hasModulePermissions(category) {
510 return $q(function(resolve, reject) {
514 api.userProfileSection
516 userProfileId: motionCurrentUser.userProfileId
518 .$promise.then(function(entities) {
519 var sections = entities && entities.rows ? entities.rows : [];
520 if (!_.isEmpty(sections)) {
521 var enabledSections = _.filter(sections, function(section) {
522 return section.enabled;
524 resolve(_.some(enabledSections, ['category', category]));
529 .catch(function(err) {
537 * Check if the user has valid permissions on at least one section for each module
538 * @param {Array} categories The categories' names
539 * @return {Object} Object with each module as key
541 function hasModulesPermissions(categories) {
542 return $q(function(resolve, reject) {
546 categories.forEach(function(key) {
551 api.userProfileSection
553 userProfileId: motionCurrentUser.userProfileId
555 .$promise.then(function(entities) {
556 var sections = entities && entities.rows ? entities.rows : [];
557 if (!_.isEmpty(sections)) {
558 var enabledCategories = _(sections)
559 .filter(function(section) {
560 return section.enabled && _.includes(categories, section.category);
562 .uniqBy(function(section) {
563 return section.category;
565 .map(function(section) {
566 return section.category;
570 enabledCategories.forEach(function(key) {
578 .catch(function(err) {
586 * Return authentication type choose by user
588 function getAuthenticationType() {
589 return $window.localStorage['motion.authenticationtype'] || 'NONE';
592 function setAuthenticationType(authenticationType) {
593 $window.localStorage['motion.authenticationtype'] = authenticationType;
596 function loginSSO(provider) {
597 setAuthenticationType('SSO_LOGIN');
598 return '/api/auth/' + provider;