nestJS(nodeJS) GoogleOauth 연동하기

Gyus·2022년 6월 24일
0

GoogleOauth

설치

npm install google-auth-library --save

Module


@Module({
  imports: [
    TypeOrmModule.forFeature([User]),
    //* JwtService를 사용하기위해서 import 해준다.
    JwtModule.register({
      secret: 'secret',
      signOptions: { expiresIn: '3h' },
    }),
    forwardRef(() => UsersModule),
  ],
  providers: [AuthService, JwtStrategy],
  exports: [AuthService],
  controllers: [AuthController],
})
export class AuthModule {}

JWT 토큰을 만들어야 하기때문에 Jwt 관련 설정도 만들어준다.

controller

@ApiResponse({
    status: 1000,
    description: '성공',
    type: SignInResponse,
  })
  @Post('ios/google')
  @ApiOperation({ summary: 'IOS 구글 로그인' })
  @ApiQuery({ description: 'IOS 구글 로그인', type: GoogleLoginRequest })
  async iosGoogleAuth(@Body() googleLoginRequest: GoogleLoginRequest) {
    return this.authService.iosVerifyGoogle(googleLoginRequest.token);
  }

contoller에는 token을 body로 받아준다.

Service

import { OAuth2Client } from 'google-auth-library';

 async iosVerifyGoogle(token) {
    const queryRunner = this.connection.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();
    try {
      const ticket = await client.verifyIdToken({
        idToken: token,
        audience: secret.ios_google_client_id, // Specify the CLIENT_ID of the app that accesses the backend
        // Or, if multiple clients access the backend:
        //[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
      });
      const payload = ticket.getPayload();
      const userId = payload['sub'];

      const user = await this.userRepository.findOne({
        where: { id: userId },
      });

      // 유저가 존재하지 않는 경우
      if (user == undefined) {
        const user = new User();
        user.id = userId;
        const createUserData = await queryRunner.manager.save(user);
      }
      const payload1 = { sub: userId };

      const data = {
        id: userId,
        user: user.nickname,
        token: this.jwtService.sign(payload1),
      };

      const result = makeResponse(response.SUCCESS, data);

      await queryRunner.commitTransaction();
      await queryRunner.release();
      return result;
    } catch (error) {
      // Rollback
      await queryRunner.rollbackTransaction();
      await queryRunner.release();
      return response.ERROR;
    }
  }

토큰은 받아서 Service Layer에서 토큰을 검증해준다.
그리고 토큰에서 sub을 추출해서 우리의 데이터베이스에 해당 유저가 있는지 검색한 후에 없다면 회원가입을 시켜준다.
그리고 해당 userId로 jwt 토큰을 만들어서 리턴 시켜준다.
여기서 clientID는 프론트엔드와 동일하게 지정해줘야한다.


Reference

https://www.npmjs.com/package/google-auth-library

profile
푸로구래머

0개의 댓글