(function () { 'use strict'; angular.module('app').factory('user', ['$q', 'DSCacheFactory', '$http', 'config', 'myUsersDataContext', user]); angular.module('app').factory('userAuth', ['DSCacheFactory', '$injector', '$q', 'config', userAuth]); //service to manage user related stuff function user($q, DSCacheFactory, $http, config, myUsersDataContext) { var myIndividualFrameworksName = 'myIndividualFrameworks'; var allMyFrameworksName = 'allMyFrameworks'; var me = 'me'; var meCache = 'meCache'; var myFrameworksCache = 'myFrameworksCache'; var orgUserEndpoint = 'api/organisations/'; var uploadBucketSasName = 'uploadbucketsas'; var userDictionary = []; var orgs; // var dropboxOAuthName = 'dropboxoauth'; createMeCache(); createMyFrameworksCache(); var service = { getProfile: getProfile, getUserProfile: getUserProfile, updateLastActivity: updateLastActivity, getUserProfiles: getUserProfiles, getUserSimpleProfile: getUserSimpleProfile, getUsers: getUsers, getUsersOrgs: getUsersOrgs, // getDropboxOAuth: getDropboxOAuth, // setDropboxOAuth: setDropboxOAuth, editIndividualFrameworks: editIndividualFrameworks, getMyIndividualFrameworks: getMyIndividualFrameworks, getAllMyFrameworks: getAllMyFrameworks, getAllMyFrameworkAssignmentDeployments: getAllMyFrameworkAssignmentDeployments, getUploadBucketSasCached: getUploadBucketSasCached, getUploadBucketSas: getUploadBucketSas, getUploadBucketSasForContainer: getUploadBucketSasForContainer, getUploadBucketSasForContainerMyUsers: getUploadBucketSasForContainerMyUsers, getUploadBucketSasForUser: getUploadBucketSasForUser, getUserDetail: getUserDetail, setOnboardStatus: setOnboardStatus, getOnboards: getOnboards, getUsersIndividualFrameworks: getUsersIndividualFrameworks, getUserAccountSummary: getUserAccountSummary, getAssignedTaskCountForUser: getAssignedTaskCountForUser, getMyOffTheJobApprenticeship: getMyOffTheJobApprenticeship }; //we use DSCache to cache user's data function createMeCache() { var cache = DSCacheFactory(meCache, { storageMode: 'localStorage' }); cache.setOptions({ maxAge: 300000, deleteOnExpire: 'aggressive' }); } function createMyFrameworksCache() { var cache = DSCacheFactory(myFrameworksCache, { storageMode: 'localStorage' }); cache.setOptions({ maxAge: 30000, deleteOnExpire: 'aggressive' }); } ////get the oauth details fro Dropbox //function getDropboxOAuth() { // return DSCacheFactory.get(meCache).get(dropboxOAuthName); //} ////put the dropbox oauth details into the cache //function setDropboxOAuth(auth) { // return DSCacheFactory.get(meCache).put(dropboxOAuthName, auth); //} //get the Secure Access Token that allows the user to directly upload files to Microsoft Azure blob storage function getUploadBucketSas() { var request = $http({ method: "get", url: config.userRemoteServiceUrl + 'uploadbucket/sas' }); return (request.then(function (response) { DSCacheFactory.get(meCache).put(uploadBucketSasName, response.data); return response.data; }, handleError)); } //get the Secure Access Token that allows the user to directly upload files to Microsoft Azure blob storage function getUploadBucketSasForContainer(container) { var request = $http({ method: "get", url: config.myShowcaseSiteUrl + 'api/user/uploadbucket/sas/' + container }); return (request.then(function (response) { return response.data; }, handleError)); } //get the Secure Access Token that allows the user to directly upload files to Microsoft Azure blob storage function getUploadBucketSasForContainerMyUsers(container) { var request = $http({ method: "get", url: config.myusersUrl + 'api/account/uploadbucket/sas?containerName=' + container }); return (request.then(function (response) { return response.data; }, handleError)); } //get the Secure Access Token that allows the user to directly upload files to Microsoft Azure blob storage function getUploadBucketSasForUser(userId) { var request = $http({ method: "get", url: config.myShowcaseSiteUrl + 'api/user/uploadbucket/sas/' + "upload-" + userId }); return (request.then(function (response) { return response.data; }, handleError)); } //get the upload bucket SAS code from cache function getUploadBucketSasCached() { return DSCacheFactory.get(meCache).get(uploadBucketSasName); } return service; function getUsersIndividualFrameworks(userId) { var request = $http({ method: "get", url: config.myShowcaseSiteUrl + 'api/individualframeworks/user/' + userId }); return (request.then(function (response) { return response.data; }, handleError)); } function getMyIndividualFrameworks() { //is the data in cache var cache = DSCacheFactory.get(myFrameworksCache); if (cache) { var cached = DSCacheFactory.get(myFrameworksCache).get(myIndividualFrameworksName); if (cached) { var deferred = $q.defer(); deferred.resolve(cached); return deferred.promise; } } //no - so get from server var request = $http({ method: "get", url: config.userRemoteServiceUrl + 'frameworks/individual' }); return (request.then(function (response) { var theCache = DSCacheFactory.get(myFrameworksCache); if (!theCache) createMyFrameworksCache(); //add user data to the cache DSCacheFactory.get(myFrameworksCache).put(myIndividualFrameworksName, response.data); return response.data; }, handleError)); } function editIndividualFrameworks(editedFrameworks) { var request = $http({ method: "post", url: config.userRemoteServiceUrl + 'frameworks', data: editedFrameworks }); return (request.then(function () { var theCache = DSCacheFactory.get(myFrameworksCache); if (!theCache) createMyFrameworksCache(); //add user data to the cache return theCache.removeAll(); }, handleError)); } //get all the frameworks for this user function getAllMyFrameworks() { //is the data in cache var cache = DSCacheFactory.get(myFrameworksCache); if (cache) { var cached = DSCacheFactory.get(myFrameworksCache).get(allMyFrameworksName); if (cached) { var deferred = $q.defer(); deferred.resolve(cached); return deferred.promise; } } //its not in the cacahe so get from server return getMyIndividualFrameworks().then(function (individualFrameworks) { return myUsersDataContext.getAllOrgFrameworksInParentHierarchy().then(function (orgFrameworks) { //The list of frameworks that are visible to the user, based on self and org allocation values var visibleFrameworks = []; /* * Only make the users' individualframeworks that have either been 'self', 'group', or both allocated, visible */ for (var ind in individualFrameworks) { //initialise check flag var groupAllocated = false; //is it self allocated? var selfAllocated = individualFrameworks[ind].selfAllocated; //Check each of the org allocated frameworks to see if the user has it, //if so, set it to 'group' allocated for (var o in orgFrameworks) { if (orgFrameworks[o] == individualFrameworks[ind].id) { //has been allocated groupAllocated = true; //stop checking framework goto next break; } else { //not yet matched so is deallocated (at the moment) groupAllocated = false; } } //If it's self org group allocated, add it to the 'visible' list if (groupAllocated || selfAllocated) { visibleFrameworks.push({ id: individualFrameworks[ind].id, deactivated: false, groupAllocated: groupAllocated, selfAllocated: selfAllocated }); } } /* * Push orgallocated frameworks to the 'visible' list if the user doesn't have an individual framework for it yet * i.e. allocated org frameworks that the user has not accessed yet */ for (var i = 0; i < orgFrameworks.length; i++) { var alreadyPresent = false; for (var j = 0; j < individualFrameworks.length; j++) { if (individualFrameworks[j].id === orgFrameworks[i]) { alreadyPresent = true; break; } } if (!alreadyPresent) visibleFrameworks.push({ id: orgFrameworks[i], deactivated: false, groupAllocated: true, selfAllocated: false }); } var theCache = DSCacheFactory.get(myFrameworksCache); if (!theCache) createMyFrameworksCache(); //add user data to the cache DSCacheFactory.get(myFrameworksCache).put(allMyFrameworksName, visibleFrameworks); return visibleFrameworks; }); }); } //get all the deployed framework assignments for this user function getAllMyFrameworkAssignmentDeployments() { //url: 'https://mkm-apigateway-dev.azurewebsites.net/deployedassignment/formewithgroups', var request = $http({ method: "get", url: config.apigatewayUrl + 'deployedassignment/formewithgroups' }); return request.then(function (response) { return response.data.deploymentSummaries; }).catch(function (reason) { //TODO: log reason return []; }); } function getUsersOrgs(refresh) { if (orgs && !refresh) { return $q.resolve(orgs); } var request = $http({ method: "get", url: config.myusersUrl + orgUserEndpoint }); return (request.then(function (response) { orgs = response.data; return response.data; }, handleError)); } //get the user details function updateLastActivity(userId) { var request = $http({ method: "post", url: config.userProfileServiceUrl + 'lastactivity/' + userId, }); return (request.then(function (response) { return response.data; }, handleError)); } //get the user details function getProfile(refresh) { if (!refresh) { //is the data in cache var cache = DSCacheFactory.get(meCache); if (cache) { var cachedMe = DSCacheFactory.get(meCache).get(me); if (cachedMe) { var deferred = $q.defer(); deferred.resolve(cachedMe); return deferred.promise; } } } //no - so get from server var request = $http({ method: "get", url: config.userProfileServiceUrl + 'user', params: { includefields: "title,firstname,lastname,emailaddresses,gender,dateofbirth,country,avatarurl,avatartype,managedaccount,addresses,telephones,socialmedias,createdon,associatedUsers" } }); return (request.then(function (response) { return response.data; }, handleError)); } //get the user details function getUserProfile(userId) { //no - so get from server var request = $http({ method: "get", url: config.userProfileServiceUrl + 'user/' + userId, params: { includefields: "title,firstname,lastname,emailaddresses,gender,dateofbirth,country,avatarurl,avatartype,managedaccount,addresses,createdon,associatedUsers" } }); return (request.then(function (response) { return response.data; }, handleError)); } //get the user details of many users function getUserProfiles(userIds) { //no - so get from server var request = $http({ method: "post", url: config.userProfileServiceUrl + 'users', data: { userIds: userIds, includeFields: "title,firstname,lastname,emailaddresses,gender,dateofbirth,country,avatarurl,avatartype,managedaccount,addresses,createdon,associatedUsers" } }); return (request.then(function (response) { return response.data; }, handleError)); } //get the user details function getUserSimpleProfile(userId) { //no - so get from server var request = $http({ method: "get", url: config.userProfileServiceUrl + 'user/' + userId, params: { includefields: "firstname,lastname,avatarurl" } }); return (request.then(function (response) { return response.data; }, handleError)); } function getUsers(userIds) { var request = $http({ method: "post", url: config.usersRemoteServiceUrl + 'details', data: { userIds: userIds } }); return (request.then(function (response) { return response.data; }, handleError)); } function getUserDetail(userId) { var usersToReturn = []; if (userDictionary[userId]) { usersToReturn.push(userDictionary[userId]) } if (usersToReturn.length > 0) { return $q.resolve(usersToReturn); } var request = $http({ method: "post", url: config.usersRemoteServiceUrl + 'details', data: { userIds: [userId] } }); return (request.then(function (response) { for (i in response.data) { if (!userDictionary[response.data[i].id]) { userDictionary[response.data[i].id] = response.data[i] } } return response.data; }, handleError)); } function getUserAccountSummary(userId) { var request = $http({ method: "get", url: config.userRemoteServiceUrl + 'accountsummary/' + userId, }); return (request.then(function (response) { return response.data; }, handleError)); } function getAssignedTaskCountForUser(userId) { var request = $http({ method: "get", url: config.taskUrl + 'taskindividualassignments/' + userId + '/assigned', }); return (request.then(function (response) { return response.data; }, handleError)); } function setOnboardStatus(type, accepted) { var request = $http({ method: "post", url: config.myShowcaseSiteUrl + 'api/onboards/', data: { accepted: accepted, onBoardTypeName: type } }); return (request.then(function (response) { return response.data; }, handleError)); } function getOnboards(user) { var onboards = {}; if (config.myShowcaseSiteUrl) { var request = $http({ method: "get", url: config.myShowcaseSiteUrl + 'api/onboards', }); } else { var request = $http({ method: "get", url: 'api/onboards', }); } return (request.then(function (response) { for (var i in response.data) { onboards[response.data[i].onBoardTypeName] = response.data[i].accepted; } return onboards; }, handleError)); } //get all the deployed framework assignments for this user function getMyOffTheJobApprenticeship() { //url: 'https://mkm-apigateway-dev.azurewebsites.net/deployedassignment/formewithgroups', var request = $http({ method: "get", url: config.apigatewayUrl + 'offthejob/api/apprenticeships/reports/currentuser/offthejob?startDate=undefined&endDate=undefined' }); return request.then(function (response) { return response.data; }).catch(function (reason) { //TODO: log reason return []; }); } function handleError(response) { if ( !angular.isObject(response.data) || !response.data.message ) { return ($q.reject("An unknown error occurred.")); } // Otherwise, use expected error message. return ($q.reject(response.data.message)); } } //service to manage user authentication related stuff function userAuth(DSCacheFactory, $injector, $q, config) { var authTokenName = 'authtoken'; var authCache = 'authcache'; var roleTokenName = 'roletoken'; var roleCache = 'rolecache'; var canvasTokenName = 'canvasroletoken'; var canvasRoleCache = 'canvasrolecache'; //we cache the user's auth data using DSCacheFactory createAuthCache(); createRoleCache(); createCanvasCache(); function createAuthCache() { var cache = DSCacheFactory(authCache, { storageMode: 'localStorage' }); cache.setOptions({ maxAge: 604800000, deleteOnExpire: 'aggressive' }); } function createRoleCache() { var cache = DSCacheFactory(roleCache, { storageMode: 'localStorage' }); cache.setOptions({ maxAge: 604800000, deleteOnExpire: 'aggressive' }); } function createCanvasCache() { var cache = DSCacheFactory(canvasRoleCache, { storageMode: 'localStorage' }); cache.setOptions({ maxAge: 604800000, deleteOnExpire: 'aggressive' }); } var service = { getAuthToken: getAuthToken, setAuthToken: setAuthToken, getRoleToken: getRoleToken, setRoleToken: setRoleToken, refreshRoleToken: refreshRoleToken, getCanvasToken: getCanvasToken, setCanvasToken: setCanvasToken }; return service; //get the authentication (bearer) token for the user from the cache function getAuthToken() { var cache = DSCacheFactory.get(authCache); if(cache) return cache.get(authTokenName); return null; } //put the auth token into the cache function setAuthToken(auth) { var cache = DSCacheFactory.get(authCache); if (!cache) createAuthCache(); if (auth) localStorage.setItem(authTokenName, auth.access_token); return DSCacheFactory.get(authCache).put(authTokenName, auth); } //get the canvas authentication (bearer) token for the user from the cache function getCanvasToken() { var cache = DSCacheFactory.get(canvasRoleCache); if (cache) return cache.get(canvasTokenName); return null; } //put the canvas auth token into the cache function setCanvasToken(auth) { var cache = DSCacheFactory.get(canvasRoleCache); if (!cache) createCanvasCache(); return DSCacheFactory.get(canvasRoleCache).put(canvasTokenName, auth); } //get the role (bearer) token for the user from the cache function getRoleToken() { var cache = DSCacheFactory.get(roleCache); if (cache) return cache.get(roleTokenName); return null; } //put the role token into the cache function setRoleToken(role) { if (role) { // set the expiry date of the token role.expires_on = Date.now(); role.expires_on = role.expires_on + 30 * 60 * 1000; } var cache = DSCacheFactory.get(roleCache); if (!cache) createRoleCache(); if (role) localStorage.setItem(roleTokenName, role.token); return DSCacheFactory.get(roleCache).put(roleTokenName, role); } function refreshRoleToken(roleId) { // We need to use the $injector service to wire up the $http service // in order to resolve circular dependency issues var httpService = $injector.get('$http'); var request = httpService({ method: "get", url: rolesUrl + 'api/roletokens/' + config.appCode + '/role/' + roleId + '?cache=' + Date.now(), }); return (request.then(handleSuccess, handleError)); } function handleError(response) { // The API response from the server should be returned in a // nomralized format. However, if the request was not handled by the // server (or what not handles properly - ex. server error), then we // may have to normalize it on our end, as best we can. if ( !angular.isObject(response.data) || !response.data.message ) { return ($q.reject("An unknown error occurred.")); } // Otherwise, use expected error message. return ($q.reject(response.data.message)); } // I transform the successful response, unwrapping the application data // from the API response payload. function handleSuccess(response) { return (response.data); } } })();