64 lines
1.9 KiB
TypeScript
64 lines
1.9 KiB
TypeScript
import { Injectable } from '@angular/core';
|
|
import { HttpClient } from '@angular/common/http';
|
|
|
|
import { BehaviorSubject, Observable } from 'rxjs';
|
|
import { map } from 'rxjs/operators';
|
|
|
|
import { User } from '../models/user';
|
|
import { BaseService } from './base.service';
|
|
import { DateService } from './date.service';
|
|
|
|
|
|
@Injectable({
|
|
providedIn: 'root'
|
|
})
|
|
export class AuthenticationService extends BaseService {
|
|
private currentUserSubject: BehaviorSubject<User>;
|
|
public currentUser: Observable<User>;
|
|
|
|
constructor(private http: HttpClient, private dateService: DateService) {
|
|
super();
|
|
|
|
this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
|
|
this.currentUser = this.currentUserSubject.asObservable();
|
|
}
|
|
|
|
public get currentUserValue(): User {
|
|
const tmp = localStorage.getItem('currentUser');
|
|
if (tmp) {
|
|
const storedUser = JSON.parse(tmp);
|
|
if (new Date().getTime() > storedUser.expired) {
|
|
localStorage.removeItem('currentUser');
|
|
}
|
|
}
|
|
|
|
return this.currentUserSubject.value;
|
|
}
|
|
|
|
login(username: string, password: string) {
|
|
const bodyLogin = {
|
|
login: username,
|
|
password: password
|
|
};
|
|
|
|
return this.http.post<any>(`${this.apiUrl}/User/Authenticate`, bodyLogin, {
|
|
headers: this.headers
|
|
})
|
|
.pipe(map(user => {
|
|
// store user details and basic auth credentials in local storage to keep user logged in between page refreshes
|
|
user.authdata = window.btoa(username + ':' + password);
|
|
user.expired = this.dateService.AddDays(new Date(), 1).getTime();
|
|
|
|
localStorage.setItem('currentUser', JSON.stringify(user));
|
|
this.currentUserSubject.next(user);
|
|
return user;
|
|
}));
|
|
}
|
|
|
|
logout() {
|
|
// remove user from local storage to log user out
|
|
localStorage.removeItem('currentUser');
|
|
this.currentUserSubject.next(null);
|
|
}
|
|
}
|