import {
ExecutionContext,
Injectable,
// UnauthorizedException,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
canActivate(context: ExecutionContext) {
return super.canActivate(context);
}
handleRequest(err: any, user: any, info: any) {
if (err || !user) {
// throw err || new UnauthorizedException('인증 문제가 있습니다.')
}
return user;
}
}
//* guard -> strategy
import { Payload } from './jwt.payload';
import { UsersService } from '../../users/users.service';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly usersService: UsersService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'secret',
ignoreExpiration: false,
});
}
async validate(payload: Payload) {
try {
const user = await this.usersService.findUserById(payload.sub);
if (user) {
return user;
} else {
throw new Error('해당하는 유저는 없습니다.');
}
} catch (error) {
throw new UnauthorizedException(error);
}
}
}
export type Payload = {
email: string;
sub: string;
};
@ApiOperation({ summary: '회원조회'})
@Get()
@UseGuards(JwtAuthGuard)
getCurrentUser(@CurrentUser() currentUser: UserDTO) {
console.log(currentUser);
return currentUser;
}
https://docs.nestjs.com/security/authentication#jwt-functionality