book_manage/apps/server/src/auth/auth.guard.ts

41 lines
1.1 KiB
TypeScript
Raw Normal View History

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
2024-09-09 18:48:07 +08:00
import { JwtPayload } from '@nicestack/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-10 11:23:02 +08:00
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
}
);
2024-09-10 11:23:02 +08:00
2024-09-03 20:19:33 +08:00
// 💡 We're assigning the payload to the request object here
// so that we can access it in our route handlers
request['user'] = payload;
} catch {
throw new UnauthorizedException();
}
return true;
}
2025-01-03 09:24:46 +08:00
2024-09-03 20:19:33 +08:00
}