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,
21 userAutocompleteValidator,
24 usersRegisterValidator,
28 } from '../../../middlewares'
30 usersAskResetPasswordValidator,
31 usersAskSendVerifyEmailValidator,
32 usersBlockingValidator,
33 usersResetPasswordValidator,
34 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/typings/models'
52 import { Hooks } from '@server/lib/plugins/hooks'
54 const auditLogger = auditLoggerFactory('users')
56 const loginRateLimiter = RateLimit({
57 windowMs: CONFIG.RATES_LIMIT.LOGIN.WINDOW_MS,
58 max: CONFIG.RATES_LIMIT.LOGIN.MAX
62 const signupRateLimiter = RateLimit({
63 windowMs: CONFIG.RATES_LIMIT.SIGNUP.WINDOW_MS,
64 max: CONFIG.RATES_LIMIT.SIGNUP.MAX,
65 skipFailedRequests: true
69 const askSendEmailLimiter = new RateLimit({
70 windowMs: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.WINDOW_MS,
71 max: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.MAX
74 const usersRouter = express.Router()
75 usersRouter.use('/', myNotificationsRouter)
76 usersRouter.use('/', mySubscriptionsRouter)
77 usersRouter.use('/', myBlocklistRouter)
78 usersRouter.use('/', myVideosHistoryRouter)
79 usersRouter.use('/', myVideoPlaylistsRouter)
80 usersRouter.use('/', meRouter)
82 usersRouter.get('/autocomplete',
83 userAutocompleteValidator,
84 asyncMiddleware(autocompleteUsers)
89 ensureUserHasRight(UserRight.MANAGE_USERS),
94 asyncMiddleware(listUsers)
97 usersRouter.post('/:id/block',
99 ensureUserHasRight(UserRight.MANAGE_USERS),
100 asyncMiddleware(usersBlockingValidator),
102 asyncMiddleware(blockUser)
104 usersRouter.post('/:id/unblock',
106 ensureUserHasRight(UserRight.MANAGE_USERS),
107 asyncMiddleware(usersBlockingValidator),
109 asyncMiddleware(unblockUser)
112 usersRouter.get('/:id',
114 ensureUserHasRight(UserRight.MANAGE_USERS),
115 asyncMiddleware(usersGetValidator),
119 usersRouter.post('/',
121 ensureUserHasRight(UserRight.MANAGE_USERS),
122 asyncMiddleware(usersAddValidator),
123 asyncRetryTransactionMiddleware(createUser)
126 usersRouter.post('/register',
128 asyncMiddleware(ensureUserRegistrationAllowed),
129 ensureUserRegistrationAllowedForIP,
130 asyncMiddleware(usersRegisterValidator),
131 asyncRetryTransactionMiddleware(registerUser)
134 usersRouter.put('/:id',
136 ensureUserHasRight(UserRight.MANAGE_USERS),
137 asyncMiddleware(usersUpdateValidator),
139 asyncMiddleware(updateUser)
142 usersRouter.delete('/:id',
144 ensureUserHasRight(UserRight.MANAGE_USERS),
145 asyncMiddleware(usersRemoveValidator),
147 asyncMiddleware(removeUser)
150 usersRouter.post('/ask-reset-password',
151 asyncMiddleware(usersAskResetPasswordValidator),
152 asyncMiddleware(askResetUserPassword)
155 usersRouter.post('/:id/reset-password',
156 asyncMiddleware(usersResetPasswordValidator),
157 asyncMiddleware(resetUserPassword)
160 usersRouter.post('/ask-send-verify-email',
162 asyncMiddleware(usersAskSendVerifyEmailValidator),
163 asyncMiddleware(reSendVerifyUserEmail)
166 usersRouter.post('/:id/verify-email',
167 asyncMiddleware(usersVerifyEmailValidator),
168 asyncMiddleware(verifyUserEmail)
171 usersRouter.post('/token',
176 // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
178 // ---------------------------------------------------------------------------
184 // ---------------------------------------------------------------------------
186 async function createUser (req: express.Request, res: express.Response) {
187 const body: UserCreate = req.body
188 const userToCreate = new UserModel({
189 username: body.username,
190 password: body.password,
192 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
195 videoQuota: body.videoQuota,
196 videoQuotaDaily: body.videoQuotaDaily,
197 adminFlags: body.adminFlags || UserAdminFlag.NONE
200 // NB: due to the validator usersAddValidator, password==='' can only be true if we can send the mail.
201 const createPassword = userToCreate.password === ''
202 if (createPassword) {
203 userToCreate.password = await generateRandomString(20)
206 const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({ userToCreate: userToCreate })
208 auditLogger.create(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
209 logger.info('User %s with its channel and account created.', body.username)
211 if (createPassword) {
212 // this will send an email for newly created users, so then can set their first password.
213 logger.info('Sending to user %s a create password email', body.username)
214 const verificationString = await Redis.Instance.setCreatePasswordVerificationString(user.id)
215 const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
216 await Emailer.Instance.addPasswordCreateEmailJob(userToCreate.username, user.email, url)
219 Hooks.runAction('action:api.user.created', { body, user, account, videoChannel })
231 async function registerUser (req: express.Request, res: express.Response) {
232 const body: UserRegister = req.body
234 const userToCreate = new UserModel({
235 username: body.username,
236 password: body.password,
238 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
241 videoQuota: CONFIG.USER.VIDEO_QUOTA,
242 videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY,
243 emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null
246 const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({
247 userToCreate: userToCreate,
248 userDisplayName: body.displayName || undefined,
249 channelNames: body.channel
252 auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON()))
253 logger.info('User %s with its channel and account registered.', body.username)
255 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) {
256 await sendVerifyUserEmail(user)
259 Notifier.Instance.notifyOnNewUserRegistration(user)
261 Hooks.runAction('action:api.user.registered', { body, user, account, videoChannel })
263 return res.type('json').status(204).end()
266 async function unblockUser (req: express.Request, res: express.Response) {
267 const user = res.locals.user
269 await changeUserBlock(res, user, false)
271 Hooks.runAction('action:api.user.unblocked', { user })
273 return res.status(204).end()
276 async function blockUser (req: express.Request, res: express.Response) {
277 const user = res.locals.user
278 const reason = req.body.reason
280 await changeUserBlock(res, user, true, reason)
282 Hooks.runAction('action:api.user.blocked', { user })
284 return res.status(204).end()
287 function getUser (req: express.Request, res: express.Response) {
288 return res.json(res.locals.user.toFormattedJSON({ withAdminFlags: true }))
291 async function autocompleteUsers (req: express.Request, res: express.Response) {
292 const resultList = await UserModel.autoComplete(req.query.search as string)
294 return res.json(resultList)
297 async function listUsers (req: express.Request, res: express.Response) {
298 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort, req.query.search)
300 return res.json(getFormattedObjects(resultList.data, resultList.total, { withAdminFlags: true }))
303 async function removeUser (req: express.Request, res: express.Response) {
304 const user = res.locals.user
308 auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
310 Hooks.runAction('action:api.user.deleted', { user })
312 return res.sendStatus(204)
315 async function updateUser (req: express.Request, res: express.Response) {
316 const body: UserUpdate = req.body
317 const userToUpdate = res.locals.user
318 const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON())
319 const roleChanged = body.role !== undefined && body.role !== userToUpdate.role
321 if (body.password !== undefined) userToUpdate.password = body.password
322 if (body.email !== undefined) userToUpdate.email = body.email
323 if (body.emailVerified !== undefined) userToUpdate.emailVerified = body.emailVerified
324 if (body.videoQuota !== undefined) userToUpdate.videoQuota = body.videoQuota
325 if (body.videoQuotaDaily !== undefined) userToUpdate.videoQuotaDaily = body.videoQuotaDaily
326 if (body.role !== undefined) userToUpdate.role = body.role
327 if (body.adminFlags !== undefined) userToUpdate.adminFlags = body.adminFlags
329 const user = await userToUpdate.save()
331 // Destroy user token to refresh rights
332 if (roleChanged || body.password !== undefined) await deleteUserToken(userToUpdate.id)
334 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
336 Hooks.runAction('action:api.user.updated', { user })
338 // Don't need to send this update to followers, these attributes are not federated
340 return res.sendStatus(204)
343 async function askResetUserPassword (req: express.Request, res: express.Response) {
344 const user = res.locals.user
346 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
347 const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
348 await Emailer.Instance.addPasswordResetEmailJob(user.email, url)
350 return res.status(204).end()
353 async function resetUserPassword (req: express.Request, res: express.Response) {
354 const user = res.locals.user
355 user.password = req.body.password
359 return res.status(204).end()
362 async function reSendVerifyUserEmail (req: express.Request, res: express.Response) {
363 const user = res.locals.user
365 await sendVerifyUserEmail(user)
367 return res.status(204).end()
370 async function verifyUserEmail (req: express.Request, res: express.Response) {
371 const user = res.locals.user
372 user.emailVerified = true
374 if (req.body.isPendingEmail === true) {
375 user.email = user.pendingEmail
376 user.pendingEmail = null
381 return res.status(204).end()
384 function tokenSuccess (req: express.Request) {
385 const username = req.body.username
387 Hooks.runAction('action:api.user.oauth2-got-token', { username, ip: req.ip })
390 async function changeUserBlock (res: express.Response, user: MUserAccountDefault, block: boolean, reason?: string) {
391 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
394 user.blockedReason = reason || null
396 await sequelizeTypescript.transaction(async t => {
397 await deleteUserToken(user.id, t)
399 await user.save({ transaction: t })
402 await Emailer.Instance.addUserBlockJob(user, block, reason)
404 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)