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