]>
Commit | Line | Data |
---|---|---|
1 | import express from 'express' | |
2 | import { tokensRouter } from '@server/controllers/api/users/token' | |
3 | import { Hooks } from '@server/lib/plugins/hooks' | |
4 | import { OAuthTokenModel } from '@server/models/oauth/oauth-token' | |
5 | import { MUserAccountDefault } from '@server/types/models' | |
6 | import { pick } from '@shared/core-utils' | |
7 | import { HttpStatusCode, UserCreate, UserCreateResult, UserRegister, UserRight, UserUpdate } from '@shared/models' | |
8 | import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger' | |
9 | import { logger } from '../../../helpers/logger' | |
10 | import { generateRandomString, getFormattedObjects } from '../../../helpers/utils' | |
11 | import { CONFIG } from '../../../initializers/config' | |
12 | import { WEBSERVER } from '../../../initializers/constants' | |
13 | import { sequelizeTypescript } from '../../../initializers/database' | |
14 | import { Emailer } from '../../../lib/emailer' | |
15 | import { Notifier } from '../../../lib/notifier' | |
16 | import { Redis } from '../../../lib/redis' | |
17 | import { buildUser, createUserAccountAndChannelAndPlaylist, sendVerifyUserEmail } from '../../../lib/user' | |
18 | import { | |
19 | adminUsersSortValidator, | |
20 | asyncMiddleware, | |
21 | asyncRetryTransactionMiddleware, | |
22 | authenticate, | |
23 | buildRateLimiter, | |
24 | ensureUserHasRight, | |
25 | ensureUserRegistrationAllowed, | |
26 | ensureUserRegistrationAllowedForIP, | |
27 | paginationValidator, | |
28 | setDefaultPagination, | |
29 | setDefaultSort, | |
30 | userAutocompleteValidator, | |
31 | usersAddValidator, | |
32 | usersGetValidator, | |
33 | usersListValidator, | |
34 | usersRegisterValidator, | |
35 | usersRemoveValidator, | |
36 | usersUpdateValidator | |
37 | } from '../../../middlewares' | |
38 | import { | |
39 | ensureCanModerateUser, | |
40 | usersAskResetPasswordValidator, | |
41 | usersAskSendVerifyEmailValidator, | |
42 | usersBlockingValidator, | |
43 | usersResetPasswordValidator, | |
44 | usersVerifyEmailValidator | |
45 | } from '../../../middlewares/validators' | |
46 | import { UserModel } from '../../../models/user/user' | |
47 | import { meRouter } from './me' | |
48 | import { myAbusesRouter } from './my-abuses' | |
49 | import { myBlocklistRouter } from './my-blocklist' | |
50 | import { myVideosHistoryRouter } from './my-history' | |
51 | import { myNotificationsRouter } from './my-notifications' | |
52 | import { mySubscriptionsRouter } from './my-subscriptions' | |
53 | import { myVideoPlaylistsRouter } from './my-video-playlists' | |
54 | import { twoFactorRouter } from './two-factor' | |
55 | ||
56 | const auditLogger = auditLoggerFactory('users') | |
57 | ||
58 | const signupRateLimiter = buildRateLimiter({ | |
59 | windowMs: CONFIG.RATES_LIMIT.SIGNUP.WINDOW_MS, | |
60 | max: CONFIG.RATES_LIMIT.SIGNUP.MAX, | |
61 | skipFailedRequests: true | |
62 | }) | |
63 | ||
64 | const askSendEmailLimiter = buildRateLimiter({ | |
65 | windowMs: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.WINDOW_MS, | |
66 | max: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.MAX | |
67 | }) | |
68 | ||
69 | const usersRouter = express.Router() | |
70 | usersRouter.use('/', twoFactorRouter) | |
71 | usersRouter.use('/', tokensRouter) | |
72 | usersRouter.use('/', myNotificationsRouter) | |
73 | usersRouter.use('/', mySubscriptionsRouter) | |
74 | usersRouter.use('/', myBlocklistRouter) | |
75 | usersRouter.use('/', myVideosHistoryRouter) | |
76 | usersRouter.use('/', myVideoPlaylistsRouter) | |
77 | usersRouter.use('/', myAbusesRouter) | |
78 | usersRouter.use('/', meRouter) | |
79 | ||
80 | usersRouter.get('/autocomplete', | |
81 | userAutocompleteValidator, | |
82 | asyncMiddleware(autocompleteUsers) | |
83 | ) | |
84 | ||
85 | usersRouter.get('/', | |
86 | authenticate, | |
87 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
88 | paginationValidator, | |
89 | adminUsersSortValidator, | |
90 | setDefaultSort, | |
91 | setDefaultPagination, | |
92 | usersListValidator, | |
93 | asyncMiddleware(listUsers) | |
94 | ) | |
95 | ||
96 | usersRouter.post('/:id/block', | |
97 | authenticate, | |
98 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
99 | asyncMiddleware(usersBlockingValidator), | |
100 | ensureCanModerateUser, | |
101 | asyncMiddleware(blockUser) | |
102 | ) | |
103 | usersRouter.post('/:id/unblock', | |
104 | authenticate, | |
105 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
106 | asyncMiddleware(usersBlockingValidator), | |
107 | ensureCanModerateUser, | |
108 | asyncMiddleware(unblockUser) | |
109 | ) | |
110 | ||
111 | usersRouter.get('/:id', | |
112 | authenticate, | |
113 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
114 | asyncMiddleware(usersGetValidator), | |
115 | getUser | |
116 | ) | |
117 | ||
118 | usersRouter.post('/', | |
119 | authenticate, | |
120 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
121 | asyncMiddleware(usersAddValidator), | |
122 | asyncRetryTransactionMiddleware(createUser) | |
123 | ) | |
124 | ||
125 | usersRouter.post('/register', | |
126 | signupRateLimiter, | |
127 | asyncMiddleware(ensureUserRegistrationAllowed), | |
128 | ensureUserRegistrationAllowedForIP, | |
129 | asyncMiddleware(usersRegisterValidator), | |
130 | asyncRetryTransactionMiddleware(registerUser) | |
131 | ) | |
132 | ||
133 | usersRouter.put('/:id', | |
134 | authenticate, | |
135 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
136 | asyncMiddleware(usersUpdateValidator), | |
137 | ensureCanModerateUser, | |
138 | asyncMiddleware(updateUser) | |
139 | ) | |
140 | ||
141 | usersRouter.delete('/:id', | |
142 | authenticate, | |
143 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
144 | asyncMiddleware(usersRemoveValidator), | |
145 | ensureCanModerateUser, | |
146 | asyncMiddleware(removeUser) | |
147 | ) | |
148 | ||
149 | usersRouter.post('/ask-reset-password', | |
150 | asyncMiddleware(usersAskResetPasswordValidator), | |
151 | asyncMiddleware(askResetUserPassword) | |
152 | ) | |
153 | ||
154 | usersRouter.post('/:id/reset-password', | |
155 | asyncMiddleware(usersResetPasswordValidator), | |
156 | asyncMiddleware(resetUserPassword) | |
157 | ) | |
158 | ||
159 | usersRouter.post('/ask-send-verify-email', | |
160 | askSendEmailLimiter, | |
161 | asyncMiddleware(usersAskSendVerifyEmailValidator), | |
162 | asyncMiddleware(reSendVerifyUserEmail) | |
163 | ) | |
164 | ||
165 | usersRouter.post('/:id/verify-email', | |
166 | asyncMiddleware(usersVerifyEmailValidator), | |
167 | asyncMiddleware(verifyUserEmail) | |
168 | ) | |
169 | ||
170 | // --------------------------------------------------------------------------- | |
171 | ||
172 | export { | |
173 | usersRouter | |
174 | } | |
175 | ||
176 | // --------------------------------------------------------------------------- | |
177 | ||
178 | async function createUser (req: express.Request, res: express.Response) { | |
179 | const body: UserCreate = req.body | |
180 | ||
181 | const userToCreate = buildUser({ | |
182 | ...pick(body, [ 'username', 'password', 'email', 'role', 'videoQuota', 'videoQuotaDaily', 'adminFlags' ]), | |
183 | ||
184 | emailVerified: null | |
185 | }) | |
186 | ||
187 | // NB: due to the validator usersAddValidator, password==='' can only be true if we can send the mail. | |
188 | const createPassword = userToCreate.password === '' | |
189 | if (createPassword) { | |
190 | userToCreate.password = await generateRandomString(20) | |
191 | } | |
192 | ||
193 | const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({ | |
194 | userToCreate, | |
195 | channelNames: body.channelName && { name: body.channelName, displayName: body.channelName } | |
196 | }) | |
197 | ||
198 | auditLogger.create(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON())) | |
199 | logger.info('User %s with its channel and account created.', body.username) | |
200 | ||
201 | if (createPassword) { | |
202 | // this will send an email for newly created users, so then can set their first password. | |
203 | logger.info('Sending to user %s a create password email', body.username) | |
204 | const verificationString = await Redis.Instance.setCreatePasswordVerificationString(user.id) | |
205 | const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString | |
206 | Emailer.Instance.addPasswordCreateEmailJob(userToCreate.username, user.email, url) | |
207 | } | |
208 | ||
209 | Hooks.runAction('action:api.user.created', { body, user, account, videoChannel, req, res }) | |
210 | ||
211 | return res.json({ | |
212 | user: { | |
213 | id: user.id, | |
214 | account: { | |
215 | id: account.id | |
216 | } | |
217 | } as UserCreateResult | |
218 | }) | |
219 | } | |
220 | ||
221 | async function registerUser (req: express.Request, res: express.Response) { | |
222 | const body: UserRegister = req.body | |
223 | ||
224 | const userToCreate = buildUser({ | |
225 | ...pick(body, [ 'username', 'password', 'email' ]), | |
226 | ||
227 | emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null | |
228 | }) | |
229 | ||
230 | const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({ | |
231 | userToCreate, | |
232 | userDisplayName: body.displayName || undefined, | |
233 | channelNames: body.channel | |
234 | }) | |
235 | ||
236 | auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON())) | |
237 | logger.info('User %s with its channel and account registered.', body.username) | |
238 | ||
239 | if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) { | |
240 | await sendVerifyUserEmail(user) | |
241 | } | |
242 | ||
243 | Notifier.Instance.notifyOnNewUserRegistration(user) | |
244 | ||
245 | Hooks.runAction('action:api.user.registered', { body, user, account, videoChannel, req, res }) | |
246 | ||
247 | return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end() | |
248 | } | |
249 | ||
250 | async function unblockUser (req: express.Request, res: express.Response) { | |
251 | const user = res.locals.user | |
252 | ||
253 | await changeUserBlock(res, user, false) | |
254 | ||
255 | Hooks.runAction('action:api.user.unblocked', { user, req, res }) | |
256 | ||
257 | return res.status(HttpStatusCode.NO_CONTENT_204).end() | |
258 | } | |
259 | ||
260 | async function blockUser (req: express.Request, res: express.Response) { | |
261 | const user = res.locals.user | |
262 | const reason = req.body.reason | |
263 | ||
264 | await changeUserBlock(res, user, true, reason) | |
265 | ||
266 | Hooks.runAction('action:api.user.blocked', { user, req, res }) | |
267 | ||
268 | return res.status(HttpStatusCode.NO_CONTENT_204).end() | |
269 | } | |
270 | ||
271 | function getUser (req: express.Request, res: express.Response) { | |
272 | return res.json(res.locals.user.toFormattedJSON({ withAdminFlags: true })) | |
273 | } | |
274 | ||
275 | async function autocompleteUsers (req: express.Request, res: express.Response) { | |
276 | const resultList = await UserModel.autoComplete(req.query.search as string) | |
277 | ||
278 | return res.json(resultList) | |
279 | } | |
280 | ||
281 | async function listUsers (req: express.Request, res: express.Response) { | |
282 | const resultList = await UserModel.listForAdminApi({ | |
283 | start: req.query.start, | |
284 | count: req.query.count, | |
285 | sort: req.query.sort, | |
286 | search: req.query.search, | |
287 | blocked: req.query.blocked | |
288 | }) | |
289 | ||
290 | return res.json(getFormattedObjects(resultList.data, resultList.total, { withAdminFlags: true })) | |
291 | } | |
292 | ||
293 | async function removeUser (req: express.Request, res: express.Response) { | |
294 | const user = res.locals.user | |
295 | ||
296 | auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON())) | |
297 | ||
298 | await sequelizeTypescript.transaction(async t => { | |
299 | // Use a transaction to avoid inconsistencies with hooks (account/channel deletion & federation) | |
300 | await user.destroy({ transaction: t }) | |
301 | }) | |
302 | ||
303 | Hooks.runAction('action:api.user.deleted', { user, req, res }) | |
304 | ||
305 | return res.status(HttpStatusCode.NO_CONTENT_204).end() | |
306 | } | |
307 | ||
308 | async function updateUser (req: express.Request, res: express.Response) { | |
309 | const body: UserUpdate = req.body | |
310 | const userToUpdate = res.locals.user | |
311 | const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON()) | |
312 | const roleChanged = body.role !== undefined && body.role !== userToUpdate.role | |
313 | ||
314 | const keysToUpdate: (keyof UserUpdate)[] = [ | |
315 | 'password', | |
316 | 'email', | |
317 | 'emailVerified', | |
318 | 'videoQuota', | |
319 | 'videoQuotaDaily', | |
320 | 'role', | |
321 | 'adminFlags', | |
322 | 'pluginAuth' | |
323 | ] | |
324 | ||
325 | for (const key of keysToUpdate) { | |
326 | if (body[key] !== undefined) userToUpdate.set(key, body[key]) | |
327 | } | |
328 | ||
329 | const user = await userToUpdate.save() | |
330 | ||
331 | // Destroy user token to refresh rights | |
332 | if (roleChanged || body.password !== undefined) await OAuthTokenModel.deleteUserToken(userToUpdate.id) | |
333 | ||
334 | auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView) | |
335 | ||
336 | Hooks.runAction('action:api.user.updated', { user, req, res }) | |
337 | ||
338 | // Don't need to send this update to followers, these attributes are not federated | |
339 | ||
340 | return res.status(HttpStatusCode.NO_CONTENT_204).end() | |
341 | } | |
342 | ||
343 | async function askResetUserPassword (req: express.Request, res: express.Response) { | |
344 | const user = res.locals.user | |
345 | ||
346 | const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id) | |
347 | const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString | |
348 | Emailer.Instance.addPasswordResetEmailJob(user.username, user.email, url) | |
349 | ||
350 | return res.status(HttpStatusCode.NO_CONTENT_204).end() | |
351 | } | |
352 | ||
353 | async function resetUserPassword (req: express.Request, res: express.Response) { | |
354 | const user = res.locals.user | |
355 | user.password = req.body.password | |
356 | ||
357 | await user.save() | |
358 | await Redis.Instance.removePasswordVerificationString(user.id) | |
359 | ||
360 | return res.status(HttpStatusCode.NO_CONTENT_204).end() | |
361 | } | |
362 | ||
363 | async function reSendVerifyUserEmail (req: express.Request, res: express.Response) { | |
364 | const user = res.locals.user | |
365 | ||
366 | await sendVerifyUserEmail(user) | |
367 | ||
368 | return res.status(HttpStatusCode.NO_CONTENT_204).end() | |
369 | } | |
370 | ||
371 | async function verifyUserEmail (req: express.Request, res: express.Response) { | |
372 | const user = res.locals.user | |
373 | user.emailVerified = true | |
374 | ||
375 | if (req.body.isPendingEmail === true) { | |
376 | user.email = user.pendingEmail | |
377 | user.pendingEmail = null | |
378 | } | |
379 | ||
380 | await user.save() | |
381 | ||
382 | return res.status(HttpStatusCode.NO_CONTENT_204).end() | |
383 | } | |
384 | ||
385 | async function changeUserBlock (res: express.Response, user: MUserAccountDefault, block: boolean, reason?: string) { | |
386 | const oldUserAuditView = new UserAuditView(user.toFormattedJSON()) | |
387 | ||
388 | user.blocked = block | |
389 | user.blockedReason = reason || null | |
390 | ||
391 | await sequelizeTypescript.transaction(async t => { | |
392 | await OAuthTokenModel.deleteUserToken(user.id, t) | |
393 | ||
394 | await user.save({ transaction: t }) | |
395 | }) | |
396 | ||
397 | await Emailer.Instance.addUserBlockJob(user, block, reason) | |
398 | ||
399 | auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView) | |
400 | } |