1 import * as express from 'express'
2 import * as RateLimit from 'express-rate-limit'
3 import { UserCreate, UserRight, UserRole, UserUpdate } from '../../../../shared'
4 import { logger } from '../../../helpers/logger'
5 import { generateRandomString, getFormattedObjects } from '../../../helpers/utils'
6 import { WEBSERVER } from '../../../initializers/constants'
7 import { Emailer } from '../../../lib/emailer'
8 import { Redis } from '../../../lib/redis'
9 import { createUserAccountAndChannelAndPlaylist, sendVerifyUserEmail } from '../../../lib/user'
12 asyncRetryTransactionMiddleware,
15 ensureUserRegistrationAllowed,
16 ensureUserRegistrationAllowedForIP,
20 userAutocompleteValidator,
24 usersRegisterValidator,
28 } from '../../../middlewares'
31 usersAskResetPasswordValidator,
32 usersAskSendVerifyEmailValidator,
33 usersBlockingValidator,
34 usersResetPasswordValidator,
35 usersVerifyEmailValidator
36 } from '../../../middlewares/validators'
37 import { UserModel } from '../../../models/account/user'
38 import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger'
39 import { meRouter } from './me'
40 import { deleteUserToken } from '../../../lib/oauth-model'
41 import { myBlocklistRouter } from './my-blocklist'
42 import { myVideoPlaylistsRouter } from './my-video-playlists'
43 import { myVideosHistoryRouter } from './my-history'
44 import { myNotificationsRouter } from './my-notifications'
45 import { Notifier } from '../../../lib/notifier'
46 import { mySubscriptionsRouter } from './my-subscriptions'
47 import { CONFIG } from '../../../initializers/config'
48 import { sequelizeTypescript } from '../../../initializers/database'
49 import { UserAdminFlag } from '../../../../shared/models/users/user-flag.model'
50 import { UserRegister } from '../../../../shared/models/users/user-register.model'
51 import { MUser, MUserAccountDefault } from '@server/types/models'
52 import { Hooks } from '@server/lib/plugins/hooks'
53 import { tokensRouter } from '@server/controllers/api/users/token'
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('/', 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
177 const userToCreate = new UserModel({
178 username: body.username,
179 password: body.password,
181 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
184 videoQuota: body.videoQuota,
185 videoQuotaDaily: body.videoQuotaDaily,
186 adminFlags: body.adminFlags || UserAdminFlag.NONE
189 // NB: due to the validator usersAddValidator, password==='' can only be true if we can send the mail.
190 const createPassword = userToCreate.password === ''
191 if (createPassword) {
192 userToCreate.password = await generateRandomString(20)
195 const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({ userToCreate: userToCreate })
197 auditLogger.create(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
198 logger.info('User %s with its channel and account created.', body.username)
200 if (createPassword) {
201 // this will send an email for newly created users, so then can set their first password.
202 logger.info('Sending to user %s a create password email', body.username)
203 const verificationString = await Redis.Instance.setCreatePasswordVerificationString(user.id)
204 const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
205 await Emailer.Instance.addPasswordCreateEmailJob(userToCreate.username, user.email, url)
208 Hooks.runAction('action:api.user.created', { body, user, account, videoChannel })
220 async function registerUser (req: express.Request, res: express.Response) {
221 const body: UserRegister = req.body
223 const userToCreate = new UserModel({
224 username: body.username,
225 password: body.password,
227 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
230 videoQuota: CONFIG.USER.VIDEO_QUOTA,
231 videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY,
232 emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null
235 const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({
236 userToCreate: userToCreate,
237 userDisplayName: body.displayName || undefined,
238 channelNames: body.channel
241 auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON()))
242 logger.info('User %s with its channel and account registered.', body.username)
244 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) {
245 await sendVerifyUserEmail(user)
248 Notifier.Instance.notifyOnNewUserRegistration(user)
250 Hooks.runAction('action:api.user.registered', { body, user, account, videoChannel })
252 return res.type('json').status(204).end()
255 async function unblockUser (req: express.Request, res: express.Response) {
256 const user = res.locals.user
258 await changeUserBlock(res, user, false)
260 Hooks.runAction('action:api.user.unblocked', { user })
262 return res.status(204).end()
265 async function blockUser (req: express.Request, res: express.Response) {
266 const user = res.locals.user
267 const reason = req.body.reason
269 await changeUserBlock(res, user, true, reason)
271 Hooks.runAction('action:api.user.blocked', { user })
273 return res.status(204).end()
276 function getUser (req: express.Request, res: express.Response) {
277 return res.json(res.locals.user.toFormattedJSON({ withAdminFlags: true }))
280 async function autocompleteUsers (req: express.Request, res: express.Response) {
281 const resultList = await UserModel.autoComplete(req.query.search as string)
283 return res.json(resultList)
286 async function listUsers (req: express.Request, res: express.Response) {
287 const resultList = await UserModel.listForApi({
288 start: req.query.start,
289 count: req.query.count,
290 sort: req.query.sort,
291 search: req.query.search,
292 blocked: req.query.blocked
295 return res.json(getFormattedObjects(resultList.data, resultList.total, { withAdminFlags: true }))
298 async function removeUser (req: express.Request, res: express.Response) {
299 const user = res.locals.user
303 auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
305 Hooks.runAction('action:api.user.deleted', { user })
307 return res.sendStatus(204)
310 async function updateUser (req: express.Request, res: express.Response) {
311 const body: UserUpdate = req.body
312 const userToUpdate = res.locals.user
313 const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON())
314 const roleChanged = body.role !== undefined && body.role !== userToUpdate.role
316 if (body.password !== undefined) userToUpdate.password = body.password
317 if (body.email !== undefined) userToUpdate.email = body.email
318 if (body.emailVerified !== undefined) userToUpdate.emailVerified = body.emailVerified
319 if (body.videoQuota !== undefined) userToUpdate.videoQuota = body.videoQuota
320 if (body.videoQuotaDaily !== undefined) userToUpdate.videoQuotaDaily = body.videoQuotaDaily
321 if (body.role !== undefined) userToUpdate.role = body.role
322 if (body.adminFlags !== undefined) userToUpdate.adminFlags = body.adminFlags
324 const user = await userToUpdate.save()
326 // Destroy user token to refresh rights
327 if (roleChanged || body.password !== undefined) await deleteUserToken(userToUpdate.id)
329 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
331 Hooks.runAction('action:api.user.updated', { user })
333 // Don't need to send this update to followers, these attributes are not federated
335 return res.sendStatus(204)
338 async function askResetUserPassword (req: express.Request, res: express.Response) {
339 const user = res.locals.user
341 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
342 const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
343 await Emailer.Instance.addPasswordResetEmailJob(user.username, user.email, url)
345 return res.status(204).end()
348 async function resetUserPassword (req: express.Request, res: express.Response) {
349 const user = res.locals.user
350 user.password = req.body.password
354 return res.status(204).end()
357 async function reSendVerifyUserEmail (req: express.Request, res: express.Response) {
358 const user = res.locals.user
360 await sendVerifyUserEmail(user)
362 return res.status(204).end()
365 async function verifyUserEmail (req: express.Request, res: express.Response) {
366 const user = res.locals.user
367 user.emailVerified = true
369 if (req.body.isPendingEmail === true) {
370 user.email = user.pendingEmail
371 user.pendingEmail = null
376 return res.status(204).end()
379 async function changeUserBlock (res: express.Response, user: MUserAccountDefault, block: boolean, reason?: string) {
380 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
383 user.blockedReason = reason || null
385 await sequelizeTypescript.transaction(async t => {
386 await deleteUserToken(user.id, t)
388 await user.save({ transaction: t })
391 await Emailer.Instance.addUserBlockJob(user, block, reason)
393 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)