Skip to content

Commit

Permalink
refac: add esm dist format, rewrite in typescript
Browse files Browse the repository at this point in the history
  • Loading branch information
hormesiel committed May 15, 2020
1 parent 4ea1322 commit 3b7be47
Show file tree
Hide file tree
Showing 5 changed files with 3,325 additions and 113 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
dist/
node_modules/
44 changes: 0 additions & 44 deletions index.js

This file was deleted.

64 changes: 64 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Imports

import type * as http from 'http';
import readCredentials from 'basic-auth';
import serveStatic from 'serve-static';

// Types

interface Options {
directory?: string;
realm?: string;

onAuthFailed?: (res) => void;
}

type ValidatorFunction = (username: string, password: string) => boolean;

// Variables

const optionsDefaultValues: Options = {
directory: process.cwd(),
realm: 'default-realm',

onAuthFailed: res => res.write('401 Unauthorized') // by default send a basic error message
};

// Exports

export default (url: string, validator: ValidatorFunction, optionsUserValues: Options = {}): http.RequestListener => {
// Check required parameters

if (typeof url !== 'string')
throw new Error('`url` is not a string');
if (typeof validator !== 'function')
throw new Error('`validator` is not a function');

// Make sure all options are initialized

const options = {
...optionsDefaultValues,
...optionsUserValues,
};

// Everything OK

const serve = serveStatic(options.directory);

return (req: http.IncomingMessage, res: http.ServerResponse) => {
if (req.url.startsWith(url)) { // if request URL requires authentication
const credentials = readCredentials(req);

if (!credentials || !validator(credentials.name, credentials.pass)) { // if credentials are missing / invalid
res.writeHead(401, { 'WWW-Authenticate': `Basic realm="${options.realm}"` });
options.onAuthFailed(res); // tell the user
return res.end(); // don't serve the requested file
}
}

serve(req, res, () => {
res.statusCode = 404;
res.end('404 Not Found');
});
};
};
13 changes: 12 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,21 @@
],
"homepage": "https://github.com/flawyte/static-auth",
"license": "MIT",
"main": "index.js",
"repository": "github:flawyte/static-auth",

"main": "dist/static-auth.js",
"module": "dist/static-auth.esm.js",
"source": "index.ts",

"scripts": {
"build": "microbundle"
},

"dependencies": {
"basic-auth": "^2.0.1",
"serve-static": "^1.14.1"
},
"devDependencies": {
"microbundle": "^0.12.0"
}
}
Loading

0 comments on commit 3b7be47

Please sign in to comment.