This repository has been archived by the owner on Jul 13, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
routes.js
102 lines (94 loc) · 2.53 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
96
97
98
99
100
101
102
const express = require('express')
const _ = require('lodash')
const passport = require('passport')
const User = require('./models/user')
const api = express.Router()
const userFields = [
'username',
'objectId',
'createdAt',
'updatedAt',
'phone',
'emailVerified',
'mobilePhoneVerified'
]
function safeReturnUser (req, user = req.user, sessionToken = req.sessionID) {
if (_.isEmpty(user)) {
return user
}
let val = _.chain(user).pick(userFields)
if (sessionToken) {
val = val.set('sessionToken', sessionToken)
}
return val.value()
}
api.route('/login')
.get(passport.authenticate('local'), (req, res) => {
res.json(safeReturnUser(req))
})
api.route('/users')
.post((req, res, next) => {
const { username, password, phone, email } = req.body
User.register(new User({
username,
password,
phone,
email
}), password, (err, user) => {
if (err) {
res.status(400).send(err.message)
} else {
res.location(`${req.baseUrl}${req.path}/${user.objectId}`)
.status(201)
.json(safeReturnUser(req, user))
}
})
})
api.route('/users/me')
.get((req, res, next) => {
const sessionToken = req.get('X-LC-Session')
console.log('session token', sessionToken)
if (_.isEmpty(sessionToken)) {
return res.status(400).send('Session token must be set')
}
// this is an undocumented API thus a hack - in order to pull the store
const { sessionStore } = req
sessionStore.get(sessionToken, (err, session) => {
if (err) {
return res.status(400).send(err.message)
}
const username = _.get(session, 'passport.user')
if (_.isEmpty(username)) {
return res.status(401).send('Unauthorized.')
}
User.findByUsername(username, (err, user) => {
if (err) {
return next(err)
}
if (_.isEmpty(user)) {
return res.status(404).json({
code: 211,
error: 'Could not find user'
})
}
return res.json(safeReturnUser(null, user, sessionToken))
})
})
})
api.route('/users/:userId([0-9a-fA-F]{24}$)')
.get((req, res, next) => {
const { userId } = req.params
User.findById(userId, (err, user) => {
if (err) {
res.status(400).send(err.message)
} else if (user) {
res.json(safeReturnUser(req, user, null))
} else {
return res.status(404).json({
code: 211,
error: 'Could not find user'
})
}
})
})
module.exports = api