'use strict'; var serviceId = 'auth'; angular.module('app').factory(serviceId, ['breeze', 'common', 'commonConfig', 'config', '$http', '$q', '$window', '$location', 'datacontext', 'userAuth', '$rootScope', 'stateService', 'DSCacheFactory', 'rolesService', auth]); function auth(breeze, common, commonConfig, config, $http, $q, $window, $location, datacontext, userAuth, $rootScope, stateService, DSCacheFactory, rolesService) { var getLogFn = common.logger.getLogFn; var logError = getLogFn(serviceId, "error"); var logInfo = getLogFn(serviceId); var verifying = false; $rootScope.systemId = $location.search().systemId; var service = { authenticate: authenticate, register: register, getAccessToken: getAccessToken, setAccessToken: setAccessToken, logOut: logOut, fillAuthData: fillAuthData, getCurrentUser: getCurrentUser, acceptAgreement: acceptAgreement, getAgreements: getAgreements, acceptAllAgreements: acceptAllAgreements }; return service; //get the bearer token for the user function getAccessToken() { return userAuth.getAuthToken(); } //set the bearer token for the user function setAccessToken(tokenData) { if (tokenData && tokenData.access_token) userAuth.setAuthToken(tokenData); } function delete_cookie(name) { document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;'; }; //fill in the user data from the token function fillAuthData() { var data = getAccessToken(); if ($location.$$path === "/signin/lockedOut") { config.isLockedOut = true; } if ($location.$$path === "/signin/failed") { var emailCookie = document.cookie.match('(^|;) ?' + ' mmu' + '=([^;]*)(;|$)'); if (emailCookie) { window.location.href = '/#/mmu?signin=failed'; } delete_cookie('mmu'); } if (data) { if (emailToVerify && !verifying) { verifying = true; var email = encodeURIComponent(emailToVerify); var url = config.realm + 'api/emailverifications?emailAddress=' + email; var newToken = data; return $http({ method: 'get', url: url, headers: { 'Authorization': 'Bearer ' + data.access_token }, }). success(function (userId, status, headers) { delete newToken.emailToVerify; setAccessToken(newToken); config.authenticated = true; config.uploadBucketName = 'upload-' + userId; }). error(function (data, status, headers, config) { logError("User email verification failed (" + status + ")", url, true); }); } if (data.access_token) { config.authenticated = true; if (!data.userId) getCurrentUser(); else { config.userId = data.userId; config.accessLevel = 1; config.firstName = data.firstName; config.lastName = data.lastName; config.email = data.email; config.uploadBucketName = 'upload-' + data.userId; config.customSignIn = data.customSignIn; config.orgs = data.orgs; config.orgAdmin = data.orgAdmin; config.systemAdmin = data.systemAdmin; stateService.handleState(); } } } return data; } function setAuthenticationData(data) { setAccessToken(data); fillAuthData(); } function logOut() { datacontext.clearAllCachedData(); var redirect = '/'; if (config.customSignIn && config.customSignIn !== '') redirect = redirect + config.customSignIn; config.userId = ''; config.authenticated = false; config.accessLevel = 0; config.firstName = ''; config.lastName = ''; config.customSignIn = ''; config.orgAdmin = ''; config.systemAdmin = ''; config.orgs = []; common.$broadcast(commonConfig.config.logoutSuccessEvent, { accessLevel: config.accessLevel }); $location.path(redirect); } function acceptAgreement(agreementId) { var url = config.realm + 'api/Account/Agree/' + agreementId; return $http({ method: 'POST', url: url, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }). success(function (data, status, headers) { logInfo('Agreement Accepted'); }).error(function (data, status, headers, config) { logError("Accept Agreement Failed (" + status + ")", url, true); }); } function acceptAllAgreements() { var promises = []; getAgreements().forEach(function (agreement) { promises.push(acceptAgreement(agreement.Id)); }); return $q.all(promises).then(function (eventArgs) { var accessToken = getAccessToken(); if (accessToken) { accessToken.agreements = null; setAccessToken(accessToken); } getCurrentUser().then(function () { $location.path('/yourframeworks'); }); }); } function getAgreements() { var accessToken = getAccessToken(); if (accessToken) return JSON.parse(accessToken.agreements); return []; } function getCurrentUser(reload) { var url = config.realm + 'api/Account/' + config.applicationId; return $http({ method: 'GET', url: url }). success(function (data, status, headers) { var accessToken = getAccessToken(); if (accessToken) { accessToken.userId = data.userId; accessToken.accessLevel = 1; accessToken.firstName = data.firstName; accessToken.lastName = data.lastName; accessToken.email = data.email; accessToken.agreements = data.agreements; accessToken.customSignIn = data.signIn; accessToken.orgs = data.orgs; accessToken.orgAdmin = data.orgAdmin; accessToken.systemAdmin = data.systemAdmin; setAccessToken(accessToken); fillAuthData(); if (data.agreements) { config.authenticated = false; $rootScope.$broadcast(commonConfig.config.logoutSuccessEvent, { accessLevel: config.accessLevel }); $location.path('/account/agreements'); } else { config.authenticated = true; $rootScope.$broadcast(commonConfig.config.loginSuccessEvent, { accessLevel: config.accessLevel }); logInfo('Got User Data'); if (reload) { $location.path('/'); $window.location.reload(); } } } }). error(function (data, status, headers, config) { logError("User Data failed (" + status + ")", url, true); }); } function authenticate(username, password, reload) { //get a bearer token from the myusers endpoint var url = config.realm + 'Token'; return $http({ method: 'POST', url: url, data: $.param({ grant_type: "password", username: username, password: password, state:config.state }), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }). success(function (data, status, headers) { logInfo('Authentication succeeded'); //save the data setAuthenticationData(data); return getCurrentUser().then(function () { if (reload) { $window.location.href = '/'; } }); }). error(function (data, status, headers, config) { logError("Authentication failed (" + status + ")", url, true); }); } //register a new user function register(user) { var url = config.realm + 'api/Account/Register'; return $http({ method: 'POST', url: url, data: { ApplicationId: config.applicationId, FirstName: user.firstName, LastName: user.lastName, Email: user.email, Password: user.password, OrganisationId: user.organisation, AppCode: config.appCode }, headers: { 'Content-Type': 'application/json' } }). success(function (data, status, headers, config) { logInfo('Registration succeeded'); //now authenticate the newly created user return authenticate(user.email, user.password, false).then(function (userData) { $window.location.href = '/'; }); }). error(function (data, status, headers, config) { if (data && data.errorCode && data.errorCode === "0") { } else logError("Registration failed (" + status + ")", url, true); }); } };