@Injectable()
export class RefreshAuthGuard extends JwtAuthGuard {
constructor(
private readonly jwtService: JwtService,
) {
super();
}
public handleRequest(err: any, user: any, info: Error, ctx: any): any {
if (err || !user) {
if (info.name === 'TokenExpiredError') {
const request: Request = ctx.getRequest();
const headers: IHttpRequestHeaders = request.headers as IHttpRequestHeaders;
const refresh_token = headers.refresh_token;
if (!this.isValidRefreshToken(refresh_token)) {
throw new HttpException('Invalid refresh token', HttpStatus.UNAUTHORIZED);
}
} else {
throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED);
}
} else {
throw new HttpException('Expired tokens only', HttpStatus.FORBIDDEN);
}
}
private isValidRefreshToken(refresh_token: string): boolean {
return !!refresh_token;
}
}
Challenge:
If I were to add the async
keyword to the method and change its return type to Promise<any>
, I encounter the following error message:
Property 'handleRequest' in type 'RefreshAuthGuard' cannot be assigned to the same property in base type 'JwtAuthGuard'. Type '(err: any, user: any, info: Error, ctx: any) => Promise<any>' is not compatible with type '<TUser = any>(err: any, user: any, info: any, context: any, status?: any) => TUser'. Type 'Promise<any>' is not assignable to type 'TUser'
I am in need of making these methods asynchronous in order to retrieve a user's refresh token from the database and validate it within this guard. Asynchronous operations are crucial for my requirements.
UPDATE:
This excerpt is taken from the source code of NestJS:
export declare type IAuthGuard = CanActivate & {
logIn<TRequest extends {
logIn: Function;
} = any>(request: TRequest): Promise<void>;
handleRequest<TUser = any>(err: any, user: any, info: any, context: any, status?: any): TUser;
};
export declare const AuthGuard: (type?: string | string[]) => Type<IAuthGuard>;
It appears that the method cannot be made asynchronous...