Skip to content
Myr

index.ts

This file

Path

src/middleware/basic-auth/index.ts

153 lines · 4.9 KiB · TypeScript

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–153why, one step back
1/**
2 * @module3 * Basic Auth Middleware for Hono.4 */56import type { Context } from '../../context'7import { HTTPException } from '../../http-exception'8import type { MiddlewareHandler } from '../../types'9import { auth } from '../../utils/basic-auth'10import { timingSafeEqual } from '../../utils/buffer'1112type MessageFunction = (c: Context) => string | object | Promise<string | object>1314type BasicAuthOptions =15 | {16 username: string17 password: string18 realm?: string19 hashFunction?: Function20 invalidUserMessage?: string | object | MessageFunction21 onAuthSuccess?: (c: Context, username: string) => void | Promise<void>22 }23 | {24 verifyUser: (username: string, password: string, c: Context) => boolean | Promise<boolean>25 realm?: string26 hashFunction?: Function27 invalidUserMessage?: string | object | MessageFunction28 onAuthSuccess?: (c: Context, username: string) => void | Promise<void>29 }3031/**32 * Basic Auth Middleware for Hono.33 *34 * @see {@link https://hono.dev/docs/middleware/builtin/basic-auth}35 *36 * @param {BasicAuthOptions} options - The options for the basic authentication middleware.37 * @param {string} options.username - The username for authentication.38 * @param {string} options.password - The password for authentication.39 * @param {string} [options.realm="Secure Area"] - The realm attribute for the WWW-Authenticate header.40 * @param {Function} [options.hashFunction] - The hash function used for secure comparison.41 * @param {Function} [options.verifyUser] - The function to verify user credentials.42 * @param {string | object | MessageFunction} [options.invalidUserMessage="Unauthorized"] - The invalid user message.43 * @param {Function} [options.onAuthSuccess] - Callback function called on successful authentication.44 * @returns {MiddlewareHandler} The middleware handler function.45 * @throws {HTTPException} If neither "username and password" nor "verifyUser" options are provided.46 *47 * @example48 * ```ts49 * const app = new Hono()50 *51 * app.use(52 * '/auth/*',53 * basicAuth({54 * username: 'hono',55 * password: 'ahotproject',56 * })57 * )58 *59 * app.get('/auth/page', (c) => {60 * return c.text('You are authorized')61 * })62 * ```63 *64 * @example65 * ```ts66 * // With onAuthSuccess callback67 * app.use(68 * '/auth/*',69 * basicAuth({70 * username: 'hono',71 * password: 'ahotproject',72 * onAuthSuccess: (c, username) => {73 * c.set('user', { name: username, role: 'admin' })74 * console.log(`User ${username} authenticated`)75 * },76 * })77 * )78 * ```79 */80export const basicAuth = (81 options: BasicAuthOptions,82 ...users: { username: string; password: string }[]83): MiddlewareHandler => {84 const usernamePasswordInOptions = 'username' in options && 'password' in options85 const verifyUserInOptions = 'verifyUser' in options8687 if (!(usernamePasswordInOptions || verifyUserInOptions)) {88 throw new Error(89 'basic auth middleware requires options for "username and password" or "verifyUser"'90 )91 }9293 if (!options.realm) {94 options.realm = 'Secure Area'95 }9697 if (!options.invalidUserMessage) {98 options.invalidUserMessage = 'Unauthorized'99 }100101 if (usernamePasswordInOptions) {102 users.unshift({ username: options.username, password: options.password })103 }104105 return async function basicAuth(ctx, next) {106 const requestUser = auth(ctx.req.raw)107 if (requestUser) {108 if (verifyUserInOptions) {109 if (await options.verifyUser(requestUser.username, requestUser.password, ctx)) {110 if (options.onAuthSuccess) {111 await options.onAuthSuccess(ctx, requestUser.username)112 }113 await next()114 return115 }116 } else {117 for (const user of users) {118 const [usernameEqual, passwordEqual] = await Promise.all([119 timingSafeEqual(user.username, requestUser.username, options.hashFunction),120 timingSafeEqual(user.password, requestUser.password, options.hashFunction),121 ])122 if (usernameEqual && passwordEqual) {123 if (options.onAuthSuccess) {124 await options.onAuthSuccess(ctx, requestUser.username)125 }126 await next()127 return128 }129 }130 }131 }132 // Invalid user.133 const status = 401134 const headers = {135 'WWW-Authenticate': 'Basic realm="' + options.realm?.replace(/"/g, '\\"') + '"',136 }137 const responseMessage =138 typeof options.invalidUserMessage === 'function'139 ? await options.invalidUserMessage(ctx)140 : options.invalidUserMessage141 const res =142 typeof responseMessage === 'string'143 ? new Response(responseMessage, { status, headers })144 : new Response(JSON.stringify(responseMessage), {145 status,146 headers: {147 ...headers,148 'content-type': 'application/json',149 },150 })151 throw new HTTPException(status, { res })152 }153}