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

44 lines
1.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';
@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;
}
}