44 lines
1.2 KiB
TypeScript
44 lines
1.2 KiB
TypeScript
![]() |
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
|
||
|
) { }
|
||
|
|
||
|
login(username, password) {
|
||
|
return new Promise(resolve => {
|
||
|
this.storage.set('basicAuth', btoa(username + ':' + password));
|
||
|
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);
|
||
|
});
|
||
|
});
|
||
|
}
|
||
|
|
||
|
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
|
||
|
return this.loggedIn;
|
||
|
}
|
||
|
}
|