Skip to content

Commit 9d69ea7

Browse files
author
Peter Marton
committedAug 7, 2017
fix(login): use bcrypt
1 parent 7accca3 commit 9d69ea7

File tree

3 files changed

+30
-8
lines changed

3 files changed

+30
-8
lines changed
 

‎README.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,8 @@
33
1. `git clone git@github.com:RisingStack/nodehero-authentication.git`
44
2. `cd nodehero-authentication`
55
3. `npm install`
6-
4. `npm start`
6+
4. `REDIS_STORE_URI=redis://localhost REDIS_STORE_SECRET=my-strong-secret npm start`
7+
8+
## Pre requirements
9+
10+
- Running [Redis](https://redis.io/) database

‎app/authentication/init.js

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,18 @@
11
const passport = require('passport')
2+
const bcrypt = require('bcrypt')
23
const LocalStrategy = require('passport-local').Strategy
34

45
const authenticationMiddleware = require('./middleware')
56

7+
// Generate Password
8+
const saltRounds = 10
9+
const myPlaintextPassword = 'my-password'
10+
const salt = bcrypt.genSaltSync(saltRounds)
11+
const passwordHash = bcrypt.hashSync(myPlaintextPassword, salt)
12+
613
const user = {
714
username: 'test-user',
8-
password: 'test-password',
15+
passwordHash,
916
id: 1
1017
}
1118

@@ -26,18 +33,28 @@ passport.deserializeUser(function (username, cb) {
2633

2734
function initPassport () {
2835
passport.use(new LocalStrategy(
29-
function(username, password, done) {
30-
findUser(username, function (err, user) {
36+
(username, password, done) => {
37+
findUser(username, (err, user) => {
3138
if (err) {
3239
return done(err)
3340
}
41+
42+
// User not found
3443
if (!user) {
44+
console.log('User not found')
3545
return done(null, false)
3646
}
37-
if (password !== user.password ) {
38-
return done(null, false)
39-
}
40-
return done(null, user)
47+
48+
// Always use hashed passwords and fixed time comparison
49+
bcrypt.compare(password, user.passwordHash, (err, isValid) => {
50+
if (err) {
51+
return done(err)
52+
}
53+
if (!isValid) {
54+
return done(null, false)
55+
}
56+
return done(null, user)
57+
})
4158
})
4259
}
4360
))

‎package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
},
2020
"homepage": "https://github.com/RisingStack/nodehero-authentication#readme",
2121
"dependencies": {
22+
"bcrypt": "1.0.2",
2223
"body-parser": "1.15.1",
2324
"connect-redis": "3.0.2",
2425
"express": "4.13.4",

0 commit comments

Comments
 (0)