1 import express from 'express'
2 import RateLimit from 'express-rate-limit'
3 import { tokensRouter } from '@server/controllers/api/users/token'
4 import { Hooks } from '@server/lib/plugins/hooks'
5 import { OAuthTokenModel } from '@server/models/oauth/oauth-token'
6 import { MUserAccountDefault } from '@server/types/models'
7 import { pick } from '@shared/core-utils'
8 import { HttpStatusCode, UserCreate, UserCreateResult, UserRegister, UserRight, UserUpdate } from '@shared/models'
9 import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger'
10 import { logger } from '../../../helpers/logger'
11 import { generateRandomString, getFormattedObjects } from '../../../helpers/utils'
12 import { CONFIG } from '../../../initializers/config'
13 import { WEBSERVER } from '../../../initializers/constants'
14 import { sequelizeTypescript } from '../../../initializers/database'
15 import { Emailer } from '../../../lib/emailer'
16 import { Notifier } from '../../../lib/notifier'
17 import { Redis } from '../../../lib/redis'
18 import { buildUser, createUserAccountAndChannelAndPlaylist, sendVerifyUserEmail } from '../../../lib/user'
21 asyncRetryTransactionMiddleware,
24 ensureUserRegistrationAllowed,
25 ensureUserRegistrationAllowedForIP,
29 userAutocompleteValidator,
33 usersRegisterValidator,
37 } from '../../../middlewares'
40 usersAskResetPasswordValidator,
41 usersAskSendVerifyEmailValidator,
42 usersBlockingValidator,
43 usersResetPasswordValidator,
44 usersVerifyEmailValidator
45 } from '../../../middlewares/validators'
46 import { UserModel } from '../../../models/user/user'
47 import { meRouter } from './me'
48 import { myAbusesRouter } from './my-abuses'
49 import { myBlocklistRouter } from './my-blocklist'
50 import { myVideosHistoryRouter } from './my-history'
51 import { myNotificationsRouter } from './my-notifications'
52 import { mySubscriptionsRouter } from './my-subscriptions'
53 import { myVideoPlaylistsRouter } from './my-video-playlists'
55 const auditLogger = auditLoggerFactory('users')
57 const signupRateLimiter = RateLimit({
58 windowMs: CONFIG.RATES_LIMIT.SIGNUP.WINDOW_MS,
59 max: CONFIG.RATES_LIMIT.SIGNUP.MAX,
60 skipFailedRequests: true
63 const askSendEmailLimiter = RateLimit({
64 windowMs: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.WINDOW_MS,
65 max: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.MAX
68 const usersRouter = express.Router()
69 usersRouter.use('/', tokensRouter)
70 usersRouter.use('/', myNotificationsRouter)
71 usersRouter.use('/', mySubscriptionsRouter)
72 usersRouter.use('/', myBlocklistRouter)
73 usersRouter.use('/', myVideosHistoryRouter)
74 usersRouter.use('/', myVideoPlaylistsRouter)
75 usersRouter.use('/', myAbusesRouter)
76 usersRouter.use('/', meRouter)
78 usersRouter.get('/autocomplete',
79 userAutocompleteValidator,
80 asyncMiddleware(autocompleteUsers)
85 ensureUserHasRight(UserRight.MANAGE_USERS),
91 asyncMiddleware(listUsers)
94 usersRouter.post('/:id/block',
96 ensureUserHasRight(UserRight.MANAGE_USERS),
97 asyncMiddleware(usersBlockingValidator),
99 asyncMiddleware(blockUser)
101 usersRouter.post('/:id/unblock',
103 ensureUserHasRight(UserRight.MANAGE_USERS),
104 asyncMiddleware(usersBlockingValidator),
106 asyncMiddleware(unblockUser)
109 usersRouter.get('/:id',
111 ensureUserHasRight(UserRight.MANAGE_USERS),
112 asyncMiddleware(usersGetValidator),
116 usersRouter.post('/',
118 ensureUserHasRight(UserRight.MANAGE_USERS),
119 asyncMiddleware(usersAddValidator),
120 asyncRetryTransactionMiddleware(createUser)
123 usersRouter.post('/register',
125 asyncMiddleware(ensureUserRegistrationAllowed),
126 ensureUserRegistrationAllowedForIP,
127 asyncMiddleware(usersRegisterValidator),
128 asyncRetryTransactionMiddleware(registerUser)
131 usersRouter.put('/:id',
133 ensureUserHasRight(UserRight.MANAGE_USERS),
134 asyncMiddleware(usersUpdateValidator),
136 asyncMiddleware(updateUser)
139 usersRouter.delete('/:id',
141 ensureUserHasRight(UserRight.MANAGE_USERS),
142 asyncMiddleware(usersRemoveValidator),
144 asyncMiddleware(removeUser)
147 usersRouter.post('/ask-reset-password',
148 asyncMiddleware(usersAskResetPasswordValidator),
149 asyncMiddleware(askResetUserPassword)
152 usersRouter.post('/:id/reset-password',
153 asyncMiddleware(usersResetPasswordValidator),
154 asyncMiddleware(resetUserPassword)
157 usersRouter.post('/ask-send-verify-email',
159 asyncMiddleware(usersAskSendVerifyEmailValidator),
160 asyncMiddleware(reSendVerifyUserEmail)
163 usersRouter.post('/:id/verify-email',
164 asyncMiddleware(usersVerifyEmailValidator),
165 asyncMiddleware(verifyUserEmail)
168 // ---------------------------------------------------------------------------
174 // ---------------------------------------------------------------------------
176 async function createUser (req: express.Request, res: express.Response) {
177 const body: UserCreate = req.body
179 const userToCreate = buildUser({
180 ...pick(body, [ 'username', 'password', 'email', 'role', 'videoQuota', 'videoQuotaDaily', 'adminFlags' ]),
185 // NB: due to the validator usersAddValidator, password==='' can only be true if we can send the mail.
186 const createPassword = userToCreate.password === ''
187 if (createPassword) {
188 userToCreate.password = await generateRandomString(20)
191 const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({
193 channelNames: body.channelName && { name: body.channelName, displayName: body.channelName }
196 auditLogger.create(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
197 logger.info('User %s with its channel and account created.', body.username)
199 if (createPassword) {
200 // this will send an email for newly created users, so then can set their first password.
201 logger.info('Sending to user %s a create password email', body.username)
202 const verificationString = await Redis.Instance.setCreatePasswordVerificationString(user.id)
203 const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
204 Emailer.Instance.addPasswordCreateEmailJob(userToCreate.username, user.email, url)
207 Hooks.runAction('action:api.user.created', { body, user, account, videoChannel, req, res })
215 } as UserCreateResult
219 async function registerUser (req: express.Request, res: express.Response) {
220 const body: UserRegister = req.body
222 const userToCreate = buildUser({
223 ...pick(body, [ 'username', 'password', 'email' ]),
225 emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null
228 const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({
229 userToCreate: userToCreate,
230 userDisplayName: body.displayName || undefined,
231 channelNames: body.channel
234 auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON()))
235 logger.info('User %s with its channel and account registered.', body.username)
237 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) {
238 await sendVerifyUserEmail(user)
241 Notifier.Instance.notifyOnNewUserRegistration(user)
243 Hooks.runAction('action:api.user.registered', { body, user, account, videoChannel, req, res })
245 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
248 async function unblockUser (req: express.Request, res: express.Response) {
249 const user = res.locals.user
251 await changeUserBlock(res, user, false)
253 Hooks.runAction('action:api.user.unblocked', { user, req, res })
255 return res.status(HttpStatusCode.NO_CONTENT_204).end()
258 async function blockUser (req: express.Request, res: express.Response) {
259 const user = res.locals.user
260 const reason = req.body.reason
262 await changeUserBlock(res, user, true, reason)
264 Hooks.runAction('action:api.user.blocked', { user, req, res })
266 return res.status(HttpStatusCode.NO_CONTENT_204).end()
269 function getUser (req: express.Request, res: express.Response) {
270 return res.json(res.locals.user.toFormattedJSON({ withAdminFlags: true }))
273 async function autocompleteUsers (req: express.Request, res: express.Response) {
274 const resultList = await UserModel.autoComplete(req.query.search as string)
276 return res.json(resultList)
279 async function listUsers (req: express.Request, res: express.Response) {
280 const resultList = await UserModel.listForApi({
281 start: req.query.start,
282 count: req.query.count,
283 sort: req.query.sort,
284 search: req.query.search,
285 blocked: req.query.blocked
288 return res.json(getFormattedObjects(resultList.data, resultList.total, { withAdminFlags: true }))
291 async function removeUser (req: express.Request, res: express.Response) {
292 const user = res.locals.user
294 auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
296 await sequelizeTypescript.transaction(async t => {
297 // Use a transaction to avoid inconsistencies with hooks (account/channel deletion & federation)
298 await user.destroy({ transaction: t })
301 Hooks.runAction('action:api.user.deleted', { user, req, res })
303 return res.status(HttpStatusCode.NO_CONTENT_204).end()
306 async function updateUser (req: express.Request, res: express.Response) {
307 const body: UserUpdate = req.body
308 const userToUpdate = res.locals.user
309 const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON())
310 const roleChanged = body.role !== undefined && body.role !== userToUpdate.role
312 const keysToUpdate: (keyof UserUpdate)[] = [
323 for (const key of keysToUpdate) {
324 if (body[key] !== undefined) userToUpdate.set(key, body[key])
327 const user = await userToUpdate.save()
329 // Destroy user token to refresh rights
330 if (roleChanged || body.password !== undefined) await OAuthTokenModel.deleteUserToken(userToUpdate.id)
332 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
334 Hooks.runAction('action:api.user.updated', { user, req, res })
336 // Don't need to send this update to followers, these attributes are not federated
338 return res.status(HttpStatusCode.NO_CONTENT_204).end()
341 async function askResetUserPassword (req: express.Request, res: express.Response) {
342 const user = res.locals.user
344 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
345 const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
346 await Emailer.Instance.addPasswordResetEmailJob(user.username, user.email, url)
348 return res.status(HttpStatusCode.NO_CONTENT_204).end()
351 async function resetUserPassword (req: express.Request, res: express.Response) {
352 const user = res.locals.user
353 user.password = req.body.password
356 await Redis.Instance.removePasswordVerificationString(user.id)
358 return res.status(HttpStatusCode.NO_CONTENT_204).end()
361 async function reSendVerifyUserEmail (req: express.Request, res: express.Response) {
362 const user = res.locals.user
364 await sendVerifyUserEmail(user)
366 return res.status(HttpStatusCode.NO_CONTENT_204).end()
369 async function verifyUserEmail (req: express.Request, res: express.Response) {
370 const user = res.locals.user
371 user.emailVerified = true
373 if (req.body.isPendingEmail === true) {
374 user.email = user.pendingEmail
375 user.pendingEmail = null
380 return res.status(HttpStatusCode.NO_CONTENT_204).end()
383 async function changeUserBlock (res: express.Response, user: MUserAccountDefault, block: boolean, reason?: string) {
384 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
387 user.blockedReason = reason || null
389 await sequelizeTypescript.transaction(async t => {
390 await OAuthTokenModel.deleteUserToken(user.id, t)
392 await user.save({ transaction: t })
395 await Emailer.Instance.addUserBlockJob(user, block, reason)
397 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)