manito42 / backend

42 Manito Backend Repository
https://42manito.com
3 stars 2 forks source link

[Refactor, Performance] auth/dev #135

Closed koreanddinghwan closed 1 year ago

koreanddinghwan commented 1 year ago

제안1.

https://github.com/manito42/backend/blob/424f83ae09f636b8068bc89e5b6d2b2a438196fc/src/modules/auth/auth.service.ts#L11-L19

  async verifyOrCreateUser(user: UserCreatePayloadDto): Promise<UserGetResponseDto> {
    const { nickname } = user;
    const userExist = await this.userService.findByNickname(nickname);
    if (!userExist) {
      return await this.userService.create(user);
    } else {
      return await this.userService.updateLastLogin(userExist.id);
    }
  }

제안2.

devService와 authService의 로직 통일이 필요해보입니다.

auth

  @UseGuards(FtGuard)
  @Get('42/callback')
  async get42AuthCallback(@Req() req, @Res() res: Response) {
    if (!req.user || !req.user.nickname) {
      res.redirect(`${this.appConfigService.accessUrl}?uid=0`);
    }

    const user = await this.authService.verifyOrCreateUser(req.user);
    const accessToken = await this.authService.createToken(user);

    res.redirect(`${this.appConfigService.accessUrl}/SignIn?uid=${user.id}&token=${accessToken}`);
  }
@Injectable()
export class AuthService {
  constructor(
    private readonly userService: UserService,
    private readonly jwtService: JwtService,
  ) {}

  async verifyOrCreateUser(user: UserCreatePayloadDto): Promise<UserGetResponseDto> {
    const { nickname } = user;
    const userExist = await this.userService.findByNickname(nickname);
    if (!userExist) {
      return await this.userService.create(user);
    } else {
      return await this.userService.updateLastLogin(userExist.id);
    }
  }

  async createToken(user: UserGetResponseDto): Promise<string> {
    // create jwt token and return it
    const payload: JwtPayloadInterface = {
      id: user.id,
      nickname: user.nickname,
      role: user.role,
      profileImage: user.profileImage,
    };
    return this.jwtService.sign(payload);
  }
}

dev

@Controller('dev')
export class DevController {
  constructor(
    private readonly devService: DevService,
    private readonly appConfigService: AppConfigService,
  ) {}

  @Get('/login/:id')
  async loginDev(@Param('id') id: number, @Res() res: Response) {
    if (process.env.NODE_ENV !== 'dev' && process.env.NODE_ENV !== 'test')
      throw new UnauthorizedException();

    // fixed fake user for dev
    const newFakeUser: UserCreatePayloadDto = {
      nickname: `manitoDevUser${id}`,
      email: `42manito${id}@gmail.com`,
      profileImage: 'https://cdn.intra.42.fr/users/medium_manito.jpg',
      role: UserRole.USER,
    };
    const fakeUser = await this.devService.verifyOrCreateFakeUser(newFakeUser);
    const accessToken = await this.devService.createToken(fakeUser);

    res.redirect(
      `${this.appConfigService.accessUrl}/SignIn?uid=${fakeUser.id}&token=${accessToken}`,
    );
  }
}
import { Injectable } from '@nestjs/common';
import { UserGetResponseDto } from '../../models/user/dto/response/userGetResponse.dto';
import { JwtPayloadInterface } from '../../common/interfaces/jwt/jwtPayload.interface';
import { JwtService } from '@nestjs/jwt';
import { UserCreatePayloadDto } from 'src/models/user/dto/request/userCreatePayload.dto';
import { UserService } from 'src/models/user/user.service';

@Injectable()
export class DevService {
  constructor(
    private readonly jwtService: JwtService,
    private readonly userService: UserService,
  ) {}

  // fixed fake user for dev
  async verifyOrCreateFakeUser(newFakeUser: UserCreatePayloadDto): Promise<UserGetResponseDto> {
    const { nickname } = newFakeUser;
    const userExist = await this.userService.findByNickname(nickname);
    if (!userExist) {
      return await this.userService.create(newFakeUser);
    } else {
      return await this.userService.updateLastLogin(userExist.id);
    }
  }

  async createToken(user: UserGetResponseDto): Promise<string> {
    // create jwt token and return it
    const payload: JwtPayloadInterface = {
      id: user.id,
      nickname: user.nickname,
      role: user.role,
      profileImage: user.profileImage,
    };
    return this.jwtService.sign(payload);
  }
}
JuneParkCode commented 1 year ago

좋은 의견... 이대로 가도 될 것 같은데요? LastLogin 은 추가 컬럼 생성 후 진행하나요?

koreanddinghwan commented 1 year ago

좋은 의견... 이대로 가도 될 것 같은데요? LastLogin 은 추가 컬럼 생성 후 진행하나요?

updatedAt 그대로 사용하면됩니다!

koreanddinghwan commented 1 year ago

좋은 의견... 이대로 가도 될 것 같은데요? LastLogin 은 추가 컬럼 생성 후 진행하나요?

서비스함수만 저렇고 레포지토리에서는 updatedAt만 수정합니당

JuneParkCode commented 1 year ago

updatedAt 만 현재로 변경하나요?

koreanddinghwan commented 1 year ago

updatedAt 만 현재로 변경하나요?

넵!

JuneParkCode commented 1 year ago

좋아요~ create 쪽에서 반환하는 값만 잘 확인하면 될듯! 두번 쿼리 날리고 있었네용 ㅋㅋ