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)
72 usersRouter.get('/me/videos/imports',
75 videoImportsSortValidator,
78 asyncMiddleware(getUserVideoImports)
81 usersRouter.get('/me/videos',
87 asyncMiddleware(getUserVideos)
90 usersRouter.get('/me/videos/:videoId/rating',
92 asyncMiddleware(usersVideoRatingValidator),
93 asyncMiddleware(getUserVideoRating)
98 ensureUserHasRight(UserRight.MANAGE_USERS),
102 setDefaultPagination,
103 asyncMiddleware(listUsers)
106 usersRouter.get('/:id',
108 ensureUserHasRight(UserRight.MANAGE_USERS),
109 asyncMiddleware(usersGetValidator),
113 usersRouter.post('/',
115 ensureUserHasRight(UserRight.MANAGE_USERS),
116 asyncMiddleware(usersAddValidator),
117 asyncRetryTransactionMiddleware(createUser)
120 usersRouter.post('/register',
121 asyncMiddleware(ensureUserRegistrationAllowed),
122 ensureUserRegistrationAllowedForIP,
123 asyncMiddleware(usersRegisterValidator),
124 asyncRetryTransactionMiddleware(registerUser)
127 usersRouter.put('/me',
129 usersUpdateMeValidator,
130 asyncMiddleware(updateMe)
133 usersRouter.post('/me/avatar/pick',
136 updateAvatarValidator,
137 asyncMiddleware(updateMyAvatar)
140 usersRouter.put('/:id',
142 ensureUserHasRight(UserRight.MANAGE_USERS),
143 asyncMiddleware(usersUpdateValidator),
144 asyncMiddleware(updateUser)
147 usersRouter.delete('/:id',
149 ensureUserHasRight(UserRight.MANAGE_USERS),
150 asyncMiddleware(usersRemoveValidator),
151 asyncMiddleware(removeUser)
154 usersRouter.post('/ask-reset-password',
155 asyncMiddleware(usersAskResetPasswordValidator),
156 asyncMiddleware(askResetUserPassword)
159 usersRouter.post('/:id/reset-password',
160 asyncMiddleware(usersResetPasswordValidator),
161 asyncMiddleware(resetUserPassword)
164 usersRouter.post('/token',
169 // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
171 // ---------------------------------------------------------------------------
177 // ---------------------------------------------------------------------------
179 async function getUserVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
180 const user = res.locals.oauth.token.User as UserModel
181 const resultList = await VideoModel.listUserVideosForApi(
183 req.query.start as number,
184 req.query.count as number,
185 req.query.sort as VideoSortField,
186 false // Display my NSFW videos
189 const additionalAttributes = {
190 waitTranscoding: true,
192 scheduledUpdate: true
194 return res.json(getFormattedObjects(resultList.data, resultList.total, { additionalAttributes }))
197 async function getUserVideoImports (req: express.Request, res: express.Response, next: express.NextFunction) {
198 const user = res.locals.oauth.token.User as UserModel
199 const resultList = await VideoImportModel.listUserVideoImportsForApi(
201 req.query.start as number,
202 req.query.count as number,
206 return res.json(getFormattedObjects(resultList.data, resultList.total))
209 async function createUser (req: express.Request, res: express.Response) {
210 const body: UserCreate = req.body
211 const userToCreate = new UserModel({
212 username: body.username,
213 password: body.password,
215 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
218 videoQuota: body.videoQuota
221 const { user, account } = await createUserAccountAndChannel(userToCreate)
223 auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new UserAuditView(user.toFormattedJSON()))
224 logger.info('User %s with its channel and account created.', body.username)
231 uuid: account.Actor.uuid
237 async function registerUser (req: express.Request, res: express.Response) {
238 const body: UserCreate = req.body
240 const userToCreate = new UserModel({
241 username: body.username,
242 password: body.password,
244 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
247 videoQuota: CONFIG.USER.VIDEO_QUOTA
250 const { user } = await createUserAccountAndChannel(userToCreate)
252 auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON()))
253 logger.info('User %s with its channel and account registered.', body.username)
255 return res.type('json').status(204).end()
258 async function getUserInformation (req: express.Request, res: express.Response, next: express.NextFunction) {
259 // We did not load channels in res.locals.user
260 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
262 return res.json(user.toFormattedJSON())
265 async function getUserVideoQuotaUsed (req: express.Request, res: express.Response, next: express.NextFunction) {
266 // We did not load channels in res.locals.user
267 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
268 const videoQuotaUsed = await UserModel.getOriginalVideoFileTotalFromUser(user)
270 const data: UserVideoQuota = {
273 return res.json(data)
276 function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
277 return res.json((res.locals.user as UserModel).toFormattedJSON())
280 async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) {
281 const videoId = +req.params.videoId
282 const accountId = +res.locals.oauth.token.User.Account.id
284 const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null)
285 const rating = ratingObj ? ratingObj.type : 'none'
287 const json: FormattedUserVideoRate = {
294 async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
295 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort)
297 return res.json(getFormattedObjects(resultList.data, resultList.total))
300 async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
301 const user = await UserModel.loadById(req.params.id)
305 auditLogger.delete(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new UserAuditView(user.toFormattedJSON()))
307 return res.sendStatus(204)
310 async function updateMe (req: express.Request, res: express.Response, next: express.NextFunction) {
311 const body: UserUpdateMe = req.body
313 const user: UserModel = res.locals.oauth.token.user
314 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
316 if (body.password !== undefined) user.password = body.password
317 if (body.email !== undefined) user.email = body.email
318 if (body.nsfwPolicy !== undefined) user.nsfwPolicy = body.nsfwPolicy
319 if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo
321 await sequelizeTypescript.transaction(async t => {
322 await user.save({ transaction: t })
324 if (body.displayName !== undefined) user.Account.name = body.displayName
325 if (body.description !== undefined) user.Account.description = body.description
326 await user.Account.save({ transaction: t })
328 await sendUpdateActor(user.Account, t)
331 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
332 new UserAuditView(user.toFormattedJSON()),
337 return res.sendStatus(204)
340 async function updateMyAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
341 const avatarPhysicalFile = req.files[ 'avatarfile' ][ 0 ]
342 const user: UserModel = res.locals.oauth.token.user
343 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
344 const account = user.Account
346 const avatar = await updateActorAvatarFile(avatarPhysicalFile, account.Actor, account)
349 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
350 new UserAuditView(user.toFormattedJSON()),
356 avatar: avatar.toFormattedJSON()
361 async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) {
362 const body: UserUpdate = req.body
363 const userToUpdate = res.locals.user as UserModel
364 const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON())
365 const roleChanged = body.role !== undefined && body.role !== userToUpdate.role
367 if (body.email !== undefined) userToUpdate.email = body.email
368 if (body.videoQuota !== undefined) userToUpdate.videoQuota = body.videoQuota
369 if (body.role !== undefined) userToUpdate.role = body.role
371 const user = await userToUpdate.save()
373 // Destroy user token to refresh rights
375 await OAuthTokenModel.deleteUserToken(userToUpdate.id)
379 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
380 new UserAuditView(user.toFormattedJSON()),
384 // Don't need to send this update to followers, these attributes are not propagated
386 return res.sendStatus(204)
389 async function askResetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
390 const user = res.locals.user as UserModel
392 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
393 const url = CONFIG.WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
394 await Emailer.Instance.addForgetPasswordEmailJob(user.email, url)
396 return res.status(204).end()
399 async function resetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
400 const user = res.locals.user as UserModel
401 user.password = req.body.password
405 return res.status(204).end()
408 function success (req: express.Request, res: express.Response, next: express.NextFunction) {