]>
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 |
f05a1c30 | 179 | const userToCreate = new UserModel({ |
4771e000 C |
180 | username: body.username, |
181 | password: body.password, | |
182 | email: body.email, | |
0883b324 | 183 | nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY, |
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 | ||
6f3fe96f | 197 | const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({ userToCreate: userToCreate }) |
eb080476 | 198 | |
993cef4b | 199 | auditLogger.create(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON())) |
38fa2065 | 200 | logger.info('User %s with its channel and account created.', body.username) |
f05a1c30 | 201 | |
45f1bd72 JL |
202 | if (createPassword) { |
203 | // this will send an email for newly created users, so then can set their first password. | |
204 | logger.info('Sending to user %s a create password email', body.username) | |
205 | const verificationString = await Redis.Instance.setCreatePasswordVerificationString(user.id) | |
206 | const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString | |
207 | await Emailer.Instance.addPasswordCreateEmailJob(userToCreate.username, user.email, url) | |
208 | } | |
209 | ||
6f3fe96f C |
210 | Hooks.runAction('action:api.user.created', { body, user, account, videoChannel }) |
211 | ||
1e904cde | 212 | return res.json({ |
90d4bb81 C |
213 | user: { |
214 | id: user.id, | |
215 | account: { | |
57cfff78 | 216 | id: account.id |
90d4bb81 C |
217 | } |
218 | } | |
219 | }).end() | |
47e0652b C |
220 | } |
221 | ||
90d4bb81 | 222 | async function registerUser (req: express.Request, res: express.Response) { |
e590b4a5 | 223 | const body: UserRegister = req.body |
77a5501f | 224 | |
80e36cd9 | 225 | const userToCreate = new UserModel({ |
77a5501f C |
226 | username: body.username, |
227 | password: body.password, | |
228 | email: body.email, | |
0883b324 | 229 | nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY, |
7efe153b | 230 | autoPlayVideo: true, |
954605a8 | 231 | role: UserRole.USER, |
bee0abff | 232 | videoQuota: CONFIG.USER.VIDEO_QUOTA, |
d9eaee39 JM |
233 | videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY, |
234 | emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null | |
77a5501f C |
235 | }) |
236 | ||
6f3fe96f | 237 | const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({ |
1f20622f C |
238 | userToCreate: userToCreate, |
239 | userDisplayName: body.displayName || undefined, | |
240 | channelNames: body.channel | |
241 | }) | |
47e0652b | 242 | |
80e36cd9 | 243 | auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON())) |
47e0652b | 244 | logger.info('User %s with its channel and account registered.', body.username) |
90d4bb81 | 245 | |
d9eaee39 JM |
246 | if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) { |
247 | await sendVerifyUserEmail(user) | |
248 | } | |
249 | ||
f7cc67b4 C |
250 | Notifier.Instance.notifyOnNewUserRegistration(user) |
251 | ||
6f3fe96f C |
252 | Hooks.runAction('action:api.user.registered', { body, user, account, videoChannel }) |
253 | ||
90d4bb81 | 254 | return res.type('json').status(204).end() |
77a5501f C |
255 | } |
256 | ||
dae86118 C |
257 | async function unblockUser (req: express.Request, res: express.Response) { |
258 | const user = res.locals.user | |
e6921918 C |
259 | |
260 | await changeUserBlock(res, user, false) | |
261 | ||
6f3fe96f C |
262 | Hooks.runAction('action:api.user.unblocked', { user }) |
263 | ||
e6921918 C |
264 | return res.status(204).end() |
265 | } | |
266 | ||
b426edd4 | 267 | async function blockUser (req: express.Request, res: express.Response) { |
dae86118 | 268 | const user = res.locals.user |
eacb25c4 | 269 | const reason = req.body.reason |
e6921918 | 270 | |
eacb25c4 | 271 | await changeUserBlock(res, user, true, reason) |
e6921918 | 272 | |
6f3fe96f C |
273 | Hooks.runAction('action:api.user.blocked', { user }) |
274 | ||
e6921918 C |
275 | return res.status(204).end() |
276 | } | |
277 | ||
b426edd4 | 278 | function getUser (req: express.Request, res: express.Response) { |
1eddc9a7 | 279 | return res.json(res.locals.user.toFormattedJSON({ withAdminFlags: true })) |
8094a898 C |
280 | } |
281 | ||
b426edd4 | 282 | async function autocompleteUsers (req: express.Request, res: express.Response) { |
5cf84858 | 283 | const resultList = await UserModel.autoComplete(req.query.search as string) |
74d63469 GR |
284 | |
285 | return res.json(resultList) | |
286 | } | |
287 | ||
b426edd4 | 288 | async function listUsers (req: express.Request, res: express.Response) { |
8491293b RK |
289 | const resultList = await UserModel.listForApi({ |
290 | start: req.query.start, | |
291 | count: req.query.count, | |
292 | sort: req.query.sort, | |
293 | search: req.query.search, | |
294 | blocked: req.query.blocked | |
295 | }) | |
eb080476 | 296 | |
1eddc9a7 | 297 | return res.json(getFormattedObjects(resultList.data, resultList.total, { withAdminFlags: true })) |
9bd26629 C |
298 | } |
299 | ||
b426edd4 | 300 | async function removeUser (req: express.Request, res: express.Response) { |
dae86118 | 301 | const user = res.locals.user |
eb080476 C |
302 | |
303 | await user.destroy() | |
304 | ||
993cef4b | 305 | auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON())) |
80e36cd9 | 306 | |
6f3fe96f C |
307 | Hooks.runAction('action:api.user.deleted', { user }) |
308 | ||
eb080476 | 309 | return res.sendStatus(204) |
9bd26629 C |
310 | } |
311 | ||
b426edd4 | 312 | async function updateUser (req: express.Request, res: express.Response) { |
8094a898 | 313 | const body: UserUpdate = req.body |
dae86118 | 314 | const userToUpdate = res.locals.user |
80e36cd9 AB |
315 | const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON()) |
316 | const roleChanged = body.role !== undefined && body.role !== userToUpdate.role | |
8094a898 | 317 | |
b426edd4 | 318 | if (body.password !== undefined) userToUpdate.password = body.password |
80e36cd9 | 319 | if (body.email !== undefined) userToUpdate.email = body.email |
fc2ec87a | 320 | if (body.emailVerified !== undefined) userToUpdate.emailVerified = body.emailVerified |
80e36cd9 | 321 | if (body.videoQuota !== undefined) userToUpdate.videoQuota = body.videoQuota |
bee0abff | 322 | if (body.videoQuotaDaily !== undefined) userToUpdate.videoQuotaDaily = body.videoQuotaDaily |
80e36cd9 | 323 | if (body.role !== undefined) userToUpdate.role = body.role |
1eddc9a7 | 324 | if (body.adminFlags !== undefined) userToUpdate.adminFlags = body.adminFlags |
8094a898 | 325 | |
80e36cd9 | 326 | const user = await userToUpdate.save() |
eb080476 | 327 | |
f8b8c36b | 328 | // Destroy user token to refresh rights |
b426edd4 | 329 | if (roleChanged || body.password !== undefined) await deleteUserToken(userToUpdate.id) |
f8b8c36b | 330 | |
91411dba | 331 | auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView) |
80e36cd9 | 332 | |
6f3fe96f C |
333 | Hooks.runAction('action:api.user.updated', { user }) |
334 | ||
b426edd4 | 335 | // Don't need to send this update to followers, these attributes are not federated |
265ba139 | 336 | |
eb080476 | 337 | return res.sendStatus(204) |
8094a898 C |
338 | } |
339 | ||
dae86118 C |
340 | async function askResetUserPassword (req: express.Request, res: express.Response) { |
341 | const user = res.locals.user | |
ecb4e35f C |
342 | |
343 | const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id) | |
6dd9de95 | 344 | const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString |
963023ab | 345 | await Emailer.Instance.addPasswordResetEmailJob(user.username, user.email, url) |
ecb4e35f C |
346 | |
347 | return res.status(204).end() | |
348 | } | |
349 | ||
dae86118 C |
350 | async function resetUserPassword (req: express.Request, res: express.Response) { |
351 | const user = res.locals.user | |
ecb4e35f C |
352 | user.password = req.body.password |
353 | ||
354 | await user.save() | |
355 | ||
356 | return res.status(204).end() | |
357 | } | |
358 | ||
d1ab89de | 359 | async function reSendVerifyUserEmail (req: express.Request, res: express.Response) { |
dae86118 | 360 | const user = res.locals.user |
d9eaee39 JM |
361 | |
362 | await sendVerifyUserEmail(user) | |
363 | ||
364 | return res.status(204).end() | |
365 | } | |
366 | ||
dae86118 C |
367 | async function verifyUserEmail (req: express.Request, res: express.Response) { |
368 | const user = res.locals.user | |
d9eaee39 JM |
369 | user.emailVerified = true |
370 | ||
d1ab89de C |
371 | if (req.body.isPendingEmail === true) { |
372 | user.email = user.pendingEmail | |
373 | user.pendingEmail = null | |
374 | } | |
375 | ||
d9eaee39 JM |
376 | await user.save() |
377 | ||
378 | return res.status(204).end() | |
379 | } | |
380 | ||
453e83ea | 381 | async function changeUserBlock (res: express.Response, user: MUserAccountDefault, block: boolean, reason?: string) { |
e6921918 C |
382 | const oldUserAuditView = new UserAuditView(user.toFormattedJSON()) |
383 | ||
384 | user.blocked = block | |
eacb25c4 | 385 | user.blockedReason = reason || null |
e6921918 C |
386 | |
387 | await sequelizeTypescript.transaction(async t => { | |
f201a749 | 388 | await deleteUserToken(user.id, t) |
e6921918 C |
389 | |
390 | await user.save({ transaction: t }) | |
391 | }) | |
392 | ||
eacb25c4 C |
393 | await Emailer.Instance.addUserBlockJob(user, block, reason) |
394 | ||
91411dba | 395 | auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView) |
e6921918 | 396 | } |