File size: 11,835 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import { randomBytes } from "node:crypto";

import {
  BadRequestException,
  ForbiddenException,
  Injectable,
  InternalServerErrorException,
  Logger,
} from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { JwtService } from "@nestjs/jwt";
import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library";
import { AuthProvidersDto, LoginDto, RegisterDto, UserWithSecrets } from "@reactive-resume/dto";
import { ErrorMessage } from "@reactive-resume/utils";
import * as bcryptjs from "bcryptjs";
import { authenticator } from "otplib";

import { Config } from "../config/schema";
import { MailService } from "../mail/mail.service";
import { UserService } from "../user/user.service";
import { Payload } from "./utils/payload";

@Injectable()
export class AuthService {
  constructor(
    private readonly configService: ConfigService<Config>,
    private readonly userService: UserService,
    private readonly mailService: MailService,
    private readonly jwtService: JwtService,
  ) {}

  private hash(password: string): Promise<string> {
    return bcryptjs.hash(password, 10);
  }

  private compare(password: string, hash: string): Promise<boolean> {
    return bcryptjs.compare(password, hash);
  }

  private async validatePassword(password: string, hashedPassword: string) {
    const isValid = await this.compare(password, hashedPassword);

    if (!isValid) {
      throw new BadRequestException(ErrorMessage.InvalidCredentials);
    }
  }

  generateToken(grantType: "access" | "refresh" | "reset" | "verification", payload?: Payload) {
    switch (grantType) {
      case "access": {
        if (!payload) throw new InternalServerErrorException("InvalidTokenPayload");
        return this.jwtService.sign(payload, {
          secret: this.configService.getOrThrow("ACCESS_TOKEN_SECRET"),
          expiresIn: "15m", // 15 minutes
        });
      }

      case "refresh": {
        if (!payload) throw new InternalServerErrorException("InvalidTokenPayload");
        return this.jwtService.sign(payload, {
          secret: this.configService.getOrThrow("REFRESH_TOKEN_SECRET"),
          expiresIn: "2d", // 2 days
        });
      }

      case "reset":
      case "verification": {
        return randomBytes(32).toString("base64url");
      }
    }
  }

  async setLastSignedIn(email: string) {
    await this.userService.updateByEmail(email, {
      secrets: { update: { lastSignedIn: new Date() } },
    });
  }

  async setRefreshToken(email: string, token: string | null) {
    await this.userService.updateByEmail(email, {
      secrets: {
        update: {
          refreshToken: token,
          lastSignedIn: token ? new Date() : undefined,
        },
      },
    });
  }

  async validateRefreshToken(payload: Payload, token: string) {
    const user = await this.userService.findOneById(payload.id);
    const storedRefreshToken = user.secrets?.refreshToken;

    if (!storedRefreshToken || storedRefreshToken !== token) throw new ForbiddenException();

    if (!user.twoFactorEnabled) return user;

    if (payload.isTwoFactorAuth) return user;
  }

  async register(registerDto: RegisterDto): Promise<UserWithSecrets> {
    const hashedPassword = await this.hash(registerDto.password);

    try {
      const user = await this.userService.create({
        name: registerDto.name,
        email: registerDto.email,
        username: registerDto.username,
        locale: registerDto.locale,
        provider: "email",
        emailVerified: false, // Set to true if you don't want to verify user's email
        secrets: { create: { password: hashedPassword } },
      });

      // Do not `await` this function, otherwise the user will have to wait for the email to be sent before the response is returned
      void this.sendVerificationEmail(user.email);

      return user;
    } catch (error) {
      if (error instanceof PrismaClientKnownRequestError && error.code === "P2002") {
        throw new BadRequestException(ErrorMessage.UserAlreadyExists);
      }

      Logger.error(error);
      throw new InternalServerErrorException(error);
    }
  }

  async authenticate({ identifier, password }: LoginDto) {
    try {
      const user = await this.userService.findOneByIdentifierOrThrow(identifier);

      if (!user.secrets?.password) {
        throw new BadRequestException(ErrorMessage.OAuthUser);
      }

      await this.validatePassword(password, user.secrets.password);
      await this.setLastSignedIn(user.email);

      return user;
    } catch {
      throw new BadRequestException(ErrorMessage.InvalidCredentials);
    }
  }

  // Password Reset Flows
  async forgotPassword(email: string) {
    const token = this.generateToken("reset");

    await this.userService.updateByEmail(email, {
      secrets: { update: { resetToken: token } },
    });

    const baseUrl = this.configService.get("PUBLIC_URL");
    const url = `${baseUrl}/auth/reset-password?token=${token}`;
    const subject = "Reset your Reactive Resume password";
    const text = `Please click on the link below to reset your password:\n\n${url}`;

    await this.mailService.sendEmail({ to: email, subject, text });
  }

  async updatePassword(email: string, currentPassword: string, newPassword: string) {
    const user = await this.userService.findOneByIdentifierOrThrow(email);

    if (!user.secrets?.password) {
      throw new BadRequestException(ErrorMessage.OAuthUser);
    }

    await this.validatePassword(currentPassword, user.secrets.password);

    const newHashedPassword = await this.hash(newPassword);

    await this.userService.updateByEmail(email, {
      secrets: { update: { password: newHashedPassword } },
    });
  }

  async resetPassword(token: string, password: string) {
    const hashedPassword = await this.hash(password);

    await this.userService.updateByResetToken(token, {
      resetToken: null,
      password: hashedPassword,
    });
  }

  getAuthProviders() {
    const providers: AuthProvidersDto = [];

    if (!this.configService.get("DISABLE_EMAIL_AUTH")) {
      providers.push("email");
    }

    if (
      this.configService.get("GITHUB_CLIENT_ID") &&
      this.configService.get("GITHUB_CLIENT_SECRET") &&
      this.configService.get("GITHUB_CALLBACK_URL")
    ) {
      providers.push("github");
    }

    if (
      this.configService.get("GOOGLE_CLIENT_ID") &&
      this.configService.get("GOOGLE_CLIENT_SECRET") &&
      this.configService.get("GOOGLE_CALLBACK_URL")
    ) {
      providers.push("google");
    }

    if (
      this.configService.get("OPENID_AUTHORIZATION_URL") &&
      this.configService.get("OPENID_CALLBACK_URL") &&
      this.configService.get("OPENID_CLIENT_ID") &&
      this.configService.get("OPENID_CLIENT_SECRET") &&
      this.configService.get("OPENID_ISSUER") &&
      this.configService.get("OPENID_SCOPE") &&
      this.configService.get("OPENID_TOKEN_URL") &&
      this.configService.get("OPENID_USER_INFO_URL")
    ) {
      providers.push("openid");
    }

    return providers;
  }

  // Email Verification Flows
  async sendVerificationEmail(email: string) {
    try {
      const token = this.generateToken("verification");

      // Set the verification token in the database
      await this.userService.updateByEmail(email, {
        secrets: { update: { verificationToken: token } },
      });

      const baseUrl = this.configService.get("PUBLIC_URL");
      const url = `${baseUrl}/auth/verify-email?token=${token}`;
      const subject = "Verify your email address";
      const text = `Please verify your email address by clicking on the link below:\n\n${url}`;

      await this.mailService.sendEmail({ to: email, subject, text });
    } catch (error) {
      Logger.error(error);
      throw new InternalServerErrorException(error);
    }
  }

  async verifyEmail(id: string, token: string) {
    const user = await this.userService.findOneById(id);

    const storedToken = user.secrets?.verificationToken;

    if (!storedToken || storedToken !== token) {
      throw new BadRequestException(ErrorMessage.InvalidVerificationToken);
    }

    await this.userService.updateByEmail(user.email, {
      emailVerified: true,
      secrets: { update: { verificationToken: null } },
    });
  }

  // Two-Factor Authentication Flows
  async setup2FASecret(email: string) {
    // If the user already has 2FA enabled, throw an error
    const user = await this.userService.findOneByIdentifierOrThrow(email);

    if (user.twoFactorEnabled) {
      throw new BadRequestException(ErrorMessage.TwoFactorAlreadyEnabled);
    }

    const secret = authenticator.generateSecret();
    const uri = authenticator.keyuri(email, "Reactive Resume", secret);

    await this.userService.updateByEmail(email, {
      secrets: { update: { twoFactorSecret: secret } },
    });

    return { message: uri };
  }

  async enable2FA(email: string, code: string) {
    const user = await this.userService.findOneByIdentifierOrThrow(email);

    // If the user already has 2FA enabled, throw an error
    if (user.twoFactorEnabled) {
      throw new BadRequestException(ErrorMessage.TwoFactorAlreadyEnabled);
    }

    // If the user doesn't have a 2FA secret set, throw an error
    if (!user.secrets?.twoFactorSecret) {
      throw new BadRequestException(ErrorMessage.TwoFactorNotEnabled);
    }

    const verified = authenticator.verify({
      secret: user.secrets.twoFactorSecret,
      token: code,
    });

    if (!verified) {
      throw new BadRequestException(ErrorMessage.InvalidTwoFactorCode);
    }

    // Create backup codes and store them in the database
    const backupCodes = Array.from({ length: 8 }, () => randomBytes(5).toString("hex"));

    await this.userService.updateByEmail(email, {
      twoFactorEnabled: true,
      secrets: { update: { twoFactorBackupCodes: backupCodes } },
    });

    return { backupCodes };
  }

  async disable2FA(email: string) {
    const user = await this.userService.findOneByIdentifierOrThrow(email);

    // If the user doesn't have 2FA enabled, throw an error
    if (!user.twoFactorEnabled) {
      throw new BadRequestException(ErrorMessage.TwoFactorNotEnabled);
    }

    await this.userService.updateByEmail(email, {
      twoFactorEnabled: false,
      secrets: { update: { twoFactorSecret: null, twoFactorBackupCodes: [] } },
    });
  }

  async verify2FACode(email: string, code: string) {
    const user = await this.userService.findOneByIdentifierOrThrow(email);

    // If the user doesn't have 2FA enabled, or does not have a 2FA secret set, throw an error
    if (!user.twoFactorEnabled || !user.secrets?.twoFactorSecret) {
      throw new BadRequestException(ErrorMessage.TwoFactorNotEnabled);
    }

    const verified = authenticator.verify({
      secret: user.secrets.twoFactorSecret,
      token: code,
    });

    if (!verified) {
      throw new BadRequestException(ErrorMessage.InvalidTwoFactorCode);
    }

    return user;
  }

  async useBackup2FACode(email: string, code: string): Promise<UserWithSecrets> {
    const user = await this.userService.findOneByIdentifierOrThrow(email);

    // If the user doesn't have 2FA enabled, or does not have a 2FA secret set, throw an error
    if (!user.twoFactorEnabled || !user.secrets?.twoFactorSecret) {
      throw new BadRequestException(ErrorMessage.TwoFactorNotEnabled);
    }

    const verified = user.secrets.twoFactorBackupCodes.includes(code);

    if (!verified) {
      throw new BadRequestException(ErrorMessage.InvalidTwoFactorBackupCode);
    }

    // Remove the used backup code from the database
    const backupCodes = user.secrets.twoFactorBackupCodes.filter((c) => c !== code);
    await this.userService.updateByEmail(email, {
      secrets: { update: { twoFactorBackupCodes: backupCodes } },
    });

    return user;
  }
}