salix/front/core/services/auth.js

106 lines
2.8 KiB
JavaScript

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 {
constructor($http, $state, $transitions, $window, vnToken, vnModules, aclService) {
Object.assign(this, {
$http,
$state,
$transitions,
$window,
vnToken,
vnModules,
aclService,
token: null,
loggedIn: false,
dataLoaded: false
});
}
initialize() {
this.loggedIn = this.vnToken.token != null;
let criteria = {
to: state => state.name != 'login'
};
this.$transitions.onStart(criteria, transition => {
if (!this.loggedIn) {
let params = {continue: this.$window.location.hash};
return transition.router.stateService.target('login', params);
}
if (!this.dataLoaded) {
this.resetData();
this.dataLoaded = true;
return this.aclService.load();
}
return true;
});
}
login(user, password, remember) {
if (!user)
throw new UserError('Please insert your user and password');
let params = {
user,
password: password || undefined
};
return this.$http.post('/api/Accounts/login', params).then(
json => this.onLoginOk(json, remember),
json => this.onLoginErr(json)
);
}
onLoginOk(json, remember) {
this.resetData();
this.vnToken.set(json.data.token, remember);
this.loggedIn = true;
let continueHash = this.$state.params.continue;
if (continueHash)
this.$window.location = continueHash;
else
this.$state.go('home');
}
onLoginErr(json) {
let message;
switch (json.status) {
case 401:
message = 'Invalid credentials';
break;
case -1:
message = 'Can\'t contact with server';
break;
default:
message = 'Something went wrong';
}
throw new UserError(message);
}
logout() {
let promise = this.$http.post('/api/Accounts/logout', null, {
headers: {Authorization: this.vnToken.token}
});
this.vnToken.unset();
this.loggedIn = false;
this.resetData();
this.$state.go('login');
return promise;
}
resetData() {
this.aclService.reset();
this.vnModules.reset();
this.dataLoaded = false;
}
}
Auth.$inject = ['$http', '$state', '$transitions', '$window', 'vnToken', 'vnModules', 'aclService'];
ngModule.service('vnAuth', Auth);