-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
routes.js
95 lines (81 loc) · 2.33 KB
/
routes.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
'use strict'
const securePassword = require('secure-password')
const DUPLICATE_KEY_ERROR = 11000
module.exports = async function (app, opts) {
const users = app.mongo.db.collection('users')
const pwd = securePassword()
// Ensure that there is an index on username
// so we do not store duplicated entries
await users.createIndex({
username: 1
}, { unique: true })
app.post('/signup', {
schema: {
body: {
type: 'object',
properties: {
username: {
type: 'string'
},
password: {
type: 'string'
}
},
required: ['username', 'password']
}
}
}, async function (req, reply) {
const { username, password } = req.body
const hashedPassword = await pwd.hash(Buffer.from(password))
try {
await users.insertOne({ username, hashedPassword })
} catch (err) {
if (err.code === DUPLICATE_KEY_ERROR) {
reply.code(400).send({ status: 'not ok' })
return
}
throw err
}
const token = await reply.jwtSign({ username })
return { status: 'ok', token }
})
app.get('/me', {
preValidation: async (request, reply) => {
await request.jwtVerify()
}
}, async function (req, reply) {
return req.user
})
app.post('/login', {
schema: {
body: {
type: 'object',
properties: {
username: {
type: 'string'
},
password: {
type: 'string'
}
},
required: ['username', 'password']
}
}
}, async function (req, reply) {
const { username, password } = req.body
const user = await users.findOne({ username })
const res = await pwd.verify(Buffer.from(password), user.hashedPassword.buffer)
if (res === securePassword.INVALID_UNRECOGNIZED_HASH) {
throw new Error('invalid unrecognized hash')
} else if (res === securePassword.INVALID) {
reply.code(400)
return { status: 'not ok' }
} else if (res === securePassword.VALID_NEEDS_REHASH) {
req.log.info({ username }, 'password needs rehashing')
const hashedPassword = await pwd.hash(Buffer.from(password))
await users.update({ _id: user._id }, { hashedPassword })
}
const token = await reply.jwtSign({ username })
return { status: 'ok', token }
})
}