basic-auth.ts
This file
Path
src/middleware/basic-auth/basic-auth.ts
55 lines · 1.6 KiB · TypeScript
Last changed by
feat: Basic-auth with polyfill (#86)Yusuke Wadabefore adoptiond5280a1
History of this fileTake it
feat(basic-auth): basic-auth middleware (#28)Minghebefore adoptioncb4f3d6
line 1why, one step back1import type { Context } from '../../context'feat: Basic-auth with polyfill (#86)Yusuke Wadabefore adoptiond5280a1
line 2why, one step back2import { timingSafeEqual, decodeBase64 } from '../../utils/buffer'feat(basic-auth): basic-auth middleware (#28)Minghebefore adoptioncb4f3d6
line 3why, one step back3fix: basic auth (#83)Yusuke Wadabefore adoption0fe95bc
line 4why, one step back4const CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/feat(basic-auth): basic-auth middleware (#28)Minghebefore adoptioncb4f3d6
lines 5–33why, one step back5const USER_PASS_REGEXP = /^([^:]*):(.*)$/67const auth = (req: Request) => {8 if (!req) {9 throw new TypeError('argument req is required')10 }1112 if (typeof req !== 'object') {13 throw new TypeError('argument req is required to be an object')14 }1516 if (!req.headers || typeof req.headers !== 'object') {17 throw new TypeError('argument req is required to have headers property')18 }1920 const match = CREDENTIALS_REGEXP.exec(req.headers.get('Authorization'))21 if (!match) {22 return undefined23 }2425 const userPass = USER_PASS_REGEXP.exec(decodeBase64(match[1]))2627 if (!userPass) {28 return undefined29 }3031 return { username: userPass[1], password: userPass[2] }32}33fix: basic auth (#83)Yusuke Wadabefore adoption0fe95bc
line 34why, one step back34export const basicAuth = (options: { username: string; password: string; realm?: string }) => {feat(basic-auth): basic-auth middleware (#28)Minghebefore adoptioncb4f3d6
lines 35–40why, one step back35 if (!options.realm) {36 options.realm = 'Secure Area'37 }3839 return async (ctx: Context, next: Function) => {40 const user = auth(ctx.req)fix: basic auth (#83)Yusuke Wadabefore adoption0fe95bc
lines 41–42why, one step back41 const usernameEqual = user && (await timingSafeEqual(options.username, user.username))42 const passwordEqual = user && (await timingSafeEqual(options.password, user.password))feat(basic-auth): basic-auth middleware (#28)Minghebefore adoptioncb4f3d6
lines 43–47why, one step back4344 if (!user || !usernameEqual || !passwordEqual) {45 ctx.res = new Response('Unauthorized', {46 status: 401,47 headers: {fix: basic auth (#83)Yusuke Wadabefore adoption0fe95bc
line 48why, one step back48 'WWW-Authenticate': 'Basic realm="' + options.realm.replace(/"/g, '\\"') + '"',feat(basic-auth): basic-auth middleware (#28)Minghebefore adoptioncb4f3d6
lines 49–55why, one step back49 },50 })51 return52 }53 return next()54 }55}