Created
April 30, 2021 18:21
-
-
Save walidum/43f508182271fe93b52bc0a45b9b4eb4 to your computer and use it in GitHub Desktop.
authentication.service.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { HttpClient } from '@angular/common/http'; | |
import { BehaviorSubject, Observable } from 'rxjs'; | |
import { map } from 'rxjs/operators'; | |
import { environment } from '@environments/environment'; | |
import { User } from '@app/_models'; | |
@Injectable({ providedIn: 'root' }) | |
export class AuthenticationService { | |
private currentUserSubject: BehaviorSubject<User>; | |
public currentUser: Observable<User>; | |
constructor(private http: HttpClient) { | |
this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser'))); | |
this.currentUser = this.currentUserSubject.asObservable(); | |
} | |
public get currentUserValue(): User { | |
return this.currentUserSubject.value; | |
} | |
login(username: string, password: string) { | |
return this.http.post<any>(`${environment.apiUrl}/users/authenticate`, { username, password }) | |
.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); | |
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment