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'
33 usersAskResetPasswordValidator,
34 usersResetPasswordValidator,
35 videoImportsSortValidator,
37 } from '../../middlewares/validators'
38 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
39 import { UserModel } from '../../models/account/user'
40 import { OAuthTokenModel } from '../../models/oauth/oauth-token'
41 import { VideoModel } from '../../models/video/video'
42 import { VideoSortField } from '../../../client/src/app/shared/video/sort-field.type'
43 import { createReqFiles } from '../../helpers/express-utils'
44 import { UserVideoQuota } from '../../../shared/models/users/user-video-quota.model'
45 import { updateAvatarValidator } from '../../middlewares/validators/avatar'
46 import { updateActorAvatarFile } from '../../lib/avatar'
47 import { auditLoggerFactory, UserAuditView } from '../../helpers/audit-logger'
48 import { VideoImportModel } from '../../models/video/video-import'
50 const auditLogger = auditLoggerFactory('users')
52 const reqAvatarFile = createReqFiles([ 'avatarfile' ], IMAGE_MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.AVATARS_DIR })
53 const loginRateLimiter = new RateLimit({
54 windowMs: RATES_LIMIT.LOGIN.WINDOW_MS,
55 max: RATES_LIMIT.LOGIN.MAX,
59 const usersRouter = express.Router()
61 usersRouter.get('/me',
63 asyncMiddleware(getUserInformation)
66 usersRouter.get('/me/video-quota-used',
68 asyncMiddleware(getUserVideoQuotaUsed)
71 usersRouter.get('/me/videos/imports',
74 videoImportsSortValidator,
77 asyncMiddleware(getUserVideoImports)
80 usersRouter.get('/me/videos',
86 asyncMiddleware(getUserVideos)
89 usersRouter.get('/me/videos/:videoId/rating',
91 asyncMiddleware(usersVideoRatingValidator),
92 asyncMiddleware(getUserVideoRating)
97 ensureUserHasRight(UserRight.MANAGE_USERS),
101 setDefaultPagination,
102 asyncMiddleware(listUsers)
105 usersRouter.get('/:id',
107 ensureUserHasRight(UserRight.MANAGE_USERS),
108 asyncMiddleware(usersGetValidator),
112 usersRouter.post('/',
114 ensureUserHasRight(UserRight.MANAGE_USERS),
115 asyncMiddleware(usersAddValidator),
116 asyncRetryTransactionMiddleware(createUser)
119 usersRouter.post('/register',
120 asyncMiddleware(ensureUserRegistrationAllowed),
121 ensureUserRegistrationAllowedForIP,
122 asyncMiddleware(usersRegisterValidator),
123 asyncRetryTransactionMiddleware(registerUser)
126 usersRouter.put('/me',
128 usersUpdateMeValidator,
129 asyncMiddleware(updateMe)
132 usersRouter.post('/me/avatar/pick',
135 updateAvatarValidator,
136 asyncMiddleware(updateMyAvatar)
139 usersRouter.put('/:id',
141 ensureUserHasRight(UserRight.MANAGE_USERS),
142 asyncMiddleware(usersUpdateValidator),
143 asyncMiddleware(updateUser)
146 usersRouter.delete('/:id',
148 ensureUserHasRight(UserRight.MANAGE_USERS),
149 asyncMiddleware(usersRemoveValidator),
150 asyncMiddleware(removeUser)
153 usersRouter.post('/ask-reset-password',
154 asyncMiddleware(usersAskResetPasswordValidator),
155 asyncMiddleware(askResetUserPassword)
158 usersRouter.post('/:id/reset-password',
159 asyncMiddleware(usersResetPasswordValidator),
160 asyncMiddleware(resetUserPassword)
163 usersRouter.post('/token',
168 // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
170 // ---------------------------------------------------------------------------
176 // ---------------------------------------------------------------------------
178 async function getUserVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
179 const user = res.locals.oauth.token.User as UserModel
180 const resultList = await VideoModel.listUserVideosForApi(
182 req.query.start as number,
183 req.query.count as number,
184 req.query.sort as VideoSortField,
185 false // Display my NSFW videos
188 const additionalAttributes = {
189 waitTranscoding: true,
191 scheduledUpdate: true
193 return res.json(getFormattedObjects(resultList.data, resultList.total, { additionalAttributes }))
196 async function getUserVideoImports (req: express.Request, res: express.Response, next: express.NextFunction) {
197 const user = res.locals.oauth.token.User as UserModel
198 const resultList = await VideoImportModel.listUserVideoImportsForApi(
200 req.query.start as number,
201 req.query.count as number,
205 return res.json(getFormattedObjects(resultList.data, resultList.total))
208 async function createUser (req: express.Request, res: express.Response) {
209 const body: UserCreate = req.body
210 const userToCreate = new UserModel({
211 username: body.username,
212 password: body.password,
214 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
217 videoQuota: body.videoQuota
220 const { user, account } = await createUserAccountAndChannel(userToCreate)
222 auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new UserAuditView(user.toFormattedJSON()))
223 logger.info('User %s with its channel and account created.', body.username)
230 uuid: account.Actor.uuid
236 async function registerUser (req: express.Request, res: express.Response) {
237 const body: UserCreate = req.body
239 const userToCreate = new UserModel({
240 username: body.username,
241 password: body.password,
243 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
246 videoQuota: CONFIG.USER.VIDEO_QUOTA
249 const { user } = await createUserAccountAndChannel(userToCreate)
251 auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON()))
252 logger.info('User %s with its channel and account registered.', body.username)
254 return res.type('json').status(204).end()
257 async function getUserInformation (req: express.Request, res: express.Response, next: express.NextFunction) {
258 // We did not load channels in res.locals.user
259 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
261 return res.json(user.toFormattedJSON())
264 async function getUserVideoQuotaUsed (req: express.Request, res: express.Response, next: express.NextFunction) {
265 // We did not load channels in res.locals.user
266 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
267 const videoQuotaUsed = await UserModel.getOriginalVideoFileTotalFromUser(user)
269 const data: UserVideoQuota = {
272 return res.json(data)
275 function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
276 return res.json((res.locals.user as UserModel).toFormattedJSON())
279 async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) {
280 const videoId = +req.params.videoId
281 const accountId = +res.locals.oauth.token.User.Account.id
283 const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null)
284 const rating = ratingObj ? ratingObj.type : 'none'
286 const json: FormattedUserVideoRate = {
293 async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
294 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort)
296 return res.json(getFormattedObjects(resultList.data, resultList.total))
299 async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
300 const user = await UserModel.loadById(req.params.id)
304 auditLogger.delete(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new UserAuditView(user.toFormattedJSON()))
306 return res.sendStatus(204)
309 async function updateMe (req: express.Request, res: express.Response, next: express.NextFunction) {
310 const body: UserUpdateMe = req.body
312 const user: UserModel = res.locals.oauth.token.user
313 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
315 if (body.password !== undefined) user.password = body.password
316 if (body.email !== undefined) user.email = body.email
317 if (body.nsfwPolicy !== undefined) user.nsfwPolicy = body.nsfwPolicy
318 if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo
320 await sequelizeTypescript.transaction(async t => {
321 await user.save({ transaction: t })
323 if (body.displayName !== undefined) user.Account.name = body.displayName
324 if (body.description !== undefined) user.Account.description = body.description
325 await user.Account.save({ transaction: t })
327 await sendUpdateActor(user.Account, t)
330 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
331 new UserAuditView(user.toFormattedJSON()),
336 return res.sendStatus(204)
339 async function updateMyAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
340 const avatarPhysicalFile = req.files[ 'avatarfile' ][ 0 ]
341 const user: UserModel = res.locals.oauth.token.user
342 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
343 const account = user.Account
345 const avatar = await updateActorAvatarFile(avatarPhysicalFile, account.Actor, account)
348 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
349 new UserAuditView(user.toFormattedJSON()),
355 avatar: avatar.toFormattedJSON()
360 async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) {
361 const body: UserUpdate = req.body
362 const userToUpdate = res.locals.user as UserModel
363 const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON())
364 const roleChanged = body.role !== undefined && body.role !== userToUpdate.role
366 if (body.email !== undefined) userToUpdate.email = body.email
367 if (body.videoQuota !== undefined) userToUpdate.videoQuota = body.videoQuota
368 if (body.role !== undefined) userToUpdate.role = body.role
370 const user = await userToUpdate.save()
372 // Destroy user token to refresh rights
374 await OAuthTokenModel.deleteUserToken(userToUpdate.id)
378 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
379 new UserAuditView(user.toFormattedJSON()),
383 // Don't need to send this update to followers, these attributes are not propagated
385 return res.sendStatus(204)
388 async function askResetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
389 const user = res.locals.user as UserModel
391 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
392 const url = CONFIG.WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
393 await Emailer.Instance.addForgetPasswordEmailJob(user.email, url)
395 return res.status(204).end()
398 async function resetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
399 const user = res.locals.user as UserModel
400 user.password = req.body.password
404 return res.status(204).end()
407 function success (req: express.Request, res: express.Response, next: express.NextFunction) {