/
users.js
188 lines (161 loc) · 5.83 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
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import bcrypt from 'bcrypt'
import cuid from 'cuid'
import httpErrors from 'http-errors'
import thenify from 'thenify'
import createThrottle from '../throttle/create-throttle'
import throttleMiddleware from '../throttle/middleware'
import users from '../models/users'
import initSession from '../session/init'
import sendAccountVerificationEmail from '../verifications/send-account-verification-email'
import setReturningCookie from '../session/set-returning-cookie'
import { checkAnyPermission } from '../permissions/check-permissions'
import { usePasswordResetCode } from '../models/password-resets'
import {
addEmailVerificationCode,
getEmailVerificationsCount,
useEmailVerificationCode,
} from '../models/email-verifications'
import { isValidUsername, isValidEmail, isValidPassword } from '../../../app/common/constants'
import { UNIQUE_VIOLATION } from '../db/pg-error-codes'
import transact from '../db/transaction'
import updateAllSessions from '../session/update-all-sessions'
import ensureLoggedIn from '../session/ensure-logged-in'
const accountCreationThrottle = createThrottle('accountcreation', {
rate: 1,
burst: 4,
window: 60000,
})
const emailVerificationThrottle = createThrottle('emailverification', {
rate: 10,
burst: 20,
window: 12 * 60 * 60 * 1000,
})
const sendVerificationThrottle = createThrottle('sendverification', {
rate: 4,
burst: 4,
window: 12 * 60 * 60 * 1000,
})
export default function(router, { nydus }) {
router
.post('/', throttleMiddleware(accountCreationThrottle, ctx => ctx.ip), createUser)
.get('/:searchTerm', checkAnyPermission('banUsers', 'editPermissions'), find)
.put('/:id', function*(next) {
// TODO(tec27): update a user
throw new httpErrors.ImATeapot()
})
.post('/:username/password', resetPassword)
.post(
'/:id/emailVerification',
throttleMiddleware(emailVerificationThrottle, ctx => {
const { id } = ctx.params
const { email } = ctx.request.body
return `${id}|${email}`
}),
ensureLoggedIn,
(ctx, next) => verifyEmail(ctx, next, nydus),
)
.post(
'/:id/sendVerification',
throttleMiddleware(sendVerificationThrottle, ctx => {
const { id } = ctx.params
const { email } = ctx.request.body
return `${id}|${email}`
}),
ensureLoggedIn,
sendVerificationEmail,
)
}
async function find(ctx, next) {
const searchTerm = ctx.params.searchTerm
try {
const user = await users.find(searchTerm)
ctx.body = user ? [user] : []
} catch (err) {
throw err
}
}
const bcryptHash = thenify(bcrypt.hash)
function hashPass(password) {
return bcryptHash(password, 10)
}
async function createUser(ctx, next) {
const { username, password } = ctx.request.body
const email = ctx.request.body.email.trim()
if (!isValidUsername(username) || !isValidEmail(email) || !isValidPassword(password)) {
throw new httpErrors.BadRequest('Invalid parameters')
}
const hashed = await hashPass(password)
let result
try {
const user = users.create(username, email, hashed, ctx.ip)
result = await user.save()
} catch (err) {
if (err.code && err.code === UNIQUE_VIOLATION) {
throw new httpErrors.Conflict('A user with that name already exists')
}
throw err
}
// regenerate the session to ensure that logged in sessions and anonymous sessions don't
// share a session ID
await ctx.regenerateSession()
initSession(ctx, result.user, result.permissions)
setReturningCookie(ctx)
const code = cuid()
await addEmailVerificationCode(result.user.id, email, code, ctx.ip)
await sendAccountVerificationEmail(code, result.user.id, email)
ctx.body = result
}
async function resetPassword(ctx, next) {
const { username } = ctx.params
const { code } = ctx.query
const { password } = ctx.request.body
if (!code || !isValidUsername(username) || !isValidPassword(password)) {
throw new httpErrors.BadRequest('Invalid parameters')
}
await transact(async client => {
try {
await usePasswordResetCode(client, username, code)
} catch (err) {
throw new httpErrors.BadRequest('Password reset code is invalid')
}
const user = await users.find(username)
user.password = await hashPass(password)
await user.save()
ctx.status = 204
})
}
async function verifyEmail(ctx, next, nydus) {
const { id } = ctx.params
const { code } = ctx.query
const { email } = ctx.request.body
if (!id || !code || !isValidEmail(email)) {
throw new httpErrors.BadRequest('Invalid parameters')
}
const emailVerified = await useEmailVerificationCode(id, email, code)
if (!emailVerified) {
throw new httpErrors.BadRequest('Email verification code is invalid')
}
// Update all of the user's sessions to indicate that their email is now indeed verified.
updateAllSessions(ctx, { emailVerified: true })
// Last thing to do is to notify all of the user's opened sockets that their email is now verified
// NOTE(2Pac): With the way the things are currently set up on client (their socket is not
// connected when they open the email verification page), the client making the request won't
// actually get this event. Thankfully, that's easy to deal with on the client-side.
nydus.publish('/userProfiles/' + ctx.session.userId, { action: 'emailVerified' })
ctx.status = 204
}
async function sendVerificationEmail(ctx, next) {
const { id } = ctx.params
const { email } = ctx.request.body
if (!id || !isValidEmail(email)) {
throw new httpErrors.BadRequest('Invalid parameters')
}
const emailVerificationsCount = await getEmailVerificationsCount(id, email)
if (emailVerificationsCount > 10) {
throw new httpErrors.Conflict('Email is over verification limit')
}
const code = cuid()
await addEmailVerificationCode(id, email, code, ctx.ip)
await sendAccountVerificationEmail(code, id, email)
ctx.status = 204
}