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