Created
May 14, 2020 19:21
-
-
Save kgao/a42b30f7078d69669e5aa36da2ffe295 to your computer and use it in GitHub Desktop.
Basic Auth
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
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