Skip to content
Myr

basic-auth.ts

This file

Path

src/middleware/basic-auth/basic-auth.ts

65 lines · 1.6 KiB · TypeScript

Last changed by

refactor(utils): better management for utils modules to avoid kitchen sink issue (#59)Minghebefore adoptionc522636

History of this file

Take it

feat(basic-auth): basic-auth middleware (#28)Minghebefore adoptioncb4f3d6

line 1why, one step back
1import type { Context } from '../../context'

refactor(utils): better management for utils modules to avoid kitchen sink issue (#59)Minghebefore adoptionc522636

line 2why, one step back
2import { timingSafeEqual } from '../../utils/buffer'

feat(basic-auth): basic-auth middleware (#28)Minghebefore adoptioncb4f3d6

lines 3–65why, one step back
3
4const CREDENTIALS_REGEXP =5 /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/6const USER_PASS_REGEXP = /^([^:]*):(.*)$/78const auth = (req: Request) => {9 if (!req) {10 throw new TypeError('argument req is required')11 }1213 if (typeof req !== 'object') {14 throw new TypeError('argument req is required to be an object')15 }1617 if (!req.headers || typeof req.headers !== 'object') {18 throw new TypeError('argument req is required to have headers property')19 }2021 const match = CREDENTIALS_REGEXP.exec(req.headers.get('Authorization'))22 if (!match) {23 return undefined24 }2526 const userPass = USER_PASS_REGEXP.exec(decodeBase64(match[1]))2728 if (!userPass) {29 return undefined30 }3132 return { username: userPass[1], password: userPass[2] }33}3435function decodeBase64(str: string) {36 return Buffer.from(str, 'base64').toString()37}3839export const basicAuth = (options: {40 username: string;41 password: string;42 realm?: string;43}) => {44 if (!options.realm) {45 options.realm = 'Secure Area'46 }4748 return async (ctx: Context, next: Function) => {49 const user = auth(ctx.req)50 const usernameEqual = user && await timingSafeEqual(options.username, user.username)51 const passwordEqual = user && await timingSafeEqual(options.password, user.password)5253 if (!user || !usernameEqual || !passwordEqual) {54 ctx.res = new Response('Unauthorized', {55 status: 401,56 headers: {57 'WWW-Authenticate':58 'Basic realm="' + options.realm.replace(/"/g, '\\"') + '"',59 },60 })61 return62 }63 return next()64 }65}