UNPKG

@trifrost/core

Version:

Blazingly fast, runtime-agnostic server framework for modern edge and node environments

40 lines (39 loc) 1.84 kB
import { Sym_TriFrostDescription, Sym_TriFrostFingerPrint, Sym_TriFrostName } from '../../types/constants'; import { Sym_TriFrostMiddlewareAuth } from './types'; /* Specific symbol attached to auth mware to identify them by */ export const Sym_TriFrostMiddlewareBearerAuth = Symbol('TriFrost.Middleware.BearerAuth'); /** * HTTP Bearer Token Authentication middleware. * * This middleware extracts the `Authorization` header using the Bearer scheme, * retrieves the token, and calls the provided validate() function. If valid, * the `$auth` state is set on the context. * * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#bearer_authentication * * @example * .use(BearerAuth({ * validate: (ctx, token) => token === ctx.env.API_TOKEN * })) */ export function BearerAuth(opts) { if (typeof opts?.validate !== 'function') throw new Error('TriFrostMiddleware@BearerAuth: A validate function must be provided'); const mware = async function TriFrostBearerAuth(ctx) { const raw = ctx.headers.authorization; if (typeof raw !== 'string' || !raw.startsWith('Bearer ')) return ctx.status(401); const token = raw.slice(7).trim(); const result = await opts.validate(ctx, token); if (!result) return ctx.status(401); const authenticated = result === true ? { token } : result; return ctx.setState({ $auth: authenticated }); }; /* Add symbols for introspection/use further down the line */ Reflect.set(mware, Sym_TriFrostName, 'TriFrostBearerAuth'); Reflect.set(mware, Sym_TriFrostDescription, 'HTTP Bearer Token Authentication middleware'); Reflect.set(mware, Sym_TriFrostMiddlewareAuth, true); Reflect.set(mware, Sym_TriFrostFingerPrint, Sym_TriFrostMiddlewareBearerAuth); return mware; }