2024-09-03 20:19:33 +08:00
|
|
|
import {
|
|
|
|
CanActivate,
|
|
|
|
ExecutionContext,
|
|
|
|
Injectable,
|
|
|
|
UnauthorizedException,
|
|
|
|
} from '@nestjs/common';
|
|
|
|
import { JwtService } from '@nestjs/jwt';
|
|
|
|
import { env } from '@server/env';
|
2025-01-03 09:24:46 +08:00
|
|
|
|
2025-01-06 08:45:23 +08:00
|
|
|
import { JwtPayload } from '@nice/common';
|
2025-01-03 09:24:46 +08:00
|
|
|
import { extractTokenFromHeader } from './utils';
|
2024-09-03 20:19:33 +08:00
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class AuthGuard implements CanActivate {
|
|
|
|
constructor(private jwtService: JwtService) { }
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
|
|
const request = context.switchToHttp().getRequest();
|
2025-01-03 09:24:46 +08:00
|
|
|
const token = extractTokenFromHeader(request);
|
2024-09-03 20:19:33 +08:00
|
|
|
if (!token) {
|
|
|
|
throw new UnauthorizedException();
|
|
|
|
}
|
|
|
|
try {
|
2024-09-09 18:48:07 +08:00
|
|
|
const payload: JwtPayload = await this.jwtService.verifyAsync(
|
2024-09-03 20:19:33 +08:00
|
|
|
token,
|
|
|
|
{
|
|
|
|
secret: env.JWT_SECRET
|
|
|
|
}
|
|
|
|
);
|
|
|
|
request['user'] = payload;
|
|
|
|
} catch {
|
|
|
|
throw new UnauthorizedException();
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2025-01-06 08:45:23 +08:00
|
|
|
|
2024-09-03 20:19:33 +08:00
|
|
|
}
|