examples: fix error handling in auth example

This commit is contained in:
Douglas Christopher Wilson 2022-02-02 00:44:28 -05:00
parent c221b8596e
commit 69997cbdbe
2 changed files with 20 additions and 4 deletions

View File

@ -59,14 +59,14 @@ function authenticate(name, pass, fn) {
if (!module.parent) console.log('authenticating %s:%s', name, pass);
var user = users[name];
// query the db for the given username
if (!user) return fn(new Error('cannot find user'));
if (!user) return fn(null, null)
// apply the same algorithm to the POSTed password, applying
// the hash against the pass / salt, if there is a match we
// found the user
hash({ password: pass, salt: user.salt }, function (err, pass, salt, hash) {
if (err) return fn(err);
if (hash === user.hash) return fn(null, user)
fn(new Error('invalid password'));
fn(null, null)
});
}
@ -99,8 +99,9 @@ app.get('/login', function(req, res){
res.render('login');
});
app.post('/login', function(req, res){
app.post('/login', function (req, res, next) {
authenticate(req.body.username, req.body.password, function(err, user){
if (err) return next(err)
if (user) {
// Regenerate session when signing in
// to prevent fixation

View File

@ -22,7 +22,7 @@ describe('auth', function(){
.expect(200, /<form/, done)
})
it('should display login error', function(done){
it('should display login error for bad user', function (done) {
request(app)
.post('/login')
.type('urlencoded')
@ -36,6 +36,21 @@ describe('auth', function(){
.expect(200, /Authentication failed/, done)
})
})
it('should display login error for bad password', function (done) {
request(app)
.post('/login')
.type('urlencoded')
.send('username=tj&password=nogood')
.expect('Location', '/login')
.expect(302, function (err, res) {
if (err) return done(err)
request(app)
.get('/login')
.set('Cookie', getCookie(res))
.expect(200, /Authentication failed/, done)
})
})
})
describe('GET /logout',function(){