File size: 9,727 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
import {
  BadRequestException,
  Body,
  Controller,
  Get,
  HttpCode,
  InternalServerErrorException,
  Patch,
  Post,
  Query,
  Res,
  UseGuards,
} from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { ApiTags } from "@nestjs/swagger";
import {
  authResponseSchema,
  backupCodesSchema,
  ForgotPasswordDto,
  messageSchema,
  RegisterDto,
  ResetPasswordDto,
  TwoFactorBackupDto,
  TwoFactorDto,
  UpdatePasswordDto,
  userSchema,
  UserWithSecrets,
} from "@reactive-resume/dto";
import { ErrorMessage } from "@reactive-resume/utils";
import type { Response } from "express";

import { User } from "../user/decorators/user.decorator";
import { AuthService } from "./auth.service";
import { GitHubGuard } from "./guards/github.guard";
import { GoogleGuard } from "./guards/google.guard";
import { JwtGuard } from "./guards/jwt.guard";
import { LocalGuard } from "./guards/local.guard";
import { OpenIDGuard } from "./guards/openid.guard";
import { RefreshGuard } from "./guards/refresh.guard";
import { TwoFactorGuard } from "./guards/two-factor.guard";
import { getCookieOptions } from "./utils/cookie";
import { payloadSchema } from "./utils/payload";

@ApiTags("Authentication")
@Controller("auth")
export class AuthController {
  constructor(
    private readonly authService: AuthService,
    private readonly configService: ConfigService,
  ) {}

  private async exchangeToken(id: string, email: string, isTwoFactorAuth = false) {
    try {
      const payload = payloadSchema.parse({ id, isTwoFactorAuth });

      const accessToken = this.authService.generateToken("access", payload);
      const refreshToken = this.authService.generateToken("refresh", payload);

      // Set Refresh Token in Database
      await this.authService.setRefreshToken(email, refreshToken);

      return { accessToken, refreshToken };
    } catch (error) {
      throw new InternalServerErrorException(error, ErrorMessage.SomethingWentWrong);
    }
  }

  private async handleAuthenticationResponse(
    user: UserWithSecrets,
    response: Response,
    isTwoFactorAuth = false,
    redirect = false,
  ) {
    let status = "authenticated";

    const baseUrl = this.configService.get("PUBLIC_URL");
    const redirectUrl = new URL(`${baseUrl}/auth/callback`);

    const { accessToken, refreshToken } = await this.exchangeToken(
      user.id,
      user.email,
      isTwoFactorAuth,
    );

    response.cookie("Authentication", accessToken, getCookieOptions("access"));
    response.cookie("Refresh", refreshToken, getCookieOptions("refresh"));

    if (user.twoFactorEnabled && !isTwoFactorAuth) status = "2fa_required";

    const responseData = authResponseSchema.parse({ status, user });

    redirectUrl.searchParams.set("status", status);

    if (redirect) response.redirect(redirectUrl.toString());
    else response.status(200).send(responseData);
  }

  @Post("register")
  async register(@Body() registerDto: RegisterDto, @Res({ passthrough: true }) response: Response) {
    const user = await this.authService.register(registerDto);

    return this.handleAuthenticationResponse(user, response);
  }

  @Post("login")
  @UseGuards(LocalGuard)
  async login(@User() user: UserWithSecrets, @Res({ passthrough: true }) response: Response) {
    return this.handleAuthenticationResponse(user, response);
  }

  @Get("providers")
  getAuthProviders() {
    return this.authService.getAuthProviders();
  }

  // OAuth Flows
  @ApiTags("OAuth", "GitHub")
  @Get("github")
  @UseGuards(GitHubGuard)
  githubLogin() {
    return;
  }

  @ApiTags("OAuth", "GitHub")
  @Get("github/callback")
  @UseGuards(GitHubGuard)
  async githubCallback(
    @User() user: UserWithSecrets,
    @Res({ passthrough: true }) response: Response,
  ) {
    return this.handleAuthenticationResponse(user, response, false, true);
  }

  @ApiTags("OAuth", "Google")
  @Get("google")
  @UseGuards(GoogleGuard)
  googleLogin() {
    return;
  }

  @ApiTags("OAuth", "Google")
  @Get("google/callback")
  @UseGuards(GoogleGuard)
  async googleCallback(
    @User() user: UserWithSecrets,
    @Res({ passthrough: true }) response: Response,
  ) {
    return this.handleAuthenticationResponse(user, response, false, true);
  }

  @ApiTags("OAuth", "OpenID")
  @Get("openid")
  @UseGuards(OpenIDGuard)
  openidLogin() {
    return;
  }

  @ApiTags("OAuth", "OpenID")
  @Get("openid/callback")
  @UseGuards(OpenIDGuard)
  async openidCallback(
    @User() user: UserWithSecrets,
    @Res({ passthrough: true }) response: Response,
  ) {
    return this.handleAuthenticationResponse(user, response, false, true);
  }

  @Post("refresh")
  @UseGuards(RefreshGuard)
  async refresh(@User() user: UserWithSecrets, @Res({ passthrough: true }) response: Response) {
    return this.handleAuthenticationResponse(user, response, true);
  }

  @Patch("password")
  @UseGuards(TwoFactorGuard)
  async updatePassword(
    @User("email") email: string,
    @Body() { currentPassword, newPassword }: UpdatePasswordDto,
  ) {
    await this.authService.updatePassword(email, currentPassword, newPassword);

    return { message: "Your password has been successfully updated." };
  }

  @Post("logout")
  @UseGuards(TwoFactorGuard)
  async logout(@User() user: UserWithSecrets, @Res({ passthrough: true }) response: Response) {
    await this.authService.setRefreshToken(user.email, null);

    response.clearCookie("Authentication");
    response.clearCookie("Refresh");

    const data = messageSchema.parse({ message: "You have been logged out, tschüss!" });
    response.status(200).send(data);
  }

  // Two-Factor Authentication Flows
  @ApiTags("Two-Factor Auth")
  @Post("2fa/setup")
  @UseGuards(JwtGuard)
  async setup2FASecret(@User("email") email: string) {
    return this.authService.setup2FASecret(email);
  }

  @ApiTags("Two-Factor Auth")
  @HttpCode(200)
  @Post("2fa/enable")
  @UseGuards(JwtGuard)
  async enable2FA(
    @User("id") id: string,
    @User("email") email: string,
    @Body() { code }: TwoFactorDto,
    @Res({ passthrough: true }) response: Response,
  ) {
    const { backupCodes } = await this.authService.enable2FA(email, code);

    const { accessToken, refreshToken } = await this.exchangeToken(id, email, true);

    response.cookie("Authentication", accessToken, getCookieOptions("access"));
    response.cookie("Refresh", refreshToken, getCookieOptions("refresh"));

    const data = backupCodesSchema.parse({ backupCodes });
    response.status(200).send(data);
  }

  @ApiTags("Two-Factor Auth")
  @HttpCode(200)
  @Post("2fa/disable")
  @UseGuards(TwoFactorGuard)
  async disable2FA(@User("email") email: string) {
    await this.authService.disable2FA(email);

    return { message: "Two-factor authentication has been successfully disabled on your account." };
  }

  @ApiTags("Two-Factor Auth")
  @HttpCode(200)
  @Post("2fa/verify")
  @UseGuards(JwtGuard)
  async verify2FACode(
    @User() user: UserWithSecrets,
    @Body() { code }: TwoFactorDto,
    @Res({ passthrough: true }) response: Response,
  ) {
    await this.authService.verify2FACode(user.email, code);

    const { accessToken, refreshToken } = await this.exchangeToken(user.id, user.email, true);

    response.cookie("Authentication", accessToken, getCookieOptions("access"));
    response.cookie("Refresh", refreshToken, getCookieOptions("refresh"));

    response.status(200).send(userSchema.parse(user));
  }

  @ApiTags("Two-Factor Auth")
  @HttpCode(200)
  @Post("2fa/backup")
  @UseGuards(JwtGuard)
  async useBackup2FACode(
    @User("id") id: string,
    @User("email") email: string,
    @Body() { code }: TwoFactorBackupDto,
    @Res({ passthrough: true }) response: Response,
  ) {
    const user = await this.authService.useBackup2FACode(email, code);

    return this.handleAuthenticationResponse(user, response, true);
  }

  // Password Recovery Flows
  @ApiTags("Password Reset")
  @HttpCode(200)
  @Post("forgot-password")
  async forgotPassword(@Body() { email }: ForgotPasswordDto) {
    try {
      await this.authService.forgotPassword(email);
    } catch {
      // pass
    }

    return {
      message:
        "A password reset link should have been sent to your inbox, if an account existed with the email you provided.",
    };
  }

  @ApiTags("Password Reset")
  @HttpCode(200)
  @Post("reset-password")
  async resetPassword(@Body() { token, password }: ResetPasswordDto) {
    try {
      await this.authService.resetPassword(token, password);

      return { message: "Your password has been successfully reset." };
    } catch {
      throw new BadRequestException(ErrorMessage.InvalidResetToken);
    }
  }

  // Email Verification Flows
  @ApiTags("Email Verification")
  @Post("verify-email")
  @UseGuards(TwoFactorGuard)
  async verifyEmail(
    @User("id") id: string,
    @User("emailVerified") emailVerified: boolean,
    @Query("token") token: string,
  ) {
    if (!token) throw new BadRequestException(ErrorMessage.InvalidVerificationToken);

    if (emailVerified) {
      throw new BadRequestException(ErrorMessage.EmailAlreadyVerified);
    }

    await this.authService.verifyEmail(id, token);

    return { message: "Your email has been successfully verified." };
  }

  @ApiTags("Email Verification")
  @Post("verify-email/resend")
  @UseGuards(TwoFactorGuard)
  async resendVerificationEmail(
    @User("email") email: string,
    @User("emailVerified") emailVerified: boolean,
  ) {
    if (emailVerified) {
      throw new BadRequestException(ErrorMessage.EmailAlreadyVerified);
    }

    await this.authService.sendVerificationEmail(email);

    return {
      message: "You should have received a new email with a link to verify your email address.",
    };
  }
}