아주 좋은 질문이야.
지금 상황을 정리해보면,
MongoDB에 사용자 정보가 저장되어 있음
프론트에서 자신의 MongoDB _id
를 직접 전달해서 사용자 정보를 조회 중
문제점:
“로그인한 사용자는 반드시 자기 정보만 볼 수 있어야 한다.
(id를 아무리 바꿔도, 내 계정이 아닌 건 못 보게)”
// user.controller.ts
@UseGuards(JwtAuthGuard)
@Get('me')
async getMe(@Request() req) {
// req.user는 JWT에서 추출한 유저 정보 (보통 { userId, email, ... })
const user = await this.userService.findById(req.user.userId);
// 여기서 필요한 정보만 골라서 반환 (예: DTO로 필터링)
return new UserResponseDto(user);
}
/me
엔드포인트만 호출// fetch('/api/user/me', { headers: { Authorization: 'Bearer ...' } })
id 탈취해도 소용 없음 (내 JWT 토큰이 아니면 내 정보밖에 못 봄)
API 구조도 심플:
/user/me
또는 /me
같은 경로 사용@Get(':id')
@UseGuards(JwtAuthGuard)
async getUser(@Request() req, @Param('id') id: string) {
if (id !== req.user.userId) {
throw new ForbiddenException('본인 정보만 조회 가능');
}
return new UserResponseDto(await this.userService.findById(id));
}
export class UserResponseDto {
readonly email: string;
readonly name: string;
// ... 필요한 필드만
}
실제 NestJS + Mongoose + Passport(JWT) 조합 코드 샘플이 더 필요하면 추가로 보여줄 수 있어!
원해?