@@ -5,6 +5,9 @@ import { environment } from '../../environments/environement';
55import { UserData } from '../models/UserData' ;
66import { AlertService } from './alert.service' ;
77import { map , catchError } from 'rxjs/operators' ;
8+ import { log } from 'util' ;
9+ import { Router } from '@angular/router' ;
10+ import { JwtHelperService } from '@auth0/angular-jwt' ;
811
912@Injectable ( {
1013 providedIn : 'root'
@@ -14,11 +17,30 @@ export class AuthService {
1417
1518 private authStatus : boolean = false ;
1619 private url : string = environment . apiUrl ;
20+ private jwtHelper : JwtHelperService = new JwtHelperService ( ) ;
1721
18- constructor ( public http : HttpClient , public alertService : AlertService ) { }
22+ constructor ( public http : HttpClient , public alertService : AlertService , public router : Router ) { }
1923
20- isLoggedIn ( ) : boolean {
21- return this . authStatus ;
24+ isLoggedIn ( ) : Observable < boolean > {
25+ if ( this . jwtHelper . isTokenExpired ( localStorage . getItem ( 'token' ) ) ) {
26+ this . navToLogin ( ) ;
27+ }
28+ else {
29+ this . authStatus = true ;
30+ }
31+
32+ if ( ! this . authStatus ) {
33+ this . navToLogin ( ) ;
34+ }
35+
36+ return Observable . of ( this . authStatus ) ;
37+ }
38+
39+ navToLogin ( ) :void {
40+ this . authStatus = false ;
41+ this . router . navigate ( [ '/login' ] ) . catch ( error => {
42+ console . log ( error ) ;
43+ } ) ;
2244 }
2345
2446 login ( user :UserData ) : Observable < any > {
@@ -35,7 +57,9 @@ export class AuthService {
3557 }
3658
3759 logout ( ) : void {
38-
60+ localStorage . removeItem ( 'token' ) ;
61+ this . authStatus = false ;
62+ console . log ( "2" , this . authStatus ) ;
3963 }
4064
4165 register ( ) : void {
0 commit comments