UNPKG

zettapi_client

Version:

Client side CRUD operations in angular to use with zettapi_server rest api to get started quickly in any CMS project

229 lines (195 loc) 9.42 kB
app.factory('$auth', function ($http, $crypto, blockUI, $location, anonymousPages, $uibModalStack, customPages, routeDepth, $rootScope, Idle, zapi, $translate, $license) { function getUrlPaths(url) { var separator = '#/'; var start = url.indexOf(separator) + separator.length; var end = url.indexOf('?'); var shortURL = start > 2 ? (end > 0 ? url.substring(start, end - start) : url.substring(start)) : ""; var urlPaths = shortURL.split('/'); if (!(urlPaths instanceof Array)) urlPaths = []; return urlPaths; } var service = { currentUser: null, login: function (username, password, callback) { blockUI.start($translate.instant('api.services.auth.loginLoad')); return $http.post(zapi.serverUrl + '/api/session/login/', { username: username, password: $crypto.isMd5(password) ? password : $crypto.md5(password) }).then(function (response) { if (zapi.idle) Idle.watch(); service.currentUser = response.data.user; callback(); }).catch(function (response) { swal($translate.instant('api.services.auth.loginErrorTitle'), $translate.instant('api.services.auth.loginErrorContent'), "error"); //swal(loginErrorTitle, response.data, "danger"); callback(true); }).finally(function () { blockUI.stop(); }); }, logout: function () { $http.get(zapi.serverUrl + '/api/session/logout').then(function (response) { if (zapi.idle) Idle.unwatch(); service.currentUser = null; $rootScope.login = {}; $location.path('/'); $uibModalStack.dismissAll(); }); }, requestCurrentUser: function (callback) { if (service.isAuthenticated()) return callback(null, service.currentUser); $http.get(zapi.serverUrl + '/api/session/currentuser').then(function (response) { service.currentUser = response.data.user; callback(null, service.currentUser); }).catch(function (response) { service.currentUser = null; $rootScope.login = {}; callback(response); }); }, isAuthenticated: function () { return !!service.currentUser; }, activateAccount: function (rawCode, callback) { if (!rawCode) return callback(true); var codes = rawCode.split('&'); if (codes.length !== 2) return callback(true); blockUI.start($translate.instant('api.services.auth.activateAccountLoad')); $http.post(zapi.serverUrl + '/api/user/activate/', { email: codes[0], code: codes[1] }).then(function (response) { callback(null, response.data); }).catch(function (response) { callback(response.data); }).finally(function () { blockUI.stop(); }); }, resetPassword: function (email, username, callback) { blockUI.start($translate.instant("api.services.auth.resetPasswordLoad")); $http.post(zapi.serverUrl + '/api/user/resetpassword/', { email: email, username: username }).then(function (response) { swal($translate.instant('api.services.auth.resetPasswordSuccessTitle'), $translate.instant('api.services.auth.resetPasswordSuccessContent'), "success"); callback(); }).catch(function (response) { swal($translate.instant('api.services.auth.resetPasswordErrorTitle'), response.data, "error"); callback(response.data); }).finally(function () { blockUI.stop(); }); }, changePassword: function (user, newPassword1, newPassword2, callback) { if (!newPassword1) return callback($translate.instant('api.services.auth.changepasswordWrongPasswordContent')); if (newPassword1 !== newPassword2) { swal($translate.instant('api.services.auth.changepasswordWrongPasswordTitle'), $translate.instant('api.services.auth.changepasswordWrongPasswordContent'), "error"); return callback($translate.instant('api.services.auth.changepasswordWrongPasswordContent')); } user.newPassword = $crypto.md5(newPassword1); blockUI.start($translate.instant('api.services.auth.changepasswordLoad')); $http.post(zapi.serverUrl + '/api/user/changepassword/', user).then(function (response) { swal({ title: $translate.instant('api.services.auth.changepasswordSuccessTitle'), text: $translate.instant('api.services.auth.changepasswordSuccessContent'), type: "info", confirmButtonText: $translate.instant('api.services.auth.changepasswordSuccessBtnOk') }); callback(); }).catch(function (response) { swal($translate.instant('api.services.auth.changepasswordErrorTitle'), response.data, "error"); callback(response.data); }).finally(function () { blockUI.stop(); }); }, changePasswordUnencrypted: function (user, newPassword1, newPassword2, callback) { if (!newPassword1) return callback($translate.instant('api.services.auth.changepasswordWrongPasswordContent')); if (newPassword1 !== newPassword2) { swal($translate.instant('api.services.auth.changepasswordWrongPasswordTitle'), $translate.instant('api.services.auth.changepasswordWrongPasswordContent'), "error"); return callback($translate.instant('api.services.auth.changepasswordWrongPasswordContent')); } user.newPassword = $crypto.md5(newPassword1); user.newKey = newPassword1; blockUI.start($translate.instant('api.services.auth.changepasswordLoad')); $http.post(zapi.serverUrl + '/api/user/changepassword/', user).then(function (response) { swal({ title: $translate.instant('api.services.auth.changepasswordSuccessTitle'), text: $translate.instant('api.services.auth.changepasswordSuccessContent'), type: "info", confirmButtonText: $translate.instant('api.services.auth.changepasswordSuccessBtnOk') }); callback(); }).catch(function (response) { swal($translate.instant('api.services.auth.changepasswordErrorTitle'), response.data, "error"); callback(response.data); }).finally(function () { blockUI.stop(); }); }, isPageAnonymous: function (urlPaths) { if (!urlPaths) urlPaths = getUrlPaths($location.path()); return anonymousPages.some(function (anonymousPage) { return anonymousPage === urlPaths[0]; }); }, isPageCustom: function (urlPaths) { if (!urlPaths) urlPaths = getUrlPaths($location.path()); return customPages.find(function (customPage) { if (customPage.urlParts.length < urlPaths.length) return false; return !customPage.urlParts.some(function (part, i) { //ignore url wildcards by configuring the custom page with % if (part === '%') return false; return part !== urlPaths[i]; }); }); }, getNextRoute: function (callback) { return function (event, next, current) { var urlPaths = getUrlPaths(next); if (urlPaths.length === 0) return callback(); if (service.isPageAnonymous(urlPaths)) return callback(); //service.currentUser = null; service.requestCurrentUser(function (err, user) { $rootScope.login = (err ? {} : user) || {}; if (!$rootScope.login._id) return callback("Sem sessão iniciada. Isto pode ocorrer por motivos de inactividade, aceder à mesma conta noutro computador ou actualização recente ao servidor.", user); if (urlPaths[0] === 'profile') return callback(null, user); //authenticate and authorize custom pages var customPage = service.isPageCustom(urlPaths); if (customPage) { //check license if (typeof customPage.license !== 'undefined') { if (!$license.isLicensed(customPage.license)) $license.notify(customPage.license); } return callback(null, user); } //authenticate and authorize entity pages var entity = zapi.entityMap[urlPaths[routeDepth]]; if (!entity) return callback("A página que está a tentar consultar não existe", user); if (urlPaths.length <= routeDepth + 1) return callback("A página que está a tentar consultar não existe", user); var action = entity[urlPaths[routeDepth + 1]]; if (!action) return callback("A página que está a tentar consultar não existe", user); if (user.role.admin) return callback(null, user); if (action.admin) return callback("A página que está a tentar consultar não existe", user); //check license if (typeof entity.license !== 'undefined') { if (!$license.isLicensed(entity.license)) $license.notify(entity.license); } return callback(null, user); }); }; }, isAnonymous: function () { return !service.isLoggedIn(); }, isLoggedIn: function () { if (!service.currentUser) return false; return !!service.currentUser._id; }, isAdmin: function () { if (service.isLoggedIn()) return service.currentUser.role.admin; return false; }, hasClearance: function (level) { if (!service.currentUser) return false; if (!service.currentUser.role) return false; return service.currentUser.role.approvalLevel >= level; } }; return service; });