-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
60 lines (53 loc) · 1.93 KB
/
db.js
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import crypto from 'crypto'
import { v4 as uuidv4 } from 'uuid'
export function getAllUsers(req) {
// For demo purpose only. You are not likely to have to return all users.
return req.session.users
}
export function createUser(req, { username, password, name }) {
// Here you should create the user and save the salt and hashed password (some dbs may have
// authentication methods that will do it for you so you don't have to worry about it):
const salt = crypto.randomBytes(16).toString('hex')
const hash = crypto
.pbkdf2Sync(password, salt, 1000, 64, 'sha512')
.toString('hex')
const user = {
id: uuidv4(),
createdAt: Date.now(),
username,
name,
hash,
salt,
}
// Here you should insert the user into the database
// await db.createUser(user)
req.session.users.push(user)
}
export function findUserByUsername(req, username) {
// Here you find the user based on id/username in the database
// const user = await db.findUserById(id)
return req.session.users.find((user) => user.username === username)
}
export function updateUserByUsername(req, username, update) {
// Here you update the user based on id/username in the database
// const user = await db.updateUserById(id, update)
const user = req.session.users.find((u) => u.username === username)
Object.assign(user, update)
return user
}
export function deleteUser(req, username) {
// Here you should delete the user in the database
// await db.deleteUser(req.user)
req.session.users = req.session.users.filter(
(user) => user.username !== req.user.username
)
}
// Compare the password of an already fetched user (using `findUserByUsername`) and compare the
// password for a potential match
export function validatePassword(user, inputPassword) {
const inputHash = crypto
.pbkdf2Sync(inputPassword, user.salt, 1000, 64, 'sha512')
.toString('hex')
const passwordsMatch = user.hash === inputHash
return passwordsMatch
}