Created
January 31, 2019 13:01
-
-
Save matheusmurta/2c685ae47dad88590729e8902ca0ebc6 to your computer and use it in GitHub Desktop.
Angular 7 com Json Web Token
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 { CanActivate } from '@angular/router'; | |
import { Observable } from 'rxjs'; | |
import { AuthService } from '../services/auth.service'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class AuthGuard implements CanActivate { | |
constructor(private authService: AuthService) { } | |
canActivate(): Observable<boolean> { | |
return this.authService.autenticado$; | |
} | |
} |
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 { Observable, BehaviorSubject } from 'rxjs'; | |
import { map, finalize } from 'rxjs/operators'; | |
import * as jwtDecode from 'jwt-decode'; | |
import { TokenService } from './token.service'; | |
import { Usuario } from '../interfaces/usuario'; | |
import { environment } from '../../environments/environment'; | |
import { TokenApi } from '../interfaces/respostas/token-api'; | |
import { UsuarioService } from './usuario.service'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class AuthService { | |
private _autenticado: BehaviorSubject<boolean>; | |
public readonly autenticado$: Observable<boolean>; | |
constructor( | |
private http: HttpClient, | |
private tokenService: TokenService, | |
private usuarioService: UsuarioService | |
) { | |
this._autenticado = new BehaviorSubject(false); | |
this.autenticado$ = this._autenticado.asObservable(); | |
} | |
logar(usuario: Usuario): Observable<boolean> { | |
const url = `${environment.linguagensApiUrl}/auth/login`; | |
return this.http.post<TokenApi>(url, usuario).pipe( | |
map((resposta: TokenApi) => { | |
if (!this.criarSessao(resposta.token)) { | |
throw new Error(); | |
} | |
return true; | |
}) | |
); | |
} | |
deslogar(): Observable<TokenApi> { | |
const url = `${environment.linguagensApiUrl}/auth/logout`; | |
return this.http.post<TokenApi>(url, {}).pipe( | |
finalize(() => { this.resetarSessao(); }) | |
); | |
} | |
criarSessao(token: string): boolean { | |
try { | |
const usuario: Usuario = jwtDecode(token); | |
this.usuarioService.setUsuario(usuario); | |
this.tokenService.token = token; | |
this._autenticado.next(true); | |
return true; | |
} catch (err) { | |
return false; | |
} | |
} | |
resetarSessao() { | |
this.tokenService.resetarToken(); | |
if (this._autenticado.value) { | |
this._autenticado.next(false); | |
} | |
} | |
} |
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 { | |
HttpInterceptor, | |
HttpRequest, | |
HttpHandler, | |
HttpEvent, | |
HttpErrorResponse | |
} from '@angular/common/http'; | |
import { catchError } from 'rxjs/operators'; | |
import { Observable, throwError } from 'rxjs'; | |
import { AuthService } from '../services/auth.service'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class InvalidTokenApiService implements HttpInterceptor { | |
constructor(private authService: AuthService) { } | |
intercept( | |
req: HttpRequest<any>, | |
next: HttpHandler | |
): Observable<HttpEvent<any>> { | |
return next.handle(req).pipe( | |
catchError((errorResponse: HttpErrorResponse) => { | |
if (errorResponse.status === 401) { | |
this.authService.resetarSessao(); | |
} | |
return throwError(errorResponse); | |
}) | |
); | |
} | |
} |
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 { CanActivate } from '@angular/router'; | |
import { Observable } from 'rxjs'; | |
import { map } from 'rxjs/operators'; | |
import { AuthService } from '../services/auth.service'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class NotAuthGuard implements CanActivate { | |
constructor(private authService: AuthService) { } | |
canActivate(): Observable<boolean> { | |
return this.authService.autenticado$.pipe( | |
map(autenticado => { | |
return !autenticado; | |
}) | |
); | |
} | |
} |
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 { | |
HttpInterceptor, | |
HttpRequest, | |
HttpHandler, | |
HttpEvent, | |
HttpErrorResponse | |
} from '@angular/common/http'; | |
import { catchError } from 'rxjs/operators'; | |
import { Observable, throwError } from 'rxjs'; | |
import { AuthService } from '../services/auth.service'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class InvalidTokenApiService implements HttpInterceptor { | |
constructor(private authService: AuthService) { } | |
intercept( | |
req: HttpRequest<any>, | |
next: HttpHandler | |
): Observable<HttpEvent<any>> { | |
return next.handle(req).pipe( | |
catchError((errorResponse: HttpErrorResponse) => { | |
if (errorResponse.status === 401) { | |
this.authService.resetarSessao(); | |
} | |
return throwError(errorResponse); | |
}) | |
); | |
} | |
} |
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
export interface TokenApi { | |
token: string; | |
} |
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 { TOKEN_STORAGE } from '../../environments/environment'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class TokenService { | |
get token() { | |
return localStorage.getItem(TOKEN_STORAGE); | |
} | |
set token(token: string) { | |
localStorage.setItem(TOKEN_STORAGE, token); | |
} | |
resetarToken() { | |
localStorage.removeItem(TOKEN_STORAGE); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment