-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathindex.js
76 lines (70 loc) · 2.15 KB
/
index.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
const bcrypt = require('bcryptjs')
const handler = require('./jwt')
exports.isHashed = function (string) {
return string && string.length === 60 && string[0] === '$'
}
exports.createHash = function (password) {
const salt = bcrypt.genSaltSync(10)
return bcrypt.hashSync(password, salt)
}
exports.isValidPassword = function (password, hashedPassword) {
return bcrypt.compareSync(password, hashedPassword)
}
exports.doLogin = handler.doLogin
exports.middleware = async function authMiddleware(req, res, next) {
const key = req.query['access_key'] || req.headers['x-access-key']
if (key) {
if (typeof key == 'string' && req.db['access_keys']) {
const accessKeys = await req.db['access_keys'].find({ key: { $eq: key } }, 0, 1)
if (accessKeys && accessKeys.length > 0) {
const accessKey = accessKeys[0]
// check if access key is still valid
if (accessKey.expires_at >= new Date().toISOString()) {
let user
try {
user = await req.db[accessKey.user_collection].get(accessKey.user_id)
} catch (e) {
req.uerror = 'user no longer exists'
}
if (user && !req.uerror) {
req.uid = user._id
req.ucollection = 'users'
req.user = user
}
}
}
} else {
console.error('Non-string access key sent')
}
}
req.query = req.query || {}
const token = req.query['token'] || req.headers['x-access-token']
delete req.query['token']
delete req.headers['x-access-token']
let payload
try {
payload = await handler.isLoggedIn(token, req.getSetting('jwt_secret'))
}
catch(e) {
req.uerror = e.message
}
if (payload) {
let user
try {
user = await req.db[payload.collection].get(payload._id)
} catch (e) {
req.uerror = 'user no longer exists'
}
if (user) {
if (req.getSetting('jwt_expire_on_password_change') && user.meta.password_last_updated_at !== payload.timestamp) {
req.uerror = 'jwt expired'
}
if (!req.uerror) {
req.uid = payload._id
req.ucollection = payload.collection
req.user = user
}
}
}
next()
}