|
| 1 | +// Modified from https://jasonwatmore.com/post/2022/11/15/angular-14-jwt-authentication-example-tutorial#login-component-ts |
| 2 | +import { Injectable } from '@angular/core'; |
| 3 | +import { Router } from '@angular/router'; |
| 4 | +import { HttpClient } from '@angular/common/http'; |
| 5 | +import { BehaviorSubject, Observable } from 'rxjs'; |
| 6 | +import { map, switchMap } from 'rxjs/operators'; |
| 7 | +import { UServRes } from '../_models/user.service.model'; |
| 8 | +import { User } from '../_models/user.model'; |
| 9 | +import { ApiService } from './api.service'; |
| 10 | + |
| 11 | +@Injectable({ providedIn: 'root' }) |
| 12 | +export class AuthenticationService extends ApiService { |
| 13 | + protected apiPath = 'user'; |
| 14 | + |
| 15 | + private userSubject: BehaviorSubject<User | null>; |
| 16 | + public user$: Observable<User | null>; |
| 17 | + |
| 18 | + constructor( |
| 19 | + private router: Router, |
| 20 | + private http: HttpClient, |
| 21 | + ) { |
| 22 | + super(); |
| 23 | + const userData = localStorage.getItem('user'); |
| 24 | + this.userSubject = new BehaviorSubject(userData ? JSON.parse(userData) : null); |
| 25 | + this.user$ = this.userSubject.asObservable(); |
| 26 | + } |
| 27 | + |
| 28 | + public get userValue() { |
| 29 | + return this.userSubject.value; |
| 30 | + } |
| 31 | + |
| 32 | + login(username: string, password: string) { |
| 33 | + console.log('login', `${this.apiUrl}/auth/login`); |
| 34 | + return this.http |
| 35 | + .post<UServRes>( |
| 36 | + `${this.apiUrl}/auth/login`, |
| 37 | + { username: username, password: password }, |
| 38 | + { observe: 'response' }, |
| 39 | + ) |
| 40 | + .pipe( |
| 41 | + map(response => { |
| 42 | + // store user details and jwt token in local storage to keep user logged in between page refreshes |
| 43 | + let user = null; |
| 44 | + if (response.body) { |
| 45 | + const { id, username, email, accessToken, isAdmin, createdAt } = response.body.data; |
| 46 | + user = { id, username, email, accessToken, isAdmin, createdAt }; |
| 47 | + } |
| 48 | + localStorage.setItem('user', JSON.stringify(user)); |
| 49 | + this.userSubject.next(user); |
| 50 | + return user; |
| 51 | + }), |
| 52 | + ); |
| 53 | + } |
| 54 | + |
| 55 | + createAccount(username: string, email: string, password: string) { |
| 56 | + return this.http |
| 57 | + .post<UServRes>( |
| 58 | + `${this.apiUrl}/users`, |
| 59 | + { username: username, email: email, password: password }, |
| 60 | + { observe: 'response' }, |
| 61 | + ) |
| 62 | + .pipe(switchMap(() => this.login(username, password))); // auto login after registration |
| 63 | + } |
| 64 | + |
| 65 | + logout() { |
| 66 | + // remove user from local storage to log user out |
| 67 | + localStorage.removeItem('user'); |
| 68 | + this.userSubject.next(null); |
| 69 | + this.router.navigate(['/account/login']); |
| 70 | + } |
| 71 | +} |
0 commit comments