definma-ui/src/app/services/login.service.ts

88 lines
2.2 KiB
TypeScript
Raw Normal View History

2020-05-20 10:07:34 +02:00
import { Injectable } from '@angular/core';
import {ApiService} from './api.service';
import {ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot} from '@angular/router';
import {LocalStorageService} from 'angular-2-local-storage';
import {Observable} from 'rxjs';
2020-05-20 10:07:34 +02:00
@Injectable({
providedIn: 'root'
})
export class LoginService implements CanActivate {
2020-07-27 17:52:03 +02:00
private maintainPaths = ['templates'];
private loggedIn;
2020-07-27 17:52:03 +02:00
private level;
2020-05-20 10:07:34 +02:00
constructor(
private api: ApiService,
private storage: LocalStorageService
2020-05-22 12:52:17 +02:00
) {
2020-05-22 12:52:17 +02:00
}
2020-05-20 10:07:34 +02:00
2020-05-22 12:52:17 +02:00
login(username = '', password = '') {
2020-05-20 10:07:34 +02:00
return new Promise(resolve => {
2020-05-22 12:52:17 +02:00
if (username !== '') {
this.storage.set('basicAuth', btoa(username + ':' + password));
}
this.api.get('/authorized', (data: any, error) => {
if (!error) {
2020-05-20 10:07:34 +02:00
if (data.status === 'Authorization successful') {
this.loggedIn = true;
2020-07-27 17:52:03 +02:00
this.level = data.level;
2020-05-20 10:07:34 +02:00
resolve(true);
} else {
2020-05-20 10:07:34 +02:00
this.loggedIn = false;
this.storage.remove('basicAuth');
resolve(false);
}
} else {
2020-05-20 10:07:34 +02:00
this.loggedIn = false;
this.storage.remove('basicAuth');
resolve(false);
}
});
2020-05-20 10:07:34 +02:00
});
}
logout() {
this.storage.remove('basicAuth');
this.loggedIn = false;
}
canActivate(route: ActivatedRouteSnapshot = null, state: RouterStateSnapshot = null): Observable<boolean> {
return new Observable<boolean>(observer => {
2020-07-27 17:52:03 +02:00
const isMaintainPath = this.maintainPaths.indexOf(route.url[0].path) >= 0;
if (!isMaintainPath || (isMaintainPath && this.isMaintain)) {
if (this.loggedIn === undefined) {
this.login().then(res => {
observer.next(res as any);
observer.complete();
});
}
else {
observer.next(this.loggedIn);
observer.complete();
2020-07-27 17:52:03 +02:00
}
}
else {
2020-07-27 17:52:03 +02:00
observer.next(false);
observer.complete();
}
});
2020-05-20 10:07:34 +02:00
}
2020-07-13 10:52:10 +02:00
get isLoggedIn() {
return this.loggedIn;
}
2020-07-27 17:52:03 +02:00
get isMaintain() {
return this.level === 'maintain' || this.level === 'admin';
}
get username() {
return atob(this.storage.get('basicAuth')).split(':')[0];
}
2020-05-20 10:07:34 +02:00
}