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,
23 usersRegisterValidator,
27 } from '../../../middlewares'
30 usersAskResetPasswordValidator,
31 usersAskSendVerifyEmailValidator,
32 usersBlockingValidator,
33 usersResetPasswordValidator,
34 usersVerifyEmailValidator
35 } from '../../../middlewares/validators'
36 import { UserModel } from '../../../models/account/user'
37 import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger'
38 import { meRouter } from './me'
39 import { deleteUserToken } from '../../../lib/oauth-model'
40 import { myBlocklistRouter } from './my-blocklist'
41 import { myVideoPlaylistsRouter } from './my-video-playlists'
42 import { myVideosHistoryRouter } from './my-history'
43 import { myNotificationsRouter } from './my-notifications'
44 import { Notifier } from '../../../lib/notifier'
45 import { mySubscriptionsRouter } from './my-subscriptions'
46 import { CONFIG } from '../../../initializers/config'
47 import { sequelizeTypescript } from '../../../initializers/database'
48 import { UserAdminFlag } from '../../../../shared/models/users/user-flag.model'
49 import { UserRegister } from '../../../../shared/models/users/user-register.model'
50 import { MUser, MUserAccountDefault } from '@server/typings/models'
51 import { Hooks } from '@server/lib/plugins/hooks'
52 import { tokensRouter } from '@server/controllers/api/users/token'
54 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
64 const askSendEmailLimiter = new RateLimit({
65 windowMs: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.WINDOW_MS,
66 max: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.MAX
69 const usersRouter = express.Router()
70 usersRouter.use('/', tokensRouter)
71 usersRouter.use('/', myNotificationsRouter)
72 usersRouter.use('/', mySubscriptionsRouter)
73 usersRouter.use('/', myBlocklistRouter)
74 usersRouter.use('/', myVideosHistoryRouter)
75 usersRouter.use('/', myVideoPlaylistsRouter)
76 usersRouter.use('/', meRouter)
78 usersRouter.get('/autocomplete',
79 userAutocompleteValidator,
80 asyncMiddleware(autocompleteUsers)
85 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(req.query.start, req.query.count, req.query.sort, req.query.search)
289 return res.json(getFormattedObjects(resultList.data, resultList.total, { withAdminFlags: true }))
292 async function removeUser (req: express.Request, res: express.Response) {
293 const user = res.locals.user
297 auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
299 Hooks.runAction('action:api.user.deleted', { user })
301 return res.sendStatus(204)
304 async function updateUser (req: express.Request, res: express.Response) {
305 const body: UserUpdate = req.body
306 const userToUpdate = res.locals.user
307 const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON())
308 const roleChanged = body.role !== undefined && body.role !== userToUpdate.role
310 if (body.password !== undefined) userToUpdate.password = body.password
311 if (body.email !== undefined) userToUpdate.email = body.email
312 if (body.emailVerified !== undefined) userToUpdate.emailVerified = body.emailVerified
313 if (body.videoQuota !== undefined) userToUpdate.videoQuota = body.videoQuota
314 if (body.videoQuotaDaily !== undefined) userToUpdate.videoQuotaDaily = body.videoQuotaDaily
315 if (body.role !== undefined) userToUpdate.role = body.role
316 if (body.adminFlags !== undefined) userToUpdate.adminFlags = body.adminFlags
318 const user = await userToUpdate.save()
320 // Destroy user token to refresh rights
321 if (roleChanged || body.password !== undefined) await deleteUserToken(userToUpdate.id)
323 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
325 Hooks.runAction('action:api.user.updated', { user })
327 // Don't need to send this update to followers, these attributes are not federated
329 return res.sendStatus(204)
332 async function askResetUserPassword (req: express.Request, res: express.Response) {
333 const user = res.locals.user
335 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
336 const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
337 await Emailer.Instance.addPasswordResetEmailJob(user.email, url)
339 return res.status(204).end()
342 async function resetUserPassword (req: express.Request, res: express.Response) {
343 const user = res.locals.user
344 user.password = req.body.password
348 return res.status(204).end()
351 async function reSendVerifyUserEmail (req: express.Request, res: express.Response) {
352 const user = res.locals.user
354 await sendVerifyUserEmail(user)
356 return res.status(204).end()
359 async function verifyUserEmail (req: express.Request, res: express.Response) {
360 const user = res.locals.user
361 user.emailVerified = true
363 if (req.body.isPendingEmail === true) {
364 user.email = user.pendingEmail
365 user.pendingEmail = null
370 return res.status(204).end()
373 async function changeUserBlock (res: express.Response, user: MUserAccountDefault, block: boolean, reason?: string) {
374 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
377 user.blockedReason = reason || null
379 await sequelizeTypescript.transaction(async t => {
380 await deleteUserToken(user.id, t)
382 await user.save({ transaction: t })
385 await Emailer.Instance.addUserBlockJob(user, block, reason)
387 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)