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