발급 로직
users 컨트롤러에서 사용자 정보를 입력 받아 users 서비스로 전달
users 서비스에서 auth 서비스로 이메일과 비밀번호 전달
auth 서비스에서 토큰 발행후 return
응답 헤더에 담아서 응답
users.controllers.ts
이메일과 비밀번호를 입력 받아 유저 서비스로 전달
@Post('/login')
@ApiOperation({
summary: '로그인',
description: '로그인',
})
async login(
@Body() userLoginDtodto: UserLoginDto,
@Res({ passthrough: true }) response: Response,
) {
const { email, password } = userLoginDtodto;
const accessToken = await this.usersService.login(email, password);
response.header('Hi-junsoo', 'junsoobabo');
response.header('authorization', `Bearer ${accessToken}`);
return { msg: '로그인 성공' };
}
}
users.service.ts
전달 받은 이메일과 패스워드를 레포지토리로 전달하여 db에 이메일과 패스워드가 존재하는지 확인
이메일과 비밀번호가 존재할때 토큰을 발급하는 함수 실행
async login(email: string, password: string) {
//userRepository를 사용해 사용자 검색
const user = await this.usersRepository.loginUserExists(email, password);
//존재하지 않을때 예외처리
if (!user) {
throw new NotFoundException('유저가 존재하지 않습니다');
}
//존재하면 해당 사용자 정보로 로그인 토큰 생성
const accessToken = this.authService.login({
userId: user.userId,
email: user.email,
});
return accessToken;
}
auth.service.ts
유저의 이메일과 아이디를 토큰이 담아 시크릿키와 같이 암호화
토큰 만료시간은 2시간으로 설정 후 jwt 토큰 리턴
login(user: User) {
const payload = { ...user };
try {
const accessToken = jwt.sign(payload, this.config.jwtSecret, {
expiresIn: '2h',
audience: '다이다이',
issuer: '다이백엔드',
});
return accessToken;
} catch (error) {
console.error(error);
}
}
users.controllers.ts
리턴된 토큰을 응답 헤더에 담아 반환하고 로그인 성공이라는 메세지 응답
@Res({ passthrough: true }) 옵션 : Nest 표준 응답 처리에 의존하는 Nest 기능과의 호환성이 손실
@Post('/login')
@ApiOperation({
summary: '로그인',
description: '로그인',
})
async login(
@Body() userLoginDtodto: UserLoginDto,
@Res({ passthrough: true }) response: Response,
) {
const { email, password } = userLoginDtodto;
const accessToken = await this.usersService.login(email, password);
response.header('Hi-junsoo', 'junsoobabo');
response.header('authorization', `Bearer ${accessToken}`);
return { msg: '로그인 성공' };
}
}
요청
응답