feat(basic-auth): add `verifyUser` option (#2450)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat(basic-auth): add `verifyUser` option * denoify
authored by Yusuke Wada · committed by GitHub · parent 7425ffb · Browse files · 3 files·+120 added−20 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+120 added−20 removed
- tests:+42 added−0 removed
- other:+78 added−20 removed
Provenance
- Commit
545203f- Tree
a2a7ebc- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
7425ffb
3 files changed+120 added−20 removed
modified:deno_dist/middleware/basic-auth/index.ts+39 added-10 removed
1234520 unmodified lines26272829303132333435363738394041424330444546333447484950515253545556575840596061626364656645464748495067686970717273747576777879808182838485867 unmodified linesimport type { Context } from '../../context.ts'import { HTTPException } from '../../http-exception.ts'import type { HonoRequest } from '../../request.ts'import type { MiddlewareHandler } from '../../types.ts'import { timingSafeEqual } from '../../utils/buffer.ts'20 unmodified lines
return { username: userPass[1], password: userPass[2] }}
type BasicAuthOptions = | { username: string password: string realm?: string hashFunction?: Function } | { verifyUser: (username: string, password: string, c: Context) => boolean | Promise<boolean> realm?: string hashFunction?: Function }
export const basicAuth = ( options: { username: string; password: string; realm?: string; hashFunction?: Function }, options: BasicAuthOptions, ...users: { username: string; password: string }[]): MiddlewareHandler => { if (!options) { throw new Error('basic auth middleware requires options for "username and password"') const usernamePasswordInOptions = 'username' in options && 'password' in options const verifyUserInOptions = 'verifyUser' in options
if (!(usernamePasswordInOptions || verifyUserInOptions)) { throw new Error( 'basic auth middleware requires options for "username and password" or "verifyUser"' ) }
if (!options.realm) { options.realm = 'Secure Area' } users.unshift({ username: options.username, password: options.password })
if (usernamePasswordInOptions) { users.unshift({ username: options.username, password: options.password }) }
return async function basicAuth(ctx, next) { const requestUser = auth(ctx.req) if (requestUser) { for (const user of users) { const [usernameEqual, passwordEqual] = await Promise.all([ timingSafeEqual(user.username, requestUser.username, options.hashFunction), timingSafeEqual(user.password, requestUser.password, options.hashFunction), ]) if (usernameEqual && passwordEqual) { if (verifyUserInOptions) { if (await options.verifyUser(requestUser.username, requestUser.password, ctx)) { await next() return } } else { for (const user of users) { const [usernameEqual, passwordEqual] = await Promise.all([ timingSafeEqual(user.username, requestUser.username, options.hashFunction), timingSafeEqual(user.password, requestUser.password, options.hashFunction), ]) if (usernameEqual && passwordEqual) { await next() return } } } } const res = new Response('Unauthorized', { status: 401,7 unmodified linesmodified:src/middleware/basic-auth/index.test.ts+42 added
68 unmodified lines69 const auth = basicAuth({ username: username, password: password })70 return auth(c, next)71 })72 73+ app.use('/verify-user/*', async (c, next) => {74+ const auth = basicAuth({75+ verifyUser: (username, password, c) => {76+ return (77+ c.req.path === '/verify-user' &&78+ username === 'dynamic-user' &&79+ password === 'hono-password'80+ )81+ },82+ })83+ return auth(c, next)84+ })85+86 app.get('/auth/*', (c) => {87 handlerExecuted = true88 return c.text('auth')89 })14 unmodified lines104 handlerExecuted = true105 return c.text('nested')106 })107 108+ app.get('/verify-user', (c) => {109+ handlerExecuted = true110+ return c.text('verify-user')111+ })112+113 it('Should not authorize', async () => {114 const req = new Request('http://localhost/auth/a')115 const res = await app.request(req)116 expect(res).not.toBeNull()84 unmodified lines201 expect(res).not.toBeNull()202 expect(res.status).toBe(401)203 expect(await res.text()).toBe('Unauthorized')204 })205+206+ it('Should authorize - verifyUser', async () => {207+ const credential = Buffer.from('dynamic-user' + ':' + 'hono-password').toString('base64')208+209+ const req = new Request('http://localhost/verify-user')210+ req.headers.set('Authorization', `Basic ${credential}`)211+ const res = await app.request(req)212+ expect(handlerExecuted).toBeTruthy()213+ expect(res).not.toBeNull()214+ expect(res.status).toBe(200)215+ expect(await res.text()).toBe('verify-user')216+ })217+218+ it('Should not authorize - verifyUser', async () => {219+ const credential = Buffer.from('foo' + ':' + 'bar').toString('base64')220+221+ const req = new Request('http://localhost/verify-user')222+ req.headers.set('Authorization', `Basic ${credential}`)223+ const res = await app.request(req)224+ expect(handlerExecuted).toBeFalsy()225+ expect(res).not.toBeNull()226+ expect(res.status).toBe(401)227+ expect(await res.text()).toBe('Unauthorized')228+ })229 })modified:src/middleware/basic-auth/index.ts+39 added-10 removed
1234520 unmodified lines26272829303132333435363738394041424330444546333447484950515253545556575840596061626364656645464748495067686970717273747576777879808182838485867 unmodified linesimport type { Context } from '../../context'import { HTTPException } from '../../http-exception'import type { HonoRequest } from '../../request'import type { MiddlewareHandler } from '../../types'import { timingSafeEqual } from '../../utils/buffer'20 unmodified lines
return { username: userPass[1], password: userPass[2] }}
type BasicAuthOptions = | { username: string password: string realm?: string hashFunction?: Function } | { verifyUser: (username: string, password: string, c: Context) => boolean | Promise<boolean> realm?: string hashFunction?: Function }
export const basicAuth = ( options: { username: string; password: string; realm?: string; hashFunction?: Function }, options: BasicAuthOptions, ...users: { username: string; password: string }[]): MiddlewareHandler => { if (!options) { throw new Error('basic auth middleware requires options for "username and password"') const usernamePasswordInOptions = 'username' in options && 'password' in options const verifyUserInOptions = 'verifyUser' in options
if (!(usernamePasswordInOptions || verifyUserInOptions)) { throw new Error( 'basic auth middleware requires options for "username and password" or "verifyUser"' ) }
if (!options.realm) { options.realm = 'Secure Area' } users.unshift({ username: options.username, password: options.password })
if (usernamePasswordInOptions) { users.unshift({ username: options.username, password: options.password }) }
return async function basicAuth(ctx, next) { const requestUser = auth(ctx.req) if (requestUser) { for (const user of users) { const [usernameEqual, passwordEqual] = await Promise.all([ timingSafeEqual(user.username, requestUser.username, options.hashFunction), timingSafeEqual(user.password, requestUser.password, options.hashFunction), ]) if (usernameEqual && passwordEqual) { if (verifyUserInOptions) { if (await options.verifyUser(requestUser.username, requestUser.password, ctx)) { await next() return } } else { for (const user of users) { const [usernameEqual, passwordEqual] = await Promise.all([ timingSafeEqual(user.username, requestUser.username, options.hashFunction), timingSafeEqual(user.password, requestUser.password, options.hashFunction), ]) if (usernameEqual && passwordEqual) { await next() return } } } } const res = new Response('Unauthorized', { status: 401,7 unmodified lines