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