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