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