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'
28 import { usersAskResetPasswordValidator, usersBlockingValidator, usersResetPasswordValidator } from '../../../middlewares/validators'
29 import { UserModel } from '../../../models/account/user'
30 import { OAuthTokenModel } from '../../../models/oauth/oauth-token'
31 import { auditLoggerFactory, UserAuditView } from '../../../helpers/audit-logger'
32 import { videosRouter } from '../videos'
33 import { meRouter } from './me'
35 const auditLogger = auditLoggerFactory('users')
37 const loginRateLimiter = new RateLimit({
38 windowMs: RATES_LIMIT.LOGIN.WINDOW_MS,
39 max: RATES_LIMIT.LOGIN.MAX,
43 const usersRouter = express.Router()
44 videosRouter.use('/', meRouter)
48 ensureUserHasRight(UserRight.MANAGE_USERS),
53 asyncMiddleware(listUsers)
56 usersRouter.post('/:id/block',
58 ensureUserHasRight(UserRight.MANAGE_USERS),
59 asyncMiddleware(usersBlockingValidator),
60 asyncMiddleware(blockUser)
62 usersRouter.post('/:id/unblock',
64 ensureUserHasRight(UserRight.MANAGE_USERS),
65 asyncMiddleware(usersBlockingValidator),
66 asyncMiddleware(unblockUser)
69 usersRouter.get('/:id',
71 ensureUserHasRight(UserRight.MANAGE_USERS),
72 asyncMiddleware(usersGetValidator),
78 ensureUserHasRight(UserRight.MANAGE_USERS),
79 asyncMiddleware(usersAddValidator),
80 asyncRetryTransactionMiddleware(createUser)
83 usersRouter.post('/register',
84 asyncMiddleware(ensureUserRegistrationAllowed),
85 ensureUserRegistrationAllowedForIP,
86 asyncMiddleware(usersRegisterValidator),
87 asyncRetryTransactionMiddleware(registerUser)
90 usersRouter.put('/:id',
92 ensureUserHasRight(UserRight.MANAGE_USERS),
93 asyncMiddleware(usersUpdateValidator),
94 asyncMiddleware(updateUser)
97 usersRouter.delete('/:id',
99 ensureUserHasRight(UserRight.MANAGE_USERS),
100 asyncMiddleware(usersRemoveValidator),
101 asyncMiddleware(removeUser)
104 usersRouter.post('/ask-reset-password',
105 asyncMiddleware(usersAskResetPasswordValidator),
106 asyncMiddleware(askResetUserPassword)
109 usersRouter.post('/:id/reset-password',
110 asyncMiddleware(usersResetPasswordValidator),
111 asyncMiddleware(resetUserPassword)
114 usersRouter.post('/token',
119 // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
121 // ---------------------------------------------------------------------------
127 // ---------------------------------------------------------------------------
129 async function createUser (req: express.Request, res: express.Response) {
130 const body: UserCreate = req.body
131 const userToCreate = new UserModel({
132 username: body.username,
133 password: body.password,
135 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
138 videoQuota: body.videoQuota
141 const { user, account } = await createUserAccountAndChannel(userToCreate)
143 auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new UserAuditView(user.toFormattedJSON()))
144 logger.info('User %s with its channel and account created.', body.username)
151 uuid: account.Actor.uuid
157 async function registerUser (req: express.Request, res: express.Response) {
158 const body: UserCreate = req.body
160 const userToCreate = new UserModel({
161 username: body.username,
162 password: body.password,
164 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
167 videoQuota: CONFIG.USER.VIDEO_QUOTA
170 const { user } = await createUserAccountAndChannel(userToCreate)
172 auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON()))
173 logger.info('User %s with its channel and account registered.', body.username)
175 return res.type('json').status(204).end()
178 async function unblockUser (req: express.Request, res: express.Response, next: express.NextFunction) {
179 const user: UserModel = res.locals.user
181 await changeUserBlock(res, user, false)
183 return res.status(204).end()
186 async function blockUser (req: express.Request, res: express.Response, next: express.NextFunction) {
187 const user: UserModel = res.locals.user
188 const reason = req.body.reason
190 await changeUserBlock(res, user, true, reason)
192 return res.status(204).end()
195 function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
196 return res.json((res.locals.user as UserModel).toFormattedJSON())
199 async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
200 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort)
202 return res.json(getFormattedObjects(resultList.data, resultList.total))
205 async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
206 const user: UserModel = res.locals.user
210 auditLogger.delete(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new UserAuditView(user.toFormattedJSON()))
212 return res.sendStatus(204)
215 async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) {
216 const body: UserUpdate = req.body
217 const userToUpdate = res.locals.user as UserModel
218 const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON())
219 const roleChanged = body.role !== undefined && body.role !== userToUpdate.role
221 if (body.email !== undefined) userToUpdate.email = body.email
222 if (body.videoQuota !== undefined) userToUpdate.videoQuota = body.videoQuota
223 if (body.role !== undefined) userToUpdate.role = body.role
225 const user = await userToUpdate.save()
227 // Destroy user token to refresh rights
229 await OAuthTokenModel.deleteUserToken(userToUpdate.id)
233 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
234 new UserAuditView(user.toFormattedJSON()),
238 // Don't need to send this update to followers, these attributes are not propagated
240 return res.sendStatus(204)
243 async function askResetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
244 const user = res.locals.user as UserModel
246 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
247 const url = CONFIG.WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
248 await Emailer.Instance.addForgetPasswordEmailJob(user.email, url)
250 return res.status(204).end()
253 async function resetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
254 const user = res.locals.user as UserModel
255 user.password = req.body.password
259 return res.status(204).end()
262 function success (req: express.Request, res: express.Response, next: express.NextFunction) {
266 async function changeUserBlock (res: express.Response, user: UserModel, block: boolean, reason?: string) {
267 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
270 user.blockedReason = reason || null
272 await sequelizeTypescript.transaction(async t => {
273 await OAuthTokenModel.deleteUserToken(user.id, t)
275 await user.save({ transaction: t })
278 await Emailer.Instance.addUserBlockJob(user, block, reason)
281 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
282 new UserAuditView(user.toFormattedJSON()),