UNPKG

better-auth

Version:

The most comprehensive authentication library for TypeScript.

353 lines (348 loc) • 12.2 kB
import * as z from 'zod/v4'; import { i as createAuthMiddleware, j as createAuthEndpoint, u as sendVerificationEmailFn, B as BASE_ERROR_CODES } from '../../shared/better-auth.z3dsxLxE.mjs'; import { APIError } from 'better-call'; import { setSessionCookie } from '../../cookies/index.mjs'; import { m as mergeSchema } from '../../shared/better-auth.n2KFGwjY.mjs'; import '../../shared/better-auth.8zoxzg-F.mjs'; import '../../shared/better-auth.DBGfIDnh.mjs'; import 'defu'; import '../../shared/better-auth.CW6D9eSx.mjs'; import '@better-auth/utils/hash'; import '@better-auth/utils/base64'; import '../../crypto/index.mjs'; import '@noble/ciphers/chacha'; import '@noble/ciphers/utils'; import '@noble/ciphers/webcrypto'; import 'jose'; import '@noble/hashes/scrypt'; import '@better-auth/utils'; import '@better-auth/utils/hex'; import '@noble/hashes/utils'; import '../../shared/better-auth.B4Qoxdgc.mjs'; import '@better-auth/utils/random'; import '@better-fetch/fetch'; import '../../shared/better-auth.VTXNLFMT.mjs'; import '../../shared/better-auth.DdzSJf-n.mjs'; import '../../shared/better-auth.tB5eU6EY.mjs'; import '@better-auth/utils/hmac'; import '@better-auth/utils/binary'; import 'jose/errors'; const getSchema = (normalizer) => { return { user: { fields: { username: { type: "string", required: false, sortable: true, unique: true, returned: true }, displayUsername: { type: "string", required: false, transform: { input(value) { return value == null ? value : normalizer(value); } } } } } }; }; const USERNAME_ERROR_CODES = { INVALID_USERNAME_OR_PASSWORD: "invalid username or password", EMAIL_NOT_VERIFIED: "email not verified", UNEXPECTED_ERROR: "unexpected error", USERNAME_IS_ALREADY_TAKEN: "username is already taken. please try another.", USERNAME_TOO_SHORT: "username is too short", USERNAME_TOO_LONG: "username is too long", INVALID_USERNAME: "username is invalid" }; function defaultUsernameValidator(username2) { return /^[a-zA-Z0-9_.]+$/.test(username2); } const username = (options) => { const normalizer = (username2) => { if (options?.usernameNormalization === false) { return username2; } if (options?.usernameNormalization) { return options.usernameNormalization(username2); } return username2.toLowerCase(); }; return { id: "username", endpoints: { signInUsername: createAuthEndpoint( "/sign-in/username", { method: "POST", body: z.object({ username: z.string().meta({ description: "The username of the user" }), password: z.string().meta({ description: "The password of the user" }), rememberMe: z.boolean().meta({ description: "Remember the user session" }).optional(), callbackURL: z.string().meta({ description: "The URL to redirect to after email verification" }).optional() }), metadata: { openapi: { summary: "Sign in with username", description: "Sign in with username", responses: { 200: { description: "Success", content: { "application/json": { schema: { type: "object", properties: { token: { type: "string", description: "Session token for the authenticated session" }, user: { $ref: "#/components/schemas/User" } }, required: ["token", "user"] } } } } } } } }, async (ctx) => { if (!ctx.body.username || !ctx.body.password) { ctx.context.logger.error("Username or password not found"); throw new APIError("UNAUTHORIZED", { message: USERNAME_ERROR_CODES.INVALID_USERNAME_OR_PASSWORD }); } const minUsernameLength = options?.minUsernameLength || 3; const maxUsernameLength = options?.maxUsernameLength || 30; if (ctx.body.username.length < minUsernameLength) { ctx.context.logger.error("Username too short", { username: ctx.body.username }); throw new APIError("UNPROCESSABLE_ENTITY", { message: USERNAME_ERROR_CODES.USERNAME_TOO_SHORT }); } if (ctx.body.username.length > maxUsernameLength) { ctx.context.logger.error("Username too long", { username: ctx.body.username }); throw new APIError("UNPROCESSABLE_ENTITY", { message: USERNAME_ERROR_CODES.USERNAME_TOO_LONG }); } const validator = options?.usernameValidator || defaultUsernameValidator; if (!validator(ctx.body.username)) { throw new APIError("UNPROCESSABLE_ENTITY", { message: USERNAME_ERROR_CODES.INVALID_USERNAME }); } const user = await ctx.context.adapter.findOne({ model: "user", where: [ { field: "username", value: normalizer(ctx.body.username) } ] }); if (!user) { await ctx.context.password.hash(ctx.body.password); ctx.context.logger.error("User not found", { username: ctx.body.username }); throw new APIError("UNAUTHORIZED", { message: USERNAME_ERROR_CODES.INVALID_USERNAME_OR_PASSWORD }); } if (!user.emailVerified && ctx.context.options.emailAndPassword?.requireEmailVerification) { await sendVerificationEmailFn(ctx, user); throw new APIError("FORBIDDEN", { message: USERNAME_ERROR_CODES.EMAIL_NOT_VERIFIED }); } const account = await ctx.context.adapter.findOne({ model: "account", where: [ { field: "userId", value: user.id }, { field: "providerId", value: "credential" } ] }); if (!account) { throw new APIError("UNAUTHORIZED", { message: USERNAME_ERROR_CODES.INVALID_USERNAME_OR_PASSWORD }); } const currentPassword = account?.password; if (!currentPassword) { ctx.context.logger.error("Password not found", { username: ctx.body.username }); throw new APIError("UNAUTHORIZED", { message: USERNAME_ERROR_CODES.INVALID_USERNAME_OR_PASSWORD }); } const validPassword = await ctx.context.password.verify({ hash: currentPassword, password: ctx.body.password }); if (!validPassword) { ctx.context.logger.error("Invalid password"); throw new APIError("UNAUTHORIZED", { message: USERNAME_ERROR_CODES.INVALID_USERNAME_OR_PASSWORD }); } const session = await ctx.context.internalAdapter.createSession( user.id, ctx, ctx.body.rememberMe === false ); if (!session) { return ctx.json(null, { status: 500, body: { message: BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION } }); } await setSessionCookie( ctx, { session, user }, ctx.body.rememberMe === false ); return ctx.json({ token: session.token, user: { id: user.id, email: user.email, emailVerified: user.emailVerified, username: user.username, name: user.name, image: user.image, createdAt: user.createdAt, updatedAt: user.updatedAt } }); } ), isUsernameAvailable: createAuthEndpoint( "/is-username-available", { method: "POST", body: z.object({ username: z.string().meta({ description: "The username to check" }) }) }, async (ctx) => { const username2 = ctx.body.username; if (!username2) { throw new APIError("UNPROCESSABLE_ENTITY", { message: USERNAME_ERROR_CODES.INVALID_USERNAME }); } const user = await ctx.context.adapter.findOne({ model: "user", where: [ { field: "username", value: username2.toLowerCase() } ] }); if (user) { return ctx.json({ available: false }); } return ctx.json({ available: true }); } ) }, schema: mergeSchema(getSchema(normalizer), options?.schema), hooks: { before: [ { matcher(context) { return context.path === "/sign-up/email" || context.path === "/update-user"; }, handler: createAuthMiddleware(async (ctx) => { const username2 = ctx.body.username; if (username2 !== void 0 && typeof username2 === "string") { const minUsernameLength = options?.minUsernameLength || 3; const maxUsernameLength = options?.maxUsernameLength || 30; if (username2.length < minUsernameLength) { throw new APIError("UNPROCESSABLE_ENTITY", { message: USERNAME_ERROR_CODES.USERNAME_TOO_SHORT }); } if (username2.length > maxUsernameLength) { throw new APIError("UNPROCESSABLE_ENTITY", { message: USERNAME_ERROR_CODES.USERNAME_TOO_LONG }); } const validator = options?.usernameValidator || defaultUsernameValidator; const valid = await validator(username2); if (!valid) { throw new APIError("UNPROCESSABLE_ENTITY", { message: USERNAME_ERROR_CODES.INVALID_USERNAME }); } const user = await ctx.context.adapter.findOne({ model: "user", where: [ { field: "username", value: normalizer(username2) } ] }); const blockChangeSignUp = ctx.path === "/sign-up/email" && user; const blockChangeUpdateUser = ctx.path === "/update-user" && user && ctx.context.session && user.id !== ctx.context.session.session.userId; if (blockChangeSignUp || blockChangeUpdateUser) { throw new APIError("UNPROCESSABLE_ENTITY", { message: USERNAME_ERROR_CODES.USERNAME_IS_ALREADY_TAKEN }); } } }) }, { matcher(context) { return context.path === "/sign-up/email" || context.path === "/update-user"; }, handler: createAuthMiddleware(async (ctx) => { if (ctx.body.username) { ctx.body.displayUsername ||= ctx.body.username; ctx.body.username = normalizer(ctx.body.username); } }) } ] }, $ERROR_CODES: USERNAME_ERROR_CODES }; }; export { USERNAME_ERROR_CODES, username };