-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
68 lines (63 loc) · 1.5 KB
/
auth.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
const bcrypt = require('bcrypt')
const db = require('./db')
const createAuthDummy = (schemeName) => {
const authDummy = {
name: `DummyAuthentication-${schemeName}`,
register (server, options) {
server.auth.scheme(schemeName, (server, strategyOptions) => ({
authenticate (request, h) {
return h.authenticated({ credentials: { foo: 'bar' } })
},
}))
},
}
authDummy.register.attributes = {
name: 'hapi-auth-dummy',
}
return authDummy
}
function validateToken (apiToken) {
return (request, token) => {
if (token === apiToken) {
return {
isValid: true,
credentials: {
token: apiToken,
},
}
} else {
return { isValid: false, credentials: null }
}
}
}
function validateUser (opts = {}) {
const userParam = opts.userParam || 'user'
return async (request, username, password) => {
try {
if (
!request.params[userParam] ||
request.params[userParam] !== username
) {
return { isValid: false, credentials: null }
}
const user = await db.get(username)
if (await bcrypt.compare(password, user.password)) {
return {
isValid: true,
credentials: {
name: username,
},
}
} else {
return { isValid: false, credentials: null }
}
} catch (err) {
return { isValid: false, credentials: null }
}
}
}
module.exports = {
createAuthDummy,
validateToken,
validateUser,
}