[NestJS] 회원가입, 로그인

woogiemon·2023년 3월 8일
0
post-thumbnail

app.module.ts

@Module({
  imports: [
    
    ...

    JwtModule.registerAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        secret: config.get<string>('JWT_SECRET'),
        signOptions: { expiresIn: config.get<string>('JWT_EXPIRATION_TIME') },
      }),
    }),

    ...
    
})
export class AppModule {}

로그인을 할때


import { Res } from '@nestjs/common';
import { Response } from 'express';		// import 주의할 것

@Post('/login')
  async login(@Body() request: AuthenticateRequest, @Res() res: Response) {
    const userByEmail = await this.userService.getByEmail(request.email);
    const accessToken = await this.authService.getAccessToken(
      userByEmail.email,
    );
    // 쿠키를 Authorization 에 박는 방법
    res.setHeader('Authorization', 'Bearer ' + accessToken);
    
    // Cookie 의 이름을 jwt라 한다.
    res.cookie('jwt', accessToken, {
      httpOnly: true,
      maxAge: 24 * 60 * 60 * 1000,	// 1day
    });

    return res.send({
      message: 'success',
    });
  }

유저가 로그인할 때

export class AuthenticateRequest {
  @ApiProperty()
  @IsEmail()
  readonly email: string;

  @ApiProperty()
  @IsString()
  readonly password: string;
}
profile
삽질 기록..

0개의 댓글