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 { getFormattedObjects } from '../../../helpers/utils'
6 import { CONFIG, RATES_LIMIT, sequelizeTypescript } from '../../../initializers'
7 import { Emailer } from '../../../lib/emailer'
8 import { Redis } from '../../../lib/redis'
9 import { createUserAccountAndChannel } from '../../../lib/user'
12 asyncRetryTransactionMiddleware,
15 ensureUserRegistrationAllowed,
16 ensureUserRegistrationAllowedForIP,
23 usersRegisterValidator,
27 } from '../../../middlewares'
29 usersAskResetPasswordValidator, usersBlockingValidator, usersResetPasswordValidator,
30 usersAskSendVerifyEmailValidator, usersVerifyEmailValidator
31 } from '../../../middlewares/validators'
32 import { UserModel } from '../../../models/account/user'
33 import { OAuthTokenModel } from '../../../models/oauth/oauth-token'
34 import { auditLoggerFactory, UserAuditView } from '../../../helpers/audit-logger'
35 import { meRouter } from './me'
37 const auditLogger = auditLoggerFactory('users')
39 const loginRateLimiter = new RateLimit({
40 windowMs: RATES_LIMIT.LOGIN.WINDOW_MS,
41 max: RATES_LIMIT.LOGIN.MAX,
45 const askSendEmailLimiter = new RateLimit({
46 windowMs: RATES_LIMIT.ASK_SEND_EMAIL.WINDOW_MS,
47 max: RATES_LIMIT.ASK_SEND_EMAIL.MAX,
51 const usersRouter = express.Router()
52 usersRouter.use('/', meRouter)
56 ensureUserHasRight(UserRight.MANAGE_USERS),
61 asyncMiddleware(listUsers)
64 usersRouter.post('/:id/block',
66 ensureUserHasRight(UserRight.MANAGE_USERS),
67 asyncMiddleware(usersBlockingValidator),
68 asyncMiddleware(blockUser)
70 usersRouter.post('/:id/unblock',
72 ensureUserHasRight(UserRight.MANAGE_USERS),
73 asyncMiddleware(usersBlockingValidator),
74 asyncMiddleware(unblockUser)
77 usersRouter.get('/:id',
79 ensureUserHasRight(UserRight.MANAGE_USERS),
80 asyncMiddleware(usersGetValidator),
86 ensureUserHasRight(UserRight.MANAGE_USERS),
87 asyncMiddleware(usersAddValidator),
88 asyncRetryTransactionMiddleware(createUser)
91 usersRouter.post('/register',
92 asyncMiddleware(ensureUserRegistrationAllowed),
93 ensureUserRegistrationAllowedForIP,
94 asyncMiddleware(usersRegisterValidator),
95 asyncRetryTransactionMiddleware(registerUser)
98 usersRouter.put('/:id',
100 ensureUserHasRight(UserRight.MANAGE_USERS),
101 asyncMiddleware(usersUpdateValidator),
102 asyncMiddleware(updateUser)
105 usersRouter.delete('/:id',
107 ensureUserHasRight(UserRight.MANAGE_USERS),
108 asyncMiddleware(usersRemoveValidator),
109 asyncMiddleware(removeUser)
112 usersRouter.post('/ask-reset-password',
113 asyncMiddleware(usersAskResetPasswordValidator),
114 asyncMiddleware(askResetUserPassword)
117 usersRouter.post('/:id/reset-password',
118 asyncMiddleware(usersResetPasswordValidator),
119 asyncMiddleware(resetUserPassword)
122 usersRouter.post('/ask-send-verify-email',
124 asyncMiddleware(usersAskSendVerifyEmailValidator),
125 asyncMiddleware(askSendVerifyUserEmail)
128 usersRouter.post('/:id/verify-email',
129 asyncMiddleware(usersVerifyEmailValidator),
130 asyncMiddleware(verifyUserEmail)
133 usersRouter.post('/token',
138 // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
140 // ---------------------------------------------------------------------------
146 // ---------------------------------------------------------------------------
148 async function createUser (req: express.Request, res: express.Response) {
149 const body: UserCreate = req.body
150 const userToCreate = new UserModel({
151 username: body.username,
152 password: body.password,
154 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
157 videoQuota: body.videoQuota,
158 videoQuotaDaily: body.videoQuotaDaily
161 const { user, account } = await createUserAccountAndChannel(userToCreate)
163 auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new UserAuditView(user.toFormattedJSON()))
164 logger.info('User %s with its channel and account created.', body.username)
171 uuid: account.Actor.uuid
177 async function registerUser (req: express.Request, res: express.Response) {
178 const body: UserCreate = req.body
180 const userToCreate = new UserModel({
181 username: body.username,
182 password: body.password,
184 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
187 videoQuota: CONFIG.USER.VIDEO_QUOTA,
188 videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY,
189 emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null
192 const { user } = await createUserAccountAndChannel(userToCreate)
194 auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON()))
195 logger.info('User %s with its channel and account registered.', body.username)
197 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) {
198 await sendVerifyUserEmail(user)
201 return res.type('json').status(204).end()
204 async function unblockUser (req: express.Request, res: express.Response, next: express.NextFunction) {
205 const user: UserModel = res.locals.user
207 await changeUserBlock(res, user, false)
209 return res.status(204).end()
212 async function blockUser (req: express.Request, res: express.Response, next: express.NextFunction) {
213 const user: UserModel = res.locals.user
214 const reason = req.body.reason
216 await changeUserBlock(res, user, true, reason)
218 return res.status(204).end()
221 function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
222 return res.json((res.locals.user as UserModel).toFormattedJSON())
225 async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
226 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort)
228 return res.json(getFormattedObjects(resultList.data, resultList.total))
231 async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
232 const user: UserModel = res.locals.user
236 auditLogger.delete(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new UserAuditView(user.toFormattedJSON()))
238 return res.sendStatus(204)
241 async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) {
242 const body: UserUpdate = req.body
243 const userToUpdate = res.locals.user as UserModel
244 const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON())
245 const roleChanged = body.role !== undefined && body.role !== userToUpdate.role
247 if (body.email !== undefined) userToUpdate.email = body.email
248 if (body.videoQuota !== undefined) userToUpdate.videoQuota = body.videoQuota
249 if (body.videoQuotaDaily !== undefined) userToUpdate.videoQuotaDaily = body.videoQuotaDaily
250 if (body.role !== undefined) userToUpdate.role = body.role
252 const user = await userToUpdate.save()
254 // Destroy user token to refresh rights
256 await OAuthTokenModel.deleteUserToken(userToUpdate.id)
260 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
261 new UserAuditView(user.toFormattedJSON()),
265 // Don't need to send this update to followers, these attributes are not propagated
267 return res.sendStatus(204)
270 async function askResetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
271 const user = res.locals.user as UserModel
273 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
274 const url = CONFIG.WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
275 await Emailer.Instance.addForgetPasswordEmailJob(user.email, url)
277 return res.status(204).end()
280 async function resetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
281 const user = res.locals.user as UserModel
282 user.password = req.body.password
286 return res.status(204).end()
289 async function sendVerifyUserEmail (user: UserModel) {
290 const verificationString = await Redis.Instance.setVerifyEmailVerificationString(user.id)
291 const url = CONFIG.WEBSERVER.URL + '/verify-account/email?userId=' + user.id + '&verificationString=' + verificationString
292 await Emailer.Instance.addVerifyEmailJob(user.email, url)
296 async function askSendVerifyUserEmail (req: express.Request, res: express.Response, next: express.NextFunction) {
297 const user = res.locals.user as UserModel
299 await sendVerifyUserEmail(user)
301 return res.status(204).end()
304 async function verifyUserEmail (req: express.Request, res: express.Response, next: express.NextFunction) {
305 const user = res.locals.user as UserModel
306 user.emailVerified = true
310 return res.status(204).end()
313 function success (req: express.Request, res: express.Response, next: express.NextFunction) {
317 async function changeUserBlock (res: express.Response, user: UserModel, block: boolean, reason?: string) {
318 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
321 user.blockedReason = reason || null
323 await sequelizeTypescript.transaction(async t => {
324 await OAuthTokenModel.deleteUserToken(user.id, t)
326 await user.save({ transaction: t })
329 await Emailer.Instance.addUserBlockJob(user, block, reason)
332 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
333 new UserAuditView(user.toFormattedJSON()),