forked from kentcdodds/testing-workshop
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
44 lines (37 loc) · 1.16 KB
/
Copy pathauth.js
File metadata and controls
44 lines (37 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const crypto = require('crypto')
const jwt = require('jsonwebtoken')
const secret = 'secret'
const iterations = process.env.NODE_ENV === 'production' ? 100000 : 1
// seconds/minute * minutes/hour * hours/day * 60 days
const sixtyDaysInSeconds = 60 * 60 * 24 * 60
// to keep our tests reliable, we'll use the requireTime if we're not in production
// and we'll use Date.now() if we are.
const requireTime = Date.now()
const now = () =>
process.env.NODE_ENV === 'production' ? Date.now() : requireTime
function getSaltAndHash(password) {
const salt = crypto.randomBytes(16).toString('hex')
const hash = crypto
.pbkdf2Sync(password, salt, iterations, 512, 'sha512')
.toString('hex')
return {salt, hash}
}
function isPasswordValid(password, {salt, hash}) {
return (
hash ===
crypto.pbkdf2Sync(password, salt, iterations, 512, 'sha512').toString('hex')
)
}
function getUserToken({id, username}) {
const issuedAt = Math.floor(now() / 1000)
return jwt.sign(
{
id,
username,
iat: issuedAt,
exp: issuedAt + sixtyDaysInSeconds,
},
secret,
)
}
module.exports = {getSaltAndHash, isPasswordValid, getUserToken, secret}