현재 인증 시스템 (2022-12-02)

jwt-access-token.guard.ts

// import 생략
@Injectable()
export class AccessTokenGuard extends AuthGuard("jwt-access-token") {}

jwt-refresh-token.guard.ts

// import 생략
@Injectable()
export class RefreshTokenGuard extends AuthGuard("jwt-refresh-token") {}

jwt-access-token.strategy.ts

// import 생략
interface JwtPayload {
  userId: number;
}

@Injectable()
export class AccessTokenStrategy extends PassportStrategy(Strategy, "jwt-access-token") {
  constructor(private config: ConfigService, private prisma: PrismaService) {
    super({
      secretOrKey: config.get<string>("JWT_SECRET_KEY"),
      jwtFromRequest: ExtractJwt.fromExtractors([
        (req: Request) => {
          return req.cookies["jwt-access-token"];
        },
      ]),
    });
  }

  async validate(payload: JwtPayload): Promise<User> {
    const { userId } = payload;
    const user = await this.prisma.user.findUnique({
      where: { userId },
    });

    if (!user) throw new UnauthorizedException();

    return user;
  }
}

jwt-refresh-token.strategy.ts

// import 생략
interface JwtPayload {
  userId: number;
}

@Injectable()
export class RefreshTokenStrategy extends PassportStrategy(Strategy, "jwt-refresh-token") {
  constructor(private config: ConfigService, private prisma: PrismaService) {
    super({
      secretOrKey: config.get<string>("JWT_SECRET_KEY"),
      jwtFromRequest: ExtractJwt.fromExtractors([
        (req: Request) => {
          return req.cookies["jwt-refresh-token"];
        },
      ]),
    });
  }

  async validate(req: Request, payload: JwtPayload) {
    const { userId } = payload;
    const user = await this.prisma.user.findUnique({
      where: { userId },
    });

    if (!user) throw new UnauthorizedException();

    const oldRefreshToken = req.get("Authorization").replace("Bearer", "").trim();

    return {
      user,
      oldRefreshToken,
    };
  }
}

로직