11import { serializeJson } from '../../util.js' ;
2- import { HttpEndpoint , HttpHandler } from '../http-index.js' ;
2+ import { HttpEndpoint , HttpHandler , HttpRequest } from '../http-index.js' ;
33import { httpAuthentication } from '../groups.js' ;
44
5+ export const checkBasicAuth = ( req : HttpRequest , username : string , password : string ) : boolean => {
6+ const authHeader = req . headers [ 'authorization' ] ;
7+ if ( ! authHeader ) return false ;
8+
9+ const expectedAuth = Buffer . from ( `${ username } :${ password } ` ) . toString ( 'base64' ) ;
10+ const [ authType , authValue ] = authHeader . split ( ' ' ) ;
11+ return authType === 'Basic' && authValue === expectedAuth ;
12+ } ;
13+
514const matchPath = ( path : string ) =>
615 ! ! path . match ( / ^ \/ b a s i c - a u t h \/ ( [ ^ \/ ] + ) \/ ( [ ^ \/ ] + ) $ / ) ;
716
817const handle : HttpHandler = ( req , res , { path } ) => {
918 const [ username , password ] = path . split ( '/' ) . slice ( 2 ) ;
10- const authHeader = req . headers [ 'authorization' ] ;
1119
12- if ( authHeader === undefined ) {
20+ if ( ! req . headers [ 'authorization' ] ) {
1321 res . writeHead ( 401 , {
1422 'www-authenticate' : 'Basic realm="Fake Realm"'
1523 } ) . end ( ) ;
1624 return ;
1725 }
1826
19- const expectedAuth = Buffer . from ( `${ username } :${ password } ` ) . toString ( 'base64' ) ;
20- const [ authType , authValue ] = authHeader . split ( ' ' ) ;
21- if ( authType === 'Basic' && authValue === expectedAuth ) {
27+ if ( checkBasicAuth ( req , username , password ) ) {
2228 res . writeHead ( 200 , {
2329 'content-type' : 'application/json'
2430 } ) ;
@@ -42,4 +48,4 @@ export const basicAuth: HttpEndpoint = {
4248 examples : [ '/basic-auth/admin/secret' ] ,
4349 group : httpAuthentication
4450 }
45- } ;
51+ } ;
0 commit comments