2020-08-29 10:43:35 +02:00
|
|
|
import { Injectable } from '@angular/core';
|
2020-09-29 13:21:40 +02:00
|
|
|
import { MatDialog } from '@angular/material/dialog';
|
2020-08-29 10:43:35 +02:00
|
|
|
import { Request, UnaryInterceptor, UnaryResponse } from 'grpc-web';
|
2020-09-29 13:21:40 +02:00
|
|
|
import { filter, first, take } from 'rxjs/operators';
|
|
|
|
|
import { WarnDialogComponent } from 'src/app/modules/warn-dialog/warn-dialog.component';
|
2020-08-29 10:43:35 +02:00
|
|
|
|
|
|
|
|
import { AuthenticationService } from '../authentication.service';
|
|
|
|
|
import { StorageService } from '../storage.service';
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const authorizationKey = 'Authorization';
|
|
|
|
|
const bearerPrefix = 'Bearer';
|
|
|
|
|
const accessTokenStorageKey = 'access_token';
|
|
|
|
|
@Injectable({ providedIn: 'root' })
|
2020-09-29 13:21:40 +02:00
|
|
|
/**
|
|
|
|
|
* Set the authentication token
|
|
|
|
|
*/
|
2020-08-29 10:43:35 +02:00
|
|
|
export class AuthInterceptor<TReq = unknown, TResp = unknown> implements UnaryInterceptor<TReq, TResp> {
|
2020-09-29 13:21:40 +02:00
|
|
|
constructor(
|
|
|
|
|
private authenticationService: AuthenticationService,
|
|
|
|
|
private storageService: StorageService,
|
|
|
|
|
private dialog: MatDialog,
|
|
|
|
|
) { }
|
2020-08-29 10:43:35 +02:00
|
|
|
|
|
|
|
|
public async intercept(request: Request<TReq, TResp>, invoker: any): Promise<UnaryResponse<TReq, TResp>> {
|
|
|
|
|
await this.authenticationService.authenticationChanged.pipe(
|
|
|
|
|
filter((authed) => !!authed),
|
|
|
|
|
first(),
|
|
|
|
|
).toPromise();
|
|
|
|
|
|
|
|
|
|
const metadata = request.getMetadata();
|
|
|
|
|
const accessToken = this.storageService.getItem(accessTokenStorageKey);
|
|
|
|
|
metadata[authorizationKey] = `${bearerPrefix} ${accessToken}`;
|
|
|
|
|
|
|
|
|
|
return invoker(request).then((response: any) => {
|
|
|
|
|
return response;
|
2020-09-29 13:21:40 +02:00
|
|
|
}).catch((error: any) => {
|
|
|
|
|
console.error('error: ', error);
|
|
|
|
|
if (error.code === 16) {
|
|
|
|
|
const dialogRef = this.dialog.open(WarnDialogComponent, {
|
|
|
|
|
data: {
|
|
|
|
|
confirmKey: 'ACTIONS.LOGIN',
|
|
|
|
|
titleKey: 'ERRORS.TOKENINVALID.TITLE',
|
|
|
|
|
descriptionKey: 'ERRORS.TOKENINVALID.DESCRIPTION',
|
|
|
|
|
},
|
|
|
|
|
width: '400px',
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
dialogRef.afterClosed().pipe(take(1)).subscribe(resp => {
|
|
|
|
|
if (resp) {
|
|
|
|
|
this.authenticationService.authenticate(undefined, true, true);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
2020-08-29 10:43:35 +02:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|