-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathusers.js
52 lines (46 loc) · 1.52 KB
/
users.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
const auth = require('../auth')
const util = require('../util')
const collectionsApi = require('./collections')
const permissions = require('../middleware/permissions')
exports.login = async (req, collection) => {
const password = req.body.password
if (typeof req.body.email !== 'string') {
throw new util.ApiError(400, 'email must be a string')
}
req.body.email = req.body.email.toLowerCase()
// check if user exists
const result = await req.db[collection].find({
email: req.body.email
})
if (result.length === 0) {
throw new util.ApiError(400, 'No ' + collection + ' found with this email.')
}
const user = result[0]
if (!auth.isValidPassword(password, user.password)) {
throw new util.ApiError(401, 'Incorrect password')
}
const jwt_options = req.settings.jwt_expires_in ? { expiresIn: req.settings.jwt_expires_in } : {}
const payload = auth.doLogin({
id: user._id,
collection,
timestamp: user.meta.password_last_updated_at,
jwt_secret: req.getSetting('jwt_secret'),
jwt_options
})
req.uid = user._id
req.ucollection = collection
req.user = user
await permissions.addRolePermissionsAsync(req)
payload.canUseAdmin = req.hasPermission('login to admin')
return payload
}
exports.register = function (req, collection) {
req.url = `/${collection}`
req.params.collection = collection
return collectionsApi.insert(req)
}
exports.getMe = function (req, collection) {
req.params.collection = collection
req.params.id = req.uid
return collectionsApi.getById(req)
}