| 1 | import { eq } from "drizzle-orm"; |
| 2 | import { db, settings |
| 3 | import * as schema |
| 4 | import { env } |
| 5 | import { apiKey } |
| 6 | import { i18n } |
| 7 | import { betterAuth } |
| 8 | import { APIError, createAuthMiddleware |
| 9 | import { drizzleAdapter } |
| 10 | import { nextCookies } |
| 11 | import { admin, captcha |
| 12 | import { safeDecrypt } |
| 13 | import { |
| 14 | buildEmailServiceFromSettings, |
| 15 | getEmailTemplate, |
| 16 | DEFAULT_TEMPLATES, |
| 17 | substituteVars, |
| 18 | sendEmail, |
| 19 | } from "./email"; |
| 20 | |
| 21 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 22 | type AuthInstance |
| 23 | |
| 24 | let _auth: AuthInstance |
| 25 | let _authPromise: Promise |
| 26 | |
| 27 | async function buildAuth() |
| 28 | const rows = |
| 29 | const s = |
| 30 | const appName = |
| 31 | const appUrl = |
| 32 | const baseURL = |
| 33 | const corsOrigin = |
| 34 | |
| 35 | const socialProviders: |
| 36 | if (s.github_enabled |
| 37 | socialProviders.github = |
| 38 | } |
| 39 | if (s.discord_enabled |
| 40 | socialProviders.discord = |
| 41 | } |
| 42 | |
| 43 | return betterAuth({ |
| 44 | database: drizzleAdapter(db |
| 45 | provider: "mysql", |
| 46 | schema: schema, |
| 47 | }), |
| 48 | trustedOrigins: corsOrigin ? |
| 49 | account: { |
| 50 | accountLinking: { |
| 51 | enabled: true, |
| 52 | allowDifferentEmails: true, |
| 53 | }, |
| 54 | }, |
| 55 | emailAndPassword: { |
| 56 | enabled: true, |
| 57 | sendResetPassword: async ( |
| 58 | const svc = |
| 59 | if (!svc) |
| 60 | const custom = |
| 61 | const resetToken = |
| 62 | const vars = |
| 63 | const html = |
| 64 | ? substituteVars(custom, |
| 65 | : DEFAULT_TEMPLATES["password-reset" |
| 66 | await sendEmail(svc |
| 67 | }, |
| 68 | }, |
| 69 | emailVerification: { |
| 70 | sendVerificationEmail: async ( |
| 71 | const svc = |
| 72 | if (!svc) |
| 73 | // Email disabled — auto-verify so email/password signups aren't permanently locked out. |
| 74 | // Social logins auto-verify; this keeps consistent behaviour when no email service is set. |
| 75 | await db.update |
| 76 | return; |
| 77 | } |
| 78 | const verificationToken = |
| 79 | const custom = |
| 80 | const vars = |
| 81 | const html = |
| 82 | ? substituteVars(custom, |
| 83 | : DEFAULT_TEMPLATES.verification( |
| 84 | await sendEmail(svc |
| 85 | }, |
| 86 | }, |
| 87 | socialProviders, |
| 88 | secret: env.BETTER_AUTH_SECRET |
| 89 | baseURL: baseURL || |
| 90 | appName, |
| 91 | onAPIError: { |
| 92 | errorURL: appUrl ? |
| 93 | }, |
| 94 | hooks: { |
| 95 | before: createAuthMiddleware(async |
| 96 | if (ctx.path |
| 97 | const row = |
| 98 | where: eq(settings |
| 99 | }); |
| 100 | if (row?.value |
| 101 | throw new APIError( |
| 102 | } |
| 103 | }), |
| 104 | after: createAuthMiddleware(async |
| 105 | if (ctx.path |
| 106 | const newUser = |
| 107 | if (!newUser) |
| 108 | void (async () |
| 109 | try { |
| 110 | const svc = |
| 111 | if (!svc) |
| 112 | const custom = |
| 113 | const vars = |
| 114 | const html = |
| 115 | ? substituteVars(custom, |
| 116 | : DEFAULT_TEMPLATES.welcome( |
| 117 | await sendEmail(svc |
| 118 | } catch { |
| 119 | // non-critical |
| 120 | } |
| 121 | })(); |
| 122 | }), |
| 123 | }, |
| 124 | plugins: [ |
| 125 | nextCookies(), |
| 126 | admin(), |
| 127 | twoFactor({ issuer: |
| 128 | apiKey(), |
| 129 | i18n({ |
| 130 | detection: ["cookie", |
| 131 | localeCookie: "NEXT_LOCALE", |
| 132 | translations: { |
| 133 | pl: { |
| 134 | INVALID_EMAIL_OR_PASSWORD: "Nieprawidłowy adres e-mail lub hasło.", |
| 135 | USER_NOT_FOUND: "Nie znaleziono użytkownika.", |
| 136 | USER_EMAIL_NOT_FOUND: "Nie znaleziono użytkownika z tym adresem e-mail.", |
| 137 | INVALID_PASSWORD: "Nieprawidłowe hasło.", |
| 138 | EMAIL_NOT_VERIFIED: "Adres e-mail nie został zweryfikowany.", |
| 139 | USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: "Użytkownik z tym adresem e-mail już istnieje.", |
| 140 | PASSWORD_TOO_SHORT: "Hasło jest za krótkie.", |
| 141 | PASSWORD_TOO_LONG: "Hasło jest za długie.", |
| 142 | SESSION_EXPIRED: "Sesja wygasła. Zaloguj się ponownie.", |
| 143 | CREDENTIAL_ACCOUNT_NOT_FOUND: "Nie znaleziono konta.", |
| 144 | FAILED_TO_CREATE_USER: "Nie udało się utworzyć konta. Spróbuj ponownie.", |
| 145 | FAILED_TO_CREATE_SESSION: "Nie udało się utworzyć sesji. Spróbuj ponownie.", |
| 146 | }, |
| 147 | de: { |
| 148 | INVALID_EMAIL_OR_PASSWORD: "Ungültige E-Mail-Adresse oder Passwort.", |
| 149 | USER_NOT_FOUND: "Benutzer nicht gefunden.", |
| 150 | USER_EMAIL_NOT_FOUND: "Kein Benutzer mit dieser E-Mail-Adresse gefunden.", |
| 151 | INVALID_PASSWORD: "Ungültiges Passwort.", |
| 152 | EMAIL_NOT_VERIFIED: "E-Mail-Adresse ist nicht verifiziert.", |
| 153 | USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: "Ein Benutzer mit dieser E-Mail-Adresse existiert bereits.", |
| 154 | PASSWORD_TOO_SHORT: "Das Passwort ist zu kurz.", |
| 155 | PASSWORD_TOO_LONG: "Das Passwort ist zu lang.", |
| 156 | SESSION_EXPIRED: "Sitzung abgelaufen. Bitte erneut anmelden.", |
| 157 | CREDENTIAL_ACCOUNT_NOT_FOUND: "Konto nicht gefunden.", |
| 158 | FAILED_TO_CREATE_USER: "Konto konnte nicht erstellt werden. Bitte erneut versuchen.", |
| 159 | FAILED_TO_CREATE_SESSION: "Sitzung konnte nicht erstellt werden. Bitte erneut versuchen.", |
| 160 | }, |
| 161 | es: { |
| 162 | INVALID_EMAIL_OR_PASSWORD: "Correo electrónico o contraseña incorrectos.", |
| 163 | USER_NOT_FOUND: "Usuario no encontrado.", |
| 164 | USER_EMAIL_NOT_FOUND: "No se encontró ningún usuario con ese correo electrónico.", |
| 165 | INVALID_PASSWORD: "Contraseña incorrecta.", |
| 166 | EMAIL_NOT_VERIFIED: "El correo electrónico no está verificado.", |
| 167 | USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: "Ya existe un usuario con este correo electrónico.", |
| 168 | PASSWORD_TOO_SHORT: "La contraseña es demasiado corta.", |
| 169 | PASSWORD_TOO_LONG: "La contraseña es demasiado larga.", |
| 170 | SESSION_EXPIRED: "La sesión ha expirado. Inicia sesión de nuevo.", |
| 171 | CREDENTIAL_ACCOUNT_NOT_FOUND: "Cuenta no encontrada.", |
| 172 | FAILED_TO_CREATE_USER: "No se pudo crear la cuenta. Inténtalo de nuevo.", |
| 173 | FAILED_TO_CREATE_SESSION: "No se pudo crear la sesión. Inténtalo de nuevo.", |
| 174 | }, |
| 175 | fr: { |
| 176 | INVALID_EMAIL_OR_PASSWORD: "Adresse e-mail ou mot de passe incorrect.", |
| 177 | USER_NOT_FOUND: "Utilisateur introuvable.", |
| 178 | USER_EMAIL_NOT_FOUND: "Aucun utilisateur trouvé avec cette adresse e-mail.", |
| 179 | INVALID_PASSWORD: "Mot de passe incorrect.", |
| 180 | EMAIL_NOT_VERIFIED: "L'adresse e-mail n'est pas vérifiée.", |
| 181 | USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: "Un utilisateur avec cette adresse e-mail existe déjà.", |
| 182 | PASSWORD_TOO_SHORT: "Le mot de passe est trop court.", |
| 183 | PASSWORD_TOO_LONG: "Le mot de passe est trop long.", |
| 184 | SESSION_EXPIRED: "Session expirée. Veuillez vous reconnecter.", |
| 185 | CREDENTIAL_ACCOUNT_NOT_FOUND: "Compte introuvable.", |
| 186 | FAILED_TO_CREATE_USER: "Impossible de créer le compte. Veuillez réessayer.", |
| 187 | FAILED_TO_CREATE_SESSION: "Impossible de créer la session. Veuillez réessayer.", |
| 188 | }, |
| 189 | }, |
| 190 | }), |
| 191 | ...(env.TURNSTILE_SECRET_KEY |
| 192 | ? [ |
| 193 | captcha({ |
| 194 | provider: "cloudflare-turnstile", |
| 195 | secretKey: env.TURNSTILE_SECRET_KEY |
| 196 | }), |
| 197 | ] |
| 198 | : []), |
| 199 | ], |
| 200 | }); |
| 201 | } |
| 202 | |
| 203 | export function getAuth(): |
| 204 | if (_auth) return |
| 205 | if (!_authPromise) |
| 206 | _authPromise = buildAuth() |
| 207 | _auth = a; |
| 208 | return a; |
| 209 | }); |
| 210 | } |
| 211 | return _authPromise; |
| 212 | } |