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';
|
|
|
|
|
|
|
|
@Injectable({
|
|
|
|
providedIn: 'root'
|
|
|
|
})
|
|
|
|
export class LoginService implements CanActivate {
|
|
|
|
|
|
|
|
private loggedIn = false;
|
|
|
|
|
|
|
|
constructor(
|
|
|
|
private api: ApiService,
|
|
|
|
private storage: LocalStorageService
|
2020-05-22 12:52:17 +02:00
|
|
|
) {
|
|
|
|
this.login();
|
|
|
|
}
|
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));
|
|
|
|
}
|
2020-05-20 10:07:34 +02:00
|
|
|
this.api.get('/authorized').subscribe((data: any) => {
|
|
|
|
if (data.status === 'Authorization successful') {
|
|
|
|
this.loggedIn = true;
|
|
|
|
resolve(true);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
this.loggedIn = false;
|
|
|
|
this.storage.remove('basicAuth');
|
|
|
|
resolve(false);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
() => {
|
|
|
|
this.loggedIn = false;
|
|
|
|
this.storage.remove('basicAuth');
|
|
|
|
resolve(false);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-05-22 12:52:17 +02:00
|
|
|
canActivate(route: ActivatedRouteSnapshot = null, state: RouterStateSnapshot = null) {
|
2020-05-20 10:07:34 +02:00
|
|
|
return this.loggedIn;
|
|
|
|
}
|
|
|
|
}
|