]>
Commit | Line | Data |
---|---|---|
1 | import * as express from 'express' | |
2 | import * as RateLimit from 'express-rate-limit' | |
3 | import { UserCreate, UserRight, UserRole, UserUpdate } from '../../../../shared' | |
4 | import { logger } from '../../../helpers/logger' | |
5 | import { getFormattedObjects } from '../../../helpers/utils' | |
6 | import { CONFIG, RATES_LIMIT, sequelizeTypescript } from '../../../initializers' | |
7 | import { Emailer } from '../../../lib/emailer' | |
8 | import { Redis } from '../../../lib/redis' | |
9 | import { createUserAccountAndChannel } from '../../../lib/user' | |
10 | import { | |
11 | asyncMiddleware, | |
12 | asyncRetryTransactionMiddleware, | |
13 | authenticate, | |
14 | ensureUserHasRight, | |
15 | ensureUserRegistrationAllowed, | |
16 | ensureUserRegistrationAllowedForIP, | |
17 | paginationValidator, | |
18 | setDefaultPagination, | |
19 | setDefaultSort, | |
20 | token, | |
21 | userAutocompleteValidator, | |
22 | usersAddValidator, | |
23 | usersGetValidator, | |
24 | usersRegisterValidator, | |
25 | usersRemoveValidator, | |
26 | usersSortValidator, | |
27 | usersUpdateValidator | |
28 | } from '../../../middlewares' | |
29 | import { | |
30 | usersAskResetPasswordValidator, | |
31 | usersAskSendVerifyEmailValidator, | |
32 | usersBlockingValidator, | |
33 | usersResetPasswordValidator, | |
34 | usersVerifyEmailValidator | |
35 | } from '../../../middlewares/validators' | |
36 | import { UserModel } from '../../../models/account/user' | |
37 | import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger' | |
38 | import { meRouter } from './me' | |
39 | import { deleteUserToken } from '../../../lib/oauth-model' | |
40 | import { myBlocklistRouter } from './my-blocklist' | |
41 | ||
42 | const auditLogger = auditLoggerFactory('users') | |
43 | ||
44 | const loginRateLimiter = new RateLimit({ | |
45 | windowMs: RATES_LIMIT.LOGIN.WINDOW_MS, | |
46 | max: RATES_LIMIT.LOGIN.MAX, | |
47 | delayMs: 0 | |
48 | }) | |
49 | ||
50 | const askSendEmailLimiter = new RateLimit({ | |
51 | windowMs: RATES_LIMIT.ASK_SEND_EMAIL.WINDOW_MS, | |
52 | max: RATES_LIMIT.ASK_SEND_EMAIL.MAX, | |
53 | delayMs: 0 | |
54 | }) | |
55 | ||
56 | const usersRouter = express.Router() | |
57 | usersRouter.use('/', myBlocklistRouter) | |
58 | usersRouter.use('/', meRouter) | |
59 | ||
60 | usersRouter.get('/autocomplete', | |
61 | userAutocompleteValidator, | |
62 | asyncMiddleware(autocompleteUsers) | |
63 | ) | |
64 | ||
65 | usersRouter.get('/', | |
66 | authenticate, | |
67 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
68 | paginationValidator, | |
69 | usersSortValidator, | |
70 | setDefaultSort, | |
71 | setDefaultPagination, | |
72 | asyncMiddleware(listUsers) | |
73 | ) | |
74 | ||
75 | usersRouter.post('/:id/block', | |
76 | authenticate, | |
77 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
78 | asyncMiddleware(usersBlockingValidator), | |
79 | asyncMiddleware(blockUser) | |
80 | ) | |
81 | usersRouter.post('/:id/unblock', | |
82 | authenticate, | |
83 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
84 | asyncMiddleware(usersBlockingValidator), | |
85 | asyncMiddleware(unblockUser) | |
86 | ) | |
87 | ||
88 | usersRouter.get('/:id', | |
89 | authenticate, | |
90 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
91 | asyncMiddleware(usersGetValidator), | |
92 | getUser | |
93 | ) | |
94 | ||
95 | usersRouter.post('/', | |
96 | authenticate, | |
97 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
98 | asyncMiddleware(usersAddValidator), | |
99 | asyncRetryTransactionMiddleware(createUser) | |
100 | ) | |
101 | ||
102 | usersRouter.post('/register', | |
103 | asyncMiddleware(ensureUserRegistrationAllowed), | |
104 | ensureUserRegistrationAllowedForIP, | |
105 | asyncMiddleware(usersRegisterValidator), | |
106 | asyncRetryTransactionMiddleware(registerUser) | |
107 | ) | |
108 | ||
109 | usersRouter.put('/:id', | |
110 | authenticate, | |
111 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
112 | asyncMiddleware(usersUpdateValidator), | |
113 | asyncMiddleware(updateUser) | |
114 | ) | |
115 | ||
116 | usersRouter.delete('/:id', | |
117 | authenticate, | |
118 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
119 | asyncMiddleware(usersRemoveValidator), | |
120 | asyncMiddleware(removeUser) | |
121 | ) | |
122 | ||
123 | usersRouter.post('/ask-reset-password', | |
124 | asyncMiddleware(usersAskResetPasswordValidator), | |
125 | asyncMiddleware(askResetUserPassword) | |
126 | ) | |
127 | ||
128 | usersRouter.post('/:id/reset-password', | |
129 | asyncMiddleware(usersResetPasswordValidator), | |
130 | asyncMiddleware(resetUserPassword) | |
131 | ) | |
132 | ||
133 | usersRouter.post('/ask-send-verify-email', | |
134 | askSendEmailLimiter, | |
135 | asyncMiddleware(usersAskSendVerifyEmailValidator), | |
136 | asyncMiddleware(askSendVerifyUserEmail) | |
137 | ) | |
138 | ||
139 | usersRouter.post('/:id/verify-email', | |
140 | asyncMiddleware(usersVerifyEmailValidator), | |
141 | asyncMiddleware(verifyUserEmail) | |
142 | ) | |
143 | ||
144 | usersRouter.post('/token', | |
145 | loginRateLimiter, | |
146 | token, | |
147 | success | |
148 | ) | |
149 | // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route | |
150 | ||
151 | // --------------------------------------------------------------------------- | |
152 | ||
153 | export { | |
154 | usersRouter | |
155 | } | |
156 | ||
157 | // --------------------------------------------------------------------------- | |
158 | ||
159 | async function createUser (req: express.Request, res: express.Response) { | |
160 | const body: UserCreate = req.body | |
161 | const userToCreate = new UserModel({ | |
162 | username: body.username, | |
163 | password: body.password, | |
164 | email: body.email, | |
165 | nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY, | |
166 | autoPlayVideo: true, | |
167 | role: body.role, | |
168 | videoQuota: body.videoQuota, | |
169 | videoQuotaDaily: body.videoQuotaDaily | |
170 | }) | |
171 | ||
172 | const { user, account } = await createUserAccountAndChannel(userToCreate) | |
173 | ||
174 | auditLogger.create(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON())) | |
175 | logger.info('User %s with its channel and account created.', body.username) | |
176 | ||
177 | return res.json({ | |
178 | user: { | |
179 | id: user.id, | |
180 | account: { | |
181 | id: account.id, | |
182 | uuid: account.Actor.uuid | |
183 | } | |
184 | } | |
185 | }).end() | |
186 | } | |
187 | ||
188 | async function registerUser (req: express.Request, res: express.Response) { | |
189 | const body: UserCreate = req.body | |
190 | ||
191 | const userToCreate = new UserModel({ | |
192 | username: body.username, | |
193 | password: body.password, | |
194 | email: body.email, | |
195 | nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY, | |
196 | autoPlayVideo: true, | |
197 | role: UserRole.USER, | |
198 | videoQuota: CONFIG.USER.VIDEO_QUOTA, | |
199 | videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY, | |
200 | emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null | |
201 | }) | |
202 | ||
203 | const { user } = await createUserAccountAndChannel(userToCreate) | |
204 | ||
205 | auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON())) | |
206 | logger.info('User %s with its channel and account registered.', body.username) | |
207 | ||
208 | if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) { | |
209 | await sendVerifyUserEmail(user) | |
210 | } | |
211 | ||
212 | return res.type('json').status(204).end() | |
213 | } | |
214 | ||
215 | async function unblockUser (req: express.Request, res: express.Response, next: express.NextFunction) { | |
216 | const user: UserModel = res.locals.user | |
217 | ||
218 | await changeUserBlock(res, user, false) | |
219 | ||
220 | return res.status(204).end() | |
221 | } | |
222 | ||
223 | async function blockUser (req: express.Request, res: express.Response, next: express.NextFunction) { | |
224 | const user: UserModel = res.locals.user | |
225 | const reason = req.body.reason | |
226 | ||
227 | await changeUserBlock(res, user, true, reason) | |
228 | ||
229 | return res.status(204).end() | |
230 | } | |
231 | ||
232 | function getUser (req: express.Request, res: express.Response, next: express.NextFunction) { | |
233 | return res.json((res.locals.user as UserModel).toFormattedJSON()) | |
234 | } | |
235 | ||
236 | async function autocompleteUsers (req: express.Request, res: express.Response, next: express.NextFunction) { | |
237 | const resultList = await UserModel.autoComplete(req.query.search as string) | |
238 | ||
239 | return res.json(resultList) | |
240 | } | |
241 | ||
242 | async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) { | |
243 | const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort, req.query.search) | |
244 | ||
245 | return res.json(getFormattedObjects(resultList.data, resultList.total)) | |
246 | } | |
247 | ||
248 | async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) { | |
249 | const user: UserModel = res.locals.user | |
250 | ||
251 | await user.destroy() | |
252 | ||
253 | auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON())) | |
254 | ||
255 | return res.sendStatus(204) | |
256 | } | |
257 | ||
258 | async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) { | |
259 | const body: UserUpdate = req.body | |
260 | const userToUpdate = res.locals.user as UserModel | |
261 | const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON()) | |
262 | const roleChanged = body.role !== undefined && body.role !== userToUpdate.role | |
263 | ||
264 | if (body.email !== undefined) userToUpdate.email = body.email | |
265 | if (body.videoQuota !== undefined) userToUpdate.videoQuota = body.videoQuota | |
266 | if (body.videoQuotaDaily !== undefined) userToUpdate.videoQuotaDaily = body.videoQuotaDaily | |
267 | if (body.role !== undefined) userToUpdate.role = body.role | |
268 | ||
269 | const user = await userToUpdate.save() | |
270 | ||
271 | // Destroy user token to refresh rights | |
272 | if (roleChanged) await deleteUserToken(userToUpdate.id) | |
273 | ||
274 | auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView) | |
275 | ||
276 | // Don't need to send this update to followers, these attributes are not propagated | |
277 | ||
278 | return res.sendStatus(204) | |
279 | } | |
280 | ||
281 | async function askResetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) { | |
282 | const user = res.locals.user as UserModel | |
283 | ||
284 | const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id) | |
285 | const url = CONFIG.WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString | |
286 | await Emailer.Instance.addForgetPasswordEmailJob(user.email, url) | |
287 | ||
288 | return res.status(204).end() | |
289 | } | |
290 | ||
291 | async function resetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) { | |
292 | const user = res.locals.user as UserModel | |
293 | user.password = req.body.password | |
294 | ||
295 | await user.save() | |
296 | ||
297 | return res.status(204).end() | |
298 | } | |
299 | ||
300 | async function sendVerifyUserEmail (user: UserModel) { | |
301 | const verificationString = await Redis.Instance.setVerifyEmailVerificationString(user.id) | |
302 | const url = CONFIG.WEBSERVER.URL + '/verify-account/email?userId=' + user.id + '&verificationString=' + verificationString | |
303 | await Emailer.Instance.addVerifyEmailJob(user.email, url) | |
304 | return | |
305 | } | |
306 | ||
307 | async function askSendVerifyUserEmail (req: express.Request, res: express.Response, next: express.NextFunction) { | |
308 | const user = res.locals.user as UserModel | |
309 | ||
310 | await sendVerifyUserEmail(user) | |
311 | ||
312 | return res.status(204).end() | |
313 | } | |
314 | ||
315 | async function verifyUserEmail (req: express.Request, res: express.Response, next: express.NextFunction) { | |
316 | const user = res.locals.user as UserModel | |
317 | user.emailVerified = true | |
318 | ||
319 | await user.save() | |
320 | ||
321 | return res.status(204).end() | |
322 | } | |
323 | ||
324 | function success (req: express.Request, res: express.Response, next: express.NextFunction) { | |
325 | res.end() | |
326 | } | |
327 | ||
328 | async function changeUserBlock (res: express.Response, user: UserModel, block: boolean, reason?: string) { | |
329 | const oldUserAuditView = new UserAuditView(user.toFormattedJSON()) | |
330 | ||
331 | user.blocked = block | |
332 | user.blockedReason = reason || null | |
333 | ||
334 | await sequelizeTypescript.transaction(async t => { | |
335 | await deleteUserToken(user.id, t) | |
336 | ||
337 | await user.save({ transaction: t }) | |
338 | }) | |
339 | ||
340 | await Emailer.Instance.addUserBlockJob(user, block, reason) | |
341 | ||
342 | auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView) | |
343 | } |