1 import * as express from 'express'
3 import * as RateLimit from 'express-rate-limit'
4 import { UserCreate, UserRight, UserRole, UserUpdate, UserUpdateMe, UserVideoRate as FormattedUserVideoRate } from '../../../shared'
5 import { logger } from '../../helpers/logger'
6 import { getFormattedObjects } from '../../helpers/utils'
7 import { CONFIG, IMAGE_MIMETYPE_EXT, RATES_LIMIT, sequelizeTypescript } from '../../initializers'
8 import { sendUpdateActor } from '../../lib/activitypub/send'
9 import { Emailer } from '../../lib/emailer'
10 import { Redis } from '../../lib/redis'
11 import { createUserAccountAndChannel } from '../../lib/user'
14 asyncRetryTransactionMiddleware,
17 ensureUserRegistrationAllowed,
18 ensureUserRegistrationAllowedForIP,
25 usersRegisterValidator,
28 usersUpdateMeValidator,
30 usersVideoRatingValidator
31 } from '../../middlewares'
34 usersAskResetPasswordValidator,
35 usersBlockingValidator,
36 usersResetPasswordValidator,
37 videoImportsSortValidator,
39 } from '../../middlewares/validators'
40 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
41 import { UserModel } from '../../models/account/user'
42 import { OAuthTokenModel } from '../../models/oauth/oauth-token'
43 import { VideoModel } from '../../models/video/video'
44 import { VideoSortField } from '../../../client/src/app/shared/video/sort-field.type'
45 import { createReqFiles } from '../../helpers/express-utils'
46 import { UserVideoQuota } from '../../../shared/models/users/user-video-quota.model'
47 import { updateAvatarValidator } from '../../middlewares/validators/avatar'
48 import { updateActorAvatarFile } from '../../lib/avatar'
49 import { auditLoggerFactory, UserAuditView } from '../../helpers/audit-logger'
50 import { VideoImportModel } from '../../models/video/video-import'
52 const auditLogger = auditLoggerFactory('users')
54 const reqAvatarFile = createReqFiles([ 'avatarfile' ], IMAGE_MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.AVATARS_DIR })
55 const loginRateLimiter = new RateLimit({
56 windowMs: RATES_LIMIT.LOGIN.WINDOW_MS,
57 max: RATES_LIMIT.LOGIN.MAX,
61 const usersRouter = express.Router()
63 usersRouter.get('/me',
65 asyncMiddleware(getUserInformation)
67 usersRouter.delete('/me',
69 asyncMiddleware(deleteMeValidator),
70 asyncMiddleware(deleteMe)
73 usersRouter.get('/me/video-quota-used',
75 asyncMiddleware(getUserVideoQuotaUsed)
78 usersRouter.get('/me/videos/imports',
81 videoImportsSortValidator,
84 asyncMiddleware(getUserVideoImports)
87 usersRouter.get('/me/videos',
93 asyncMiddleware(getUserVideos)
96 usersRouter.get('/me/videos/:videoId/rating',
98 asyncMiddleware(usersVideoRatingValidator),
99 asyncMiddleware(getUserVideoRating)
104 ensureUserHasRight(UserRight.MANAGE_USERS),
108 setDefaultPagination,
109 asyncMiddleware(listUsers)
112 usersRouter.post('/:id/block',
114 ensureUserHasRight(UserRight.MANAGE_USERS),
115 asyncMiddleware(usersBlockingValidator),
116 asyncMiddleware(blockUser)
118 usersRouter.post('/:id/unblock',
120 ensureUserHasRight(UserRight.MANAGE_USERS),
121 asyncMiddleware(usersBlockingValidator),
122 asyncMiddleware(unblockUser)
125 usersRouter.get('/:id',
127 ensureUserHasRight(UserRight.MANAGE_USERS),
128 asyncMiddleware(usersGetValidator),
132 usersRouter.post('/',
134 ensureUserHasRight(UserRight.MANAGE_USERS),
135 asyncMiddleware(usersAddValidator),
136 asyncRetryTransactionMiddleware(createUser)
139 usersRouter.post('/register',
140 asyncMiddleware(ensureUserRegistrationAllowed),
141 ensureUserRegistrationAllowedForIP,
142 asyncMiddleware(usersRegisterValidator),
143 asyncRetryTransactionMiddleware(registerUser)
146 usersRouter.put('/me',
148 usersUpdateMeValidator,
149 asyncMiddleware(updateMe)
152 usersRouter.post('/me/avatar/pick',
155 updateAvatarValidator,
156 asyncMiddleware(updateMyAvatar)
159 usersRouter.put('/:id',
161 ensureUserHasRight(UserRight.MANAGE_USERS),
162 asyncMiddleware(usersUpdateValidator),
163 asyncMiddleware(updateUser)
166 usersRouter.delete('/:id',
168 ensureUserHasRight(UserRight.MANAGE_USERS),
169 asyncMiddleware(usersRemoveValidator),
170 asyncMiddleware(removeUser)
173 usersRouter.post('/ask-reset-password',
174 asyncMiddleware(usersAskResetPasswordValidator),
175 asyncMiddleware(askResetUserPassword)
178 usersRouter.post('/:id/reset-password',
179 asyncMiddleware(usersResetPasswordValidator),
180 asyncMiddleware(resetUserPassword)
183 usersRouter.post('/token',
188 // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
190 // ---------------------------------------------------------------------------
196 // ---------------------------------------------------------------------------
198 async function getUserVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
199 const user = res.locals.oauth.token.User as UserModel
200 const resultList = await VideoModel.listUserVideosForApi(
202 req.query.start as number,
203 req.query.count as number,
204 req.query.sort as VideoSortField
207 const additionalAttributes = {
208 waitTranscoding: true,
210 scheduledUpdate: true,
213 return res.json(getFormattedObjects(resultList.data, resultList.total, { additionalAttributes }))
216 async function getUserVideoImports (req: express.Request, res: express.Response, next: express.NextFunction) {
217 const user = res.locals.oauth.token.User as UserModel
218 const resultList = await VideoImportModel.listUserVideoImportsForApi(
220 req.query.start as number,
221 req.query.count as number,
225 return res.json(getFormattedObjects(resultList.data, resultList.total))
228 async function createUser (req: express.Request, res: express.Response) {
229 const body: UserCreate = req.body
230 const userToCreate = new UserModel({
231 username: body.username,
232 password: body.password,
234 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
237 videoQuota: body.videoQuota
240 const { user, account } = await createUserAccountAndChannel(userToCreate)
242 auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new UserAuditView(user.toFormattedJSON()))
243 logger.info('User %s with its channel and account created.', body.username)
250 uuid: account.Actor.uuid
256 async function registerUser (req: express.Request, res: express.Response) {
257 const body: UserCreate = req.body
259 const userToCreate = new UserModel({
260 username: body.username,
261 password: body.password,
263 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
266 videoQuota: CONFIG.USER.VIDEO_QUOTA
269 const { user } = await createUserAccountAndChannel(userToCreate)
271 auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON()))
272 logger.info('User %s with its channel and account registered.', body.username)
274 return res.type('json').status(204).end()
277 async function getUserInformation (req: express.Request, res: express.Response, next: express.NextFunction) {
278 // We did not load channels in res.locals.user
279 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
281 return res.json(user.toFormattedJSON())
284 async function getUserVideoQuotaUsed (req: express.Request, res: express.Response, next: express.NextFunction) {
285 // We did not load channels in res.locals.user
286 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
287 const videoQuotaUsed = await UserModel.getOriginalVideoFileTotalFromUser(user)
289 const data: UserVideoQuota = {
292 return res.json(data)
295 async function unblockUser (req: express.Request, res: express.Response, next: express.NextFunction) {
296 const user: UserModel = res.locals.user
298 await changeUserBlock(res, user, false)
300 return res.status(204).end()
303 async function blockUser (req: express.Request, res: express.Response, next: express.NextFunction) {
304 const user: UserModel = res.locals.user
305 const reason = req.body.reason
307 await changeUserBlock(res, user, true, reason)
309 return res.status(204).end()
312 function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
313 return res.json((res.locals.user as UserModel).toFormattedJSON())
316 async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) {
317 const videoId = +req.params.videoId
318 const accountId = +res.locals.oauth.token.User.Account.id
320 const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null)
321 const rating = ratingObj ? ratingObj.type : 'none'
323 const json: FormattedUserVideoRate = {
330 async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
331 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort)
333 return res.json(getFormattedObjects(resultList.data, resultList.total))
336 async function deleteMe (req: express.Request, res: express.Response) {
337 const user: UserModel = res.locals.oauth.token.User
341 auditLogger.delete(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new UserAuditView(user.toFormattedJSON()))
343 return res.sendStatus(204)
346 async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
347 const user: UserModel = res.locals.user
351 auditLogger.delete(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new UserAuditView(user.toFormattedJSON()))
353 return res.sendStatus(204)
356 async function updateMe (req: express.Request, res: express.Response, next: express.NextFunction) {
357 const body: UserUpdateMe = req.body
359 const user: UserModel = res.locals.oauth.token.user
360 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
362 if (body.password !== undefined) user.password = body.password
363 if (body.email !== undefined) user.email = body.email
364 if (body.nsfwPolicy !== undefined) user.nsfwPolicy = body.nsfwPolicy
365 if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo
367 await sequelizeTypescript.transaction(async t => {
368 await user.save({ transaction: t })
370 if (body.displayName !== undefined) user.Account.name = body.displayName
371 if (body.description !== undefined) user.Account.description = body.description
372 await user.Account.save({ transaction: t })
374 await sendUpdateActor(user.Account, t)
377 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
378 new UserAuditView(user.toFormattedJSON()),
383 return res.sendStatus(204)
386 async function updateMyAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
387 const avatarPhysicalFile = req.files[ 'avatarfile' ][ 0 ]
388 const user: UserModel = res.locals.oauth.token.user
389 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
390 const account = user.Account
392 const avatar = await updateActorAvatarFile(avatarPhysicalFile, account.Actor, account)
395 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
396 new UserAuditView(user.toFormattedJSON()),
402 avatar: avatar.toFormattedJSON()
407 async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) {
408 const body: UserUpdate = req.body
409 const userToUpdate = res.locals.user as UserModel
410 const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON())
411 const roleChanged = body.role !== undefined && body.role !== userToUpdate.role
413 if (body.email !== undefined) userToUpdate.email = body.email
414 if (body.videoQuota !== undefined) userToUpdate.videoQuota = body.videoQuota
415 if (body.role !== undefined) userToUpdate.role = body.role
417 const user = await userToUpdate.save()
419 // Destroy user token to refresh rights
421 await OAuthTokenModel.deleteUserToken(userToUpdate.id)
425 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
426 new UserAuditView(user.toFormattedJSON()),
430 // Don't need to send this update to followers, these attributes are not propagated
432 return res.sendStatus(204)
435 async function askResetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
436 const user = res.locals.user as UserModel
438 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
439 const url = CONFIG.WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
440 await Emailer.Instance.addForgetPasswordEmailJob(user.email, url)
442 return res.status(204).end()
445 async function resetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
446 const user = res.locals.user as UserModel
447 user.password = req.body.password
451 return res.status(204).end()
454 function success (req: express.Request, res: express.Response, next: express.NextFunction) {
458 async function changeUserBlock (res: express.Response, user: UserModel, block: boolean, reason?: string) {
459 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
462 user.blockedReason = reason || null
464 await sequelizeTypescript.transaction(async t => {
465 await OAuthTokenModel.deleteUserToken(user.id, t)
467 await user.save({ transaction: t })
470 await Emailer.Instance.addUserBlockJob(user, block, reason)
473 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
474 new UserAuditView(user.toFormattedJSON()),