Skip to content

Commit ee64226

Browse files
committed
Add support for basic authentication
1 parent 0428086 commit ee64226

File tree

4 files changed

+47
-0
lines changed

4 files changed

+47
-0
lines changed

app.js

+32
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,10 @@ function initApp(config, callback) {
4141
app.server = http.createServer(app.express);
4242
app.webservice = createClient(webserviceUrl);
4343

44+
// Apply basic authentication if necessary
45+
loadBasicAuth(app, config);
46+
47+
// Load middleware
4448
loadMiddleware(app);
4549

4650
// View engine
@@ -63,6 +67,34 @@ function defaultConfig(config) {
6367
return config;
6468
}
6569

70+
function loadBasicAuth(app, config) {
71+
app.express.use((request, response, next) => {
72+
const protection = config.protection.enabled || false;
73+
if (protection) {
74+
const auth = request.headers.authorization;
75+
if (!auth) {
76+
// Prompt the user for credentials
77+
response.set('WWW-Authenticate', 'Basic realm="401"');
78+
return response.status(401).send('Authentication required.');
79+
}
80+
81+
const credentials = Buffer.from(auth.split(' ')[1], 'base64').toString().split(':');
82+
const [username, password] = credentials;
83+
84+
// Use credentials from config
85+
const USER = config.protection.user || '';
86+
const PASS = config.protection.pass || '';
87+
88+
if (username === USER && password === PASS) {
89+
return next(); // Proceed to the next middleware or route
90+
}
91+
response.set('WWW-Authenticate', 'Basic realm="401"'); // Prompt again
92+
return response.status(401).send('Authentication required.');
93+
}
94+
return next();
95+
});
96+
}
97+
6698
function loadMiddleware(app) {
6799
app.express.use(compression());
68100

config/development.sample.json

+5
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22
"port": 4000,
33
"noindex": true,
44
"readonly": false,
5+
"protection": {
6+
"enabled": false,
7+
"user": "pa11y",
8+
"pass": "pa11y"
9+
},
510
"webservice": {
611
"database": "mongodb://localhost/pa11y-webservice-dev",
712
"host": "0.0.0.0",

config/production.sample.json

+5
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22
"port": 4000,
33
"noindex": true,
44
"readonly": false,
5+
"protection": {
6+
"enabled": true,
7+
"user": "pa11y",
8+
"pass": "pa11y"
9+
},
510
"webservice": {
611
"database": "mongodb://localhost/pa11y-webservice",
712
"host": "0.0.0.0",

config/test.sample.json

+5
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22
"port": 4000,
33
"noindex": true,
44
"readonly": false,
5+
"protection": {
6+
"enabled": false,
7+
"user": "pa11y",
8+
"pass": "pa11y"
9+
},
510
"webservice": {
611
"database": "mongodb://127.0.0.1/pa11y-dashboard-integration-test",
712
"host": "127.0.0.1",

0 commit comments

Comments
 (0)