salix/front/core/services/auth.js

107 lines
2.9 KiB
JavaScript
Raw Normal View History

import ngModule from '../module';
import UserError from 'core/lib/user-error';
/**
* Authentication service.
*
* @property {Boolean} loggedIn Whether the user is currently logged
*/
export default class Auth {
2022-09-21 13:15:19 +00:00
constructor($http, $q, $state, $transitions, $window, vnToken, vnModules, aclService, $location) {
Object.assign(this, {
$http,
2019-01-25 14:09:29 +00:00
$q,
$state,
$transitions,
$window,
vnToken,
vnModules,
aclService,
2022-09-21 13:15:19 +00:00
loggedIn: false,
$location
});
}
initialize() {
let criteria = {
2022-09-14 13:18:11 +00:00
to: state => !state.name.includes('login')
};
2022-09-21 13:15:19 +00:00
this.vnToken.set(this.$location.$$search.access_token, false);
console.log(this.$location.$$search.access_token, false);
this.$transitions.onStart(criteria, transition => {
if (this.loggedIn)
return true;
let redirectToLogin = () => {
2022-09-21 13:15:19 +00:00
// return transition.router.stateService.target('login');
};
2022-09-21 13:15:19 +00:00
if (this.vnToken.token || this) {
return this.loadAcls()
.then(() => true)
.catch(redirectToLogin);
} else
return redirectToLogin();
});
}
login(user, password, remember) {
2020-03-25 19:44:59 +00:00
if (!user) {
let err = new UserError('Please enter your username');
err.code = 'EmptyLogin';
return this.$q.reject(err);
}
let params = {
user,
password: password || undefined
};
return this.$http.post('Accounts/login', params).then(
2019-01-25 14:09:29 +00:00
json => this.onLoginOk(json, remember));
}
onLoginOk(json, remember) {
2022-09-21 13:15:19 +00:00
console.log(json.data.token);
this.vnToken.set(json.data.token, remember);
return this.loadAcls().then(() => {
let continueHash = this.$state.params.continue;
if (continueHash)
this.$window.location = continueHash;
else
this.$state.go('home');
});
}
logout() {
let promise = this.$http.post('Accounts/logout', null, {
headers: {Authorization: this.vnToken.token}
2019-01-25 16:05:53 +00:00
}).catch(() => {});
this.vnToken.unset();
this.loggedIn = false;
this.vnModules.reset();
this.aclService.reset();
2022-09-21 13:15:19 +00:00
// this.$state.go('login');
return promise;
}
loadAcls() {
return this.aclService.load()
.then(() => {
this.loggedIn = true;
this.vnModules.reset();
})
.catch(err => {
this.vnToken.unset();
throw err;
});
}
}
2022-09-21 13:15:19 +00:00
Auth.$inject = ['$http', '$q', '$state', '$transitions', '$window', 'vnToken', 'vnModules', 'aclService', '$location'];
ngModule.service('vnAuth', Auth);