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