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