|
| 1 | +import { |
| 2 | + GoogleLoginProvider, |
| 3 | + SocialAuthService, |
| 4 | + SocialUser, |
| 5 | +} from '@abacritt/angularx-social-login'; |
| 6 | +import { Injectable } from '@angular/core'; |
| 7 | +import { Router } from '@angular/router'; |
| 8 | +import { BehaviorSubject, Observable } from 'rxjs'; |
| 9 | + |
| 10 | +@Injectable({ |
| 11 | + providedIn: 'root', |
| 12 | +}) |
| 13 | +export class AuthService { |
| 14 | + private isAuthenticatedSubject: BehaviorSubject<boolean> = |
| 15 | + new BehaviorSubject<boolean>(false); |
| 16 | + public isAuthenticated$: Observable<boolean> = |
| 17 | + this.isAuthenticatedSubject.asObservable(); |
| 18 | + |
| 19 | + public loginUserSubject: BehaviorSubject<SocialUser> = |
| 20 | + new BehaviorSubject<SocialUser>(new SocialUser()); |
| 21 | + public loginUser$: Observable<SocialUser> = |
| 22 | + this.loginUserSubject.asObservable(); |
| 23 | + |
| 24 | + constructor(private authService: SocialAuthService, private router: Router) { |
| 25 | + this.authService.authState.subscribe((user) => { |
| 26 | + console.log('user', user); |
| 27 | + this.loginUserSubject.next(user); |
| 28 | + if (user) this.login(user?.idToken); |
| 29 | + }); |
| 30 | + // On Page refresh |
| 31 | + if (this.isAuthenticated()) { |
| 32 | + this.isAuthenticatedSubject.next(true); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + login(token: string): void { |
| 37 | + localStorage.setItem('token', token); |
| 38 | + this.isAuthenticatedSubject.next(true); |
| 39 | + } |
| 40 | + |
| 41 | + logout(): void { |
| 42 | + localStorage.removeItem('token'); |
| 43 | + this.isAuthenticatedSubject.next(false); |
| 44 | + this.authService.signOut(); |
| 45 | + this.router.navigate(['/login']); |
| 46 | + } |
| 47 | + |
| 48 | + isAuthenticated(): boolean { |
| 49 | + const token = localStorage.getItem('token'); |
| 50 | + return !!token; |
| 51 | + } |
| 52 | + |
| 53 | + getToken(): string { |
| 54 | + return localStorage.getItem('token') || ''; |
| 55 | + } |
| 56 | + |
| 57 | + refreshToken(): void { |
| 58 | + this.authService.signIn(GoogleLoginProvider.PROVIDER_ID); |
| 59 | + // this.authService.refreshAuthToken(GoogleLoginProvider.PROVIDER_ID); |
| 60 | + } |
| 61 | +} |
0 commit comments