Skip to content

Instantly share code, notes, and snippets.

@kgao
Created May 14, 2020 19:21
Show Gist options
  • Save kgao/a42b30f7078d69669e5aa36da2ffe295 to your computer and use it in GitHub Desktop.
Save kgao/a42b30f7078d69669e5aa36da2ffe295 to your computer and use it in GitHub Desktop.
Basic Auth
var express = require('express'),
router = express.Router(),
basicAuth = require('basic-auth');
router.use(function (req, res, next) {
console.log(req.method + req.url);
next();
});
var auth = function (req, res, next) {
function unauthorized(res) {
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return res.send(401);
};
var user = basicAuth(req);
if (!user || !user.name || !user.pass) {
return unauthorized(res);
};
if (user.name === conf.admin.username && user.pass === conf.admin.password) {
return next();
} else {
return unauthorized(res);
};
};
router.get('/admin', auth, function (req, res) { //auth
res.render('pages/admin');
});
router.get('/test', function (req, res) { //no-auth
res.render('pages/test');
});
module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment