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 { MUser, MUserAccountDefault } from '@server/types/models'
7 import { HttpStatusCode, UserAdminFlag, UserCreate, UserCreateResult, UserRegister, UserRight, UserRole, UserUpdate } from '@shared/models'
8 import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger'
9 import { logger } from '../../../helpers/logger'
10 import { generateRandomString, getFormattedObjects } from '../../../helpers/utils'
11 import { CONFIG } from '../../../initializers/config'
12 import { WEBSERVER } from '../../../initializers/constants'
13 import { sequelizeTypescript } from '../../../initializers/database'
14 import { Emailer } from '../../../lib/emailer'
15 import { Notifier } from '../../../lib/notifier'
16 import { Redis } from '../../../lib/redis'
17 import { createUserAccountAndChannelAndPlaylist, sendVerifyUserEmail } from '../../../lib/user'
20 asyncRetryTransactionMiddleware,
23 ensureUserRegistrationAllowed,
24 ensureUserRegistrationAllowedForIP,
28 userAutocompleteValidator,
32 usersRegisterValidator,
36 } from '../../../middlewares'
39 usersAskResetPasswordValidator,
40 usersAskSendVerifyEmailValidator,
41 usersBlockingValidator,
42 usersResetPasswordValidator,
43 usersVerifyEmailValidator
44 } from '../../../middlewares/validators'
45 import { UserModel } from '../../../models/user/user'
46 import { meRouter } from './me'
47 import { myAbusesRouter } from './my-abuses'
48 import { myBlocklistRouter } from './my-blocklist'
49 import { myVideosHistoryRouter } from './my-history'
50 import { myNotificationsRouter } from './my-notifications'
51 import { mySubscriptionsRouter } from './my-subscriptions'
52 import { myVideoPlaylistsRouter } from './my-video-playlists'
54 const auditLogger = auditLoggerFactory('users')
56 const signupRateLimiter = RateLimit({
57 windowMs: CONFIG.RATES_LIMIT.SIGNUP.WINDOW_MS,
58 max: CONFIG.RATES_LIMIT.SIGNUP.MAX,
59 skipFailedRequests: true
62 const askSendEmailLimiter = RateLimit({
63 windowMs: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.WINDOW_MS,
64 max: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.MAX
67 const usersRouter = express.Router()
68 usersRouter.use('/', tokensRouter)
69 usersRouter.use('/', myNotificationsRouter)
70 usersRouter.use('/', mySubscriptionsRouter)
71 usersRouter.use('/', myBlocklistRouter)
72 usersRouter.use('/', myVideosHistoryRouter)
73 usersRouter.use('/', myVideoPlaylistsRouter)
74 usersRouter.use('/', myAbusesRouter)
75 usersRouter.use('/', meRouter)
77 usersRouter.get('/autocomplete',
78 userAutocompleteValidator,
79 asyncMiddleware(autocompleteUsers)
84 ensureUserHasRight(UserRight.MANAGE_USERS),
90 asyncMiddleware(listUsers)
93 usersRouter.post('/:id/block',
95 ensureUserHasRight(UserRight.MANAGE_USERS),
96 asyncMiddleware(usersBlockingValidator),
98 asyncMiddleware(blockUser)
100 usersRouter.post('/:id/unblock',
102 ensureUserHasRight(UserRight.MANAGE_USERS),
103 asyncMiddleware(usersBlockingValidator),
105 asyncMiddleware(unblockUser)
108 usersRouter.get('/:id',
110 ensureUserHasRight(UserRight.MANAGE_USERS),
111 asyncMiddleware(usersGetValidator),
115 usersRouter.post('/',
117 ensureUserHasRight(UserRight.MANAGE_USERS),
118 asyncMiddleware(usersAddValidator),
119 asyncRetryTransactionMiddleware(createUser)
122 usersRouter.post('/register',
124 asyncMiddleware(ensureUserRegistrationAllowed),
125 ensureUserRegistrationAllowedForIP,
126 asyncMiddleware(usersRegisterValidator),
127 asyncRetryTransactionMiddleware(registerUser)
130 usersRouter.put('/:id',
132 ensureUserHasRight(UserRight.MANAGE_USERS),
133 asyncMiddleware(usersUpdateValidator),
135 asyncMiddleware(updateUser)
138 usersRouter.delete('/:id',
140 ensureUserHasRight(UserRight.MANAGE_USERS),
141 asyncMiddleware(usersRemoveValidator),
143 asyncMiddleware(removeUser)
146 usersRouter.post('/ask-reset-password',
147 asyncMiddleware(usersAskResetPasswordValidator),
148 asyncMiddleware(askResetUserPassword)
151 usersRouter.post('/:id/reset-password',
152 asyncMiddleware(usersResetPasswordValidator),
153 asyncMiddleware(resetUserPassword)
156 usersRouter.post('/ask-send-verify-email',
158 asyncMiddleware(usersAskSendVerifyEmailValidator),
159 asyncMiddleware(reSendVerifyUserEmail)
162 usersRouter.post('/:id/verify-email',
163 asyncMiddleware(usersVerifyEmailValidator),
164 asyncMiddleware(verifyUserEmail)
167 // ---------------------------------------------------------------------------
173 // ---------------------------------------------------------------------------
175 async function createUser (req: express.Request, res: express.Response) {
176 const body: UserCreate = req.body
178 const userToCreate = new UserModel({
179 username: body.username,
180 password: body.password,
182 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
183 p2pEnabled: CONFIG.DEFAULTS.P2P.WEBAPP.ENABLED,
186 videoQuota: body.videoQuota,
187 videoQuotaDaily: body.videoQuotaDaily,
188 adminFlags: body.adminFlags || UserAdminFlag.NONE
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)
197 const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({
199 channelNames: body.channelName && { name: body.channelName, displayName: body.channelName }
202 auditLogger.create(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
203 logger.info('User %s with its channel and account created.', body.username)
205 if (createPassword) {
206 // this will send an email for newly created users, so then can set their first password.
207 logger.info('Sending to user %s a create password email', body.username)
208 const verificationString = await Redis.Instance.setCreatePasswordVerificationString(user.id)
209 const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
210 Emailer.Instance.addPasswordCreateEmailJob(userToCreate.username, user.email, url)
213 Hooks.runAction('action:api.user.created', { body, user, account, videoChannel, req, res })
221 } as UserCreateResult
225 async function registerUser (req: express.Request, res: express.Response) {
226 const body: UserRegister = req.body
228 const userToCreate = new UserModel({
229 username: body.username,
230 password: body.password,
232 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
233 p2pEnabled: CONFIG.DEFAULTS.P2P.WEBAPP.ENABLED,
236 videoQuota: CONFIG.USER.VIDEO_QUOTA,
237 videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY,
238 emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null
241 const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({
242 userToCreate: userToCreate,
243 userDisplayName: body.displayName || undefined,
244 channelNames: body.channel
247 auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON()))
248 logger.info('User %s with its channel and account registered.', body.username)
250 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) {
251 await sendVerifyUserEmail(user)
254 Notifier.Instance.notifyOnNewUserRegistration(user)
256 Hooks.runAction('action:api.user.registered', { body, user, account, videoChannel, req, res })
258 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
261 async function unblockUser (req: express.Request, res: express.Response) {
262 const user = res.locals.user
264 await changeUserBlock(res, user, false)
266 Hooks.runAction('action:api.user.unblocked', { user, req, res })
268 return res.status(HttpStatusCode.NO_CONTENT_204).end()
271 async function blockUser (req: express.Request, res: express.Response) {
272 const user = res.locals.user
273 const reason = req.body.reason
275 await changeUserBlock(res, user, true, reason)
277 Hooks.runAction('action:api.user.blocked', { user, req, res })
279 return res.status(HttpStatusCode.NO_CONTENT_204).end()
282 function getUser (req: express.Request, res: express.Response) {
283 return res.json(res.locals.user.toFormattedJSON({ withAdminFlags: true }))
286 async function autocompleteUsers (req: express.Request, res: express.Response) {
287 const resultList = await UserModel.autoComplete(req.query.search as string)
289 return res.json(resultList)
292 async function listUsers (req: express.Request, res: express.Response) {
293 const resultList = await UserModel.listForApi({
294 start: req.query.start,
295 count: req.query.count,
296 sort: req.query.sort,
297 search: req.query.search,
298 blocked: req.query.blocked
301 return res.json(getFormattedObjects(resultList.data, resultList.total, { withAdminFlags: true }))
304 async function removeUser (req: express.Request, res: express.Response) {
305 const user = res.locals.user
307 auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
309 await sequelizeTypescript.transaction(async t => {
310 // Use a transaction to avoid inconsistencies with hooks (account/channel deletion & federation)
311 await user.destroy({ transaction: t })
314 Hooks.runAction('action:api.user.deleted', { user, req, res })
316 return res.status(HttpStatusCode.NO_CONTENT_204).end()
319 async function updateUser (req: express.Request, res: express.Response) {
320 const body: UserUpdate = req.body
321 const userToUpdate = res.locals.user
322 const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON())
323 const roleChanged = body.role !== undefined && body.role !== userToUpdate.role
325 const keysToUpdate: (keyof UserUpdate)[] = [
336 for (const key of keysToUpdate) {
337 if (body[key] !== undefined) userToUpdate.set(key, body[key])
340 const user = await userToUpdate.save()
342 // Destroy user token to refresh rights
343 if (roleChanged || body.password !== undefined) await OAuthTokenModel.deleteUserToken(userToUpdate.id)
345 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
347 Hooks.runAction('action:api.user.updated', { user, req, res })
349 // Don't need to send this update to followers, these attributes are not federated
351 return res.status(HttpStatusCode.NO_CONTENT_204).end()
354 async function askResetUserPassword (req: express.Request, res: express.Response) {
355 const user = res.locals.user
357 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
358 const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
359 await Emailer.Instance.addPasswordResetEmailJob(user.username, user.email, url)
361 return res.status(HttpStatusCode.NO_CONTENT_204).end()
364 async function resetUserPassword (req: express.Request, res: express.Response) {
365 const user = res.locals.user
366 user.password = req.body.password
369 await Redis.Instance.removePasswordVerificationString(user.id)
371 return res.status(HttpStatusCode.NO_CONTENT_204).end()
374 async function reSendVerifyUserEmail (req: express.Request, res: express.Response) {
375 const user = res.locals.user
377 await sendVerifyUserEmail(user)
379 return res.status(HttpStatusCode.NO_CONTENT_204).end()
382 async function verifyUserEmail (req: express.Request, res: express.Response) {
383 const user = res.locals.user
384 user.emailVerified = true
386 if (req.body.isPendingEmail === true) {
387 user.email = user.pendingEmail
388 user.pendingEmail = null
393 return res.status(HttpStatusCode.NO_CONTENT_204).end()
396 async function changeUserBlock (res: express.Response, user: MUserAccountDefault, block: boolean, reason?: string) {
397 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
400 user.blockedReason = reason || null
402 await sequelizeTypescript.transaction(async t => {
403 await OAuthTokenModel.deleteUserToken(user.id, t)
405 await user.save({ transaction: t })
408 await Emailer.Instance.addUserBlockJob(user, block, reason)
410 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)