120. Creating Interceptor (#14 Section 16: Interceptor)

This commit is contained in:
Art
2021-09-13 20:35:37 +03:00
parent 22d922f3a0
commit b13c73ff24
3 changed files with 60 additions and 10 deletions

View File

@ -0,0 +1,49 @@
import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs';
import {environment} from "../../environments/environment";
import {AuthenticationService} from "../service/authentication.service";
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
private publicUrlPatterns: string[] = [];
private host: string = environment.apiUrl;
constructor(private authenticationService: AuthenticationService) {
let publicUrlsSpringPatterns: string[] = environment.publicUrls;
let hostPattern = this.host.replace("/", "\/");
for (const urlPattern of publicUrlsSpringPatterns) {
let newUrlPattern = urlPattern
.replace('/**', "\/.*")
.replace('/*', '\/[A-Za-z0-9\-\.]+')
+"$";
this.publicUrlPatterns.push(hostPattern + newUrlPattern);
}
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (this.isRequestUrlMatches(request.url)) {
request = this.injectAuthToken(request);
}
return next.handle(request);
}
private injectAuthToken(request: HttpRequest<any>) {
this.authenticationService.loadToken();
const token = this.authenticationService.getToken();
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`
}
});
return request;
}
public isRequestUrlMatches(requestUrl: string): boolean {
return requestUrl.includes(this.host) &&
!this.publicUrlPatterns.some(urlPattern => requestUrl.match(urlPattern));
}
}

View File

@ -6,14 +6,14 @@ import {Observable} from "rxjs";
import {User} from "../model/user";
import {JwtHelperService} from "@auth0/angular-jwt";
const USER_STORAGE_KEY = "user";
const JWT_TOKEN_STORAGE_KEY = "jwt-token";
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
public USER_STORAGE_KEY = "user";
public JWT_TOKEN_STORAGE_KEY = "jwt-token";
private host: string = environment.apiUrl;
private token: string | null;
private loggedInUser: string | null;
@ -38,26 +38,26 @@ export class AuthenticationService {
public logout(): void {
this.token = null;
this.loggedInUser = null;
this.storage.removeItem(JWT_TOKEN_STORAGE_KEY);
this.storage.removeItem(USER_STORAGE_KEY);
this.storage.removeItem(this.JWT_TOKEN_STORAGE_KEY);
this.storage.removeItem(this.USER_STORAGE_KEY);
this.storage.removeItem("users");
}
public saveToken(token: string): void {
this.token = token;
this.storage.setItem(JWT_TOKEN_STORAGE_KEY, token);
this.storage.setItem(this.JWT_TOKEN_STORAGE_KEY, token);
}
public loadToken(): void {
this.token = this.storage.getItem(JWT_TOKEN_STORAGE_KEY);
this.token = this.storage.getItem(this.JWT_TOKEN_STORAGE_KEY);
}
public addUserToLocalStorage(user: User) {
this.storage.setItem(USER_STORAGE_KEY, JSON.stringify(user));
this.storage.setItem(this.USER_STORAGE_KEY, JSON.stringify(user));
}
public getUserFromLocalStorage(): User {
let userJson = this.storage.getItem(USER_STORAGE_KEY);
let userJson = this.storage.getItem(this.USER_STORAGE_KEY);
return JSON.parse(userJson!);
}

View File

@ -4,7 +4,8 @@
export const environment = {
production: false,
apiUrl: 'http://localhost:8080'
apiUrl: 'http://localhost:8080',
publicUrls: ['/user/login', '/user/register', '/user/*/image/**', '/user/image/**']
};
/*