Download Reactive-Resume/apps/server/src/auth/auth.controller.ts from Devendra174/react-code-dataset: direct link, hf CLI and curl.
- Browser
- Download file 9.73 kB
-
https://huggingface.co/datasets/Devendra174/react-code-dataset/resolve/1e92f2d0b9e054abc23a53595fd89ad3e2b4a34e/Reactive-Resume/apps/server/src/auth/auth.controller.ts
- Command line
-
hf download hf://datasets/Devendra174/react-code-dataset@1e92f2d0b9e054abc23a53595fd89ad3e2b4a34e/Reactive-Resume/apps/server/src/auth/auth.controller.ts
-
curl -L -o auth.controller.ts https://huggingface.co/datasets/Devendra174/react-code-dataset/resolve/1e92f2d0b9e054abc23a53595fd89ad3e2b4a34e/Reactive-Resume/apps/server/src/auth/auth.controller.ts
9.73 kB
| 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"; | |
| ("Authentication") | |
| ("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); | |
| } | |
| ("register") | |
| async register(() registerDto: RegisterDto, ({ passthrough: true }) response: Response) { | |
| const user = await this.authService.register(registerDto); | |
| return this.handleAuthenticationResponse(user, response); | |
| } | |
| ("login") | |
| (LocalGuard) | |
| async login(() user: UserWithSecrets, ({ passthrough: true }) response: Response) { | |
| return this.handleAuthenticationResponse(user, response); | |
| } | |
| ("providers") | |
| getAuthProviders() { | |
| return this.authService.getAuthProviders(); | |
| } | |
| // OAuth Flows | |
| ("OAuth", "GitHub") | |
| ("github") | |
| (GitHubGuard) | |
| githubLogin() { | |
| return; | |
| } | |
| ("OAuth", "GitHub") | |
| ("github/callback") | |
| (GitHubGuard) | |
| async githubCallback( | |
| () user: UserWithSecrets, | |
| ({ passthrough: true }) response: Response, | |
| ) { | |
| return this.handleAuthenticationResponse(user, response, false, true); | |
| } | |
| ("OAuth", "Google") | |
| ("google") | |
| (GoogleGuard) | |
| googleLogin() { | |
| return; | |
| } | |
| ("OAuth", "Google") | |
| ("google/callback") | |
| (GoogleGuard) | |
| async googleCallback( | |
| () user: UserWithSecrets, | |
| ({ passthrough: true }) response: Response, | |
| ) { | |
| return this.handleAuthenticationResponse(user, response, false, true); | |
| } | |
| ("OAuth", "OpenID") | |
| ("openid") | |
| (OpenIDGuard) | |
| openidLogin() { | |
| return; | |
| } | |
| ("OAuth", "OpenID") | |
| ("openid/callback") | |
| (OpenIDGuard) | |
| async openidCallback( | |
| () user: UserWithSecrets, | |
| ({ passthrough: true }) response: Response, | |
| ) { | |
| return this.handleAuthenticationResponse(user, response, false, true); | |
| } | |
| ("refresh") | |
| (RefreshGuard) | |
| async refresh(() user: UserWithSecrets, ({ passthrough: true }) response: Response) { | |
| return this.handleAuthenticationResponse(user, response, true); | |
| } | |
| ("password") | |
| (TwoFactorGuard) | |
| async updatePassword( | |
| ("email") email: string, | |
| () { currentPassword, newPassword }: UpdatePasswordDto, | |
| ) { | |
| await this.authService.updatePassword(email, currentPassword, newPassword); | |
| return { message: "Your password has been successfully updated." }; | |
| } | |
| ("logout") | |
| (TwoFactorGuard) | |
| async logout(() user: UserWithSecrets, ({ 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 | |
| ("Two-Factor Auth") | |
| ("2fa/setup") | |
| (JwtGuard) | |
| async setup2FASecret(("email") email: string) { | |
| return this.authService.setup2FASecret(email); | |
| } | |
| ("Two-Factor Auth") | |
| (200) | |
| ("2fa/enable") | |
| (JwtGuard) | |
| async enable2FA( | |
| ("id") id: string, | |
| ("email") email: string, | |
| () { code }: TwoFactorDto, | |
| ({ 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); | |
| } | |
| ("Two-Factor Auth") | |
| (200) | |
| ("2fa/disable") | |
| (TwoFactorGuard) | |
| async disable2FA(("email") email: string) { | |
| await this.authService.disable2FA(email); | |
| return { message: "Two-factor authentication has been successfully disabled on your account." }; | |
| } | |
| ("Two-Factor Auth") | |
| (200) | |
| ("2fa/verify") | |
| (JwtGuard) | |
| async verify2FACode( | |
| () user: UserWithSecrets, | |
| () { code }: TwoFactorDto, | |
| ({ 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)); | |
| } | |
| ("Two-Factor Auth") | |
| (200) | |
| ("2fa/backup") | |
| (JwtGuard) | |
| async useBackup2FACode( | |
| ("id") id: string, | |
| ("email") email: string, | |
| () { code }: TwoFactorBackupDto, | |
| ({ passthrough: true }) response: Response, | |
| ) { | |
| const user = await this.authService.useBackup2FACode(email, code); | |
| return this.handleAuthenticationResponse(user, response, true); | |
| } | |
| // Password Recovery Flows | |
| ("Password Reset") | |
| (200) | |
| ("forgot-password") | |
| async forgotPassword(() { 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.", | |
| }; | |
| } | |
| ("Password Reset") | |
| (200) | |
| ("reset-password") | |
| async resetPassword(() { 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 | |
| ("Email Verification") | |
| ("verify-email") | |
| (TwoFactorGuard) | |
| async verifyEmail( | |
| ("id") id: string, | |
| ("emailVerified") emailVerified: boolean, | |
| ("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." }; | |
| } | |
| ("Email Verification") | |
| ("verify-email/resend") | |
| (TwoFactorGuard) | |
| async resendVerificationEmail( | |
| ("email") email: string, | |
| ("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.", | |
| }; | |
| } | |
| } | |