Skip to content

Commit

Permalink
examples: fix error handling in auth example
Browse files Browse the repository at this point in the history
  • Loading branch information
dougwilson committed Feb 2, 2022
1 parent c221b85 commit 69997cb
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
7 changes: 4 additions & 3 deletions examples/auth/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
});
}

Expand Down Expand Up @@ -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
Expand Down
17 changes: 16 additions & 1 deletion test/acceptance/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand All @@ -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(){
Expand Down

0 comments on commit 69997cb

Please sign in to comment.