of undefined (reading 'verifyAsync')
import { ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { JwtService } from '@nestjs/jwt';
import { WsException } from '@nestjs/websockets';
@Injectable()
export class JwtWsAuthGuard extends AuthGuard('jwt-ws') {
constructor(private readonly jwtService: JwtService) {
super();
}
async canActivate(context: ExecutionContext): Promise<boolean> {
const client = context.switchToWs().getClient();
const token = this.getTokenFromWebSocket(client);
if (!token) {
throw new WsException('Unauthorized');
}
const user = await this.validateToken(token);
if (!user) {
throw new WsException('Unauthorized');
}
client.user = user;
return true;
}
private getTokenFromWebSocket(client: any): string | null {
return this.getCookieValue(
client.handshake?.headers.cookie,
'_Secure-access-token',
);
}
private async validateToken(token: string): Promise<any> {
try {
const jwtPayload: any = await this.jwtService.verifyAsync(token, {
secret: 'secretKey',
});
return jwtPayload;
} catch (error) {
console.log(error);
return null;
}
}
}
Контекст потерялся, нужно явно задать this
Обсуждают сегодня