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