All files / src/auth jwt.service.ts

94.54% Statements 52/55
94.73% Branches 18/19
92.85% Functions 13/14
94.33% Lines 50/53

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 1674x 4x 4x   4x     4x   24x 24x 24x               7x           7x   7x             5x                           4x 4x     4x       4x           4x       1x           5x           6x       6x   6x                       4x       4x 4x                 6x 6x 4x   2x         3x 3x 2x 2x 1x 1x           2x 2x           4x 4x 3x     3x 3x 1x       2x 2x   2x 1x       1x   1x         3x      
import { Injectable } from "@nestjs/common";
import { JwtService as NestJwtService } from "@nestjs/jwt";
import { ConfigService } from "@nestjs/config";
import { JwtPayload } from "@calendar-todo/shared-types";
import { RedisService } from "../redis/redis.service";
 
@Injectable()
export class JwtAuthService {
  constructor(
    private readonly jwtService: NestJwtService,
    private readonly configService: ConfigService,
    private readonly redisService: RedisService,
  ) {}
 
  generateAccessToken(
    userId: string,
    email: string,
    rememberMe = false,
  ): string {
    const payload: Omit<JwtPayload, "iat" | "exp"> = {
      sub: userId,
      email,
    };
 
    // 로그인 유지 시 3개월, 기본 24시간
    const expiresIn = rememberMe ? "90d" : "24h";
 
    return this.jwtService.sign(payload, {
      secret: this.configService.get<string>("JWT_SECRET"),
      expiresIn,
    });
  }
 
  generateRefreshToken(userId: string): string {
    return this.jwtService.sign(
      { sub: userId, type: "refresh" },
      {
        secret: this.configService.get<string>("JWT_REFRESH_SECRET"),
        expiresIn: "7d", // 7일
      },
    );
  }
 
  async generateTokenPair(
    userId: string,
    email: string,
    rememberMe = false,
  ): Promise<{ accessToken: string; refreshToken: string }> {
    const accessToken = this.generateAccessToken(userId, email, rememberMe);
    const refreshToken = this.generateRefreshToken(userId);
 
    // Store refresh token in Redis with expiration
    const refreshTokenKey = this.redisService.generateKey(
      "refresh_token",
      userId,
    );
    await this.redisService.set(
      refreshTokenKey,
      refreshToken,
      7 * 24 * 60 * 60,
    ); // 7 days
 
    return { accessToken, refreshToken };
  }
 
  verifyAccessToken(token: string): JwtPayload {
    return this.jwtService.verify(token, {
      secret: this.configService.get<string>("JWT_SECRET"),
    });
  }
 
  verifyRefreshToken(token: string): { sub: string; type: string } {
    return this.jwtService.verify(token, {
      secret: this.configService.get<string>("JWT_REFRESH_SECRET"),
    });
  }
 
  async isRefreshTokenValid(userId: string, token: string): Promise<boolean> {
    const refreshTokenKey = this.redisService.generateKey(
      "refresh_token",
      userId,
    );
    const storedToken = await this.redisService.get(refreshTokenKey);
 
    return storedToken === token;
  }
 
  async revokeRefreshToken(userId: string): Promise<void> {
    const refreshTokenKey = this.redisService.generateKey(
      "refresh_token",
      userId,
    );
    await this.redisService.del(refreshTokenKey);
  }
 
  private isJwtPayload(decoded: unknown): decoded is JwtPayload {
    Iif (typeof decoded !== "object" || decoded === null) {
      return false;
    }
 
    const obj = decoded as Record<string, unknown>;
    return (
      typeof obj.sub === "string" &&
      typeof obj.email === "string" &&
      typeof obj.iat === "number" &&
      typeof obj.exp === "number"
    );
  }
 
  private safeDecodeToken(token: string): JwtPayload | null {
    try {
      const decoded: unknown = this.jwtService.decode(token);
      return this.isJwtPayload(decoded) ? decoded : null;
    } catch {
      return null;
    }
  }
 
  async blacklistToken(token: string): Promise<void> {
    const decoded = this.safeDecodeToken(token);
    if (decoded) {
      const ttl = decoded.exp - Math.floor(Date.now() / 1000);
      if (ttl > 0) {
        const blacklistKey = this.redisService.generateKey("blacklist", token);
        await this.redisService.set(blacklistKey, "1", ttl);
      }
    }
  }
 
  async isTokenBlacklisted(token: string): Promise<boolean> {
    const blacklistKey = this.redisService.generateKey("blacklist", token);
    return await this.redisService.exists(blacklistKey);
  }
 
  async refreshAccessToken(
    refreshToken: string,
  ): Promise<{ accessToken: string; refreshToken: string } | null> {
    try {
      const decoded = this.verifyRefreshToken(refreshToken);
      const userId = decoded.sub;
 
      // Check if refresh token is still valid in Redis
      const isValid = await this.isRefreshTokenValid(userId, refreshToken);
      if (!isValid) {
        return null;
      }
 
      // Get user info to generate new access token
      const userKey = this.redisService.generateKey("user", userId);
      const userData = await this.redisService.hgetall(userKey);
 
      if (!userData || !userData.email) {
        return null;
      }
 
      // Generate new token pair
      return await this.generateTokenPair(userId, userData.email);
    } catch {
      return null;
    }
  }
 
  decodeToken(token: string): JwtPayload | null {
    return this.safeDecodeToken(token);
  }
}