Created
January 29, 2020 09:36
-
-
Save peter/28d486255eefeab5a19de3363335b220 to your computer and use it in GitHub Desktop.
Naive Basic Auth Middleware for Koa - First Draft
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable no-plusplus */ | |
import crypto from 'crypto'; | |
function parse(header: string | null): string | null { | |
const match = (header || '').match(/^Basic (\S{3,300})$/); | |
return match && Buffer.from(match[1], 'base64').toString(); | |
} | |
function isEqual(s1: string | null, s2: string | null): boolean { | |
return ( | |
s1 != null && | |
s2 != null && | |
s1.length === s2.length && | |
crypto.timingSafeEqual(Buffer.from(s1), Buffer.from(s2)) | |
); | |
} | |
// Haven't tested if this is timing safe | |
// function isEqualNaive(s1: string | null, s2: string | null): boolean { | |
// if (!s1 || !s2 || s1.length !== s2.length) return false; | |
// let allEqual = true; | |
// for (let i = 0; i < s1.length; i++) { | |
// allEqual = s1[i] === s2[i] && allEqual; | |
// } | |
// return allEqual; | |
// } | |
export function basicAuthMiddleware({ name, pass }: any): Function { | |
const credentials = [name, pass].join(':'); | |
return async (ctx: any, next: any): Promise<any> => { | |
const header = ctx.request.get('Authorization'); | |
if (isEqual(parse(header), credentials)) { | |
await next(); | |
} else { | |
ctx.status = 401; | |
ctx.set('WWW-Authenticate', 'Basic'); | |
ctx.body = 'Access denied'; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment