1 import * as express from 'express'
3 import { extname, join } from 'path'
4 import * as uuidv4 from 'uuid/v4'
5 import * as RateLimit from 'express-rate-limit'
6 import { UserCreate, UserRight, UserRole, UserUpdate, UserUpdateMe, UserVideoRate as FormattedUserVideoRate } from '../../../shared'
7 import { retryTransactionWrapper } from '../../helpers/database-utils'
8 import { processImage } from '../../helpers/image-utils'
9 import { logger } from '../../helpers/logger'
10 import { getFormattedObjects } from '../../helpers/utils'
11 import { AVATARS_SIZE, CONFIG, IMAGE_MIMETYPE_EXT, RATES_LIMIT, sequelizeTypescript } from '../../initializers'
12 import { updateActorAvatarInstance } from '../../lib/activitypub'
13 import { sendUpdateActor } from '../../lib/activitypub/send'
14 import { Emailer } from '../../lib/emailer'
15 import { Redis } from '../../lib/redis'
16 import { createUserAccountAndChannel } from '../../lib/user'
21 ensureUserRegistrationAllowed,
28 usersRegisterValidator,
31 usersUpdateMeValidator,
33 usersVideoRatingValidator
34 } from '../../middlewares'
36 usersAskResetPasswordValidator,
37 usersResetPasswordValidator,
38 usersUpdateMyAvatarValidator,
40 } from '../../middlewares/validators'
41 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
42 import { UserModel } from '../../models/account/user'
43 import { OAuthTokenModel } from '../../models/oauth/oauth-token'
44 import { VideoModel } from '../../models/video/video'
45 import { VideoSortField } from '../../../client/src/app/shared/video/sort-field.type'
46 import { createReqFiles } from '../../helpers/express-utils'
48 const reqAvatarFile = createReqFiles([ 'avatarfile' ], IMAGE_MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.AVATARS_DIR })
49 const loginRateLimiter = new RateLimit({
50 windowMs: RATES_LIMIT.LOGIN.WINDOW_MS,
51 max: RATES_LIMIT.LOGIN.MAX,
55 const usersRouter = express.Router()
57 usersRouter.get('/me',
59 asyncMiddleware(getUserInformation)
62 usersRouter.get('/me/video-quota-used',
64 asyncMiddleware(getUserVideoQuotaUsed)
67 usersRouter.get('/me/videos',
73 asyncMiddleware(getUserVideos)
76 usersRouter.get('/me/videos/:videoId/rating',
78 asyncMiddleware(usersVideoRatingValidator),
79 asyncMiddleware(getUserVideoRating)
84 ensureUserHasRight(UserRight.MANAGE_USERS),
89 asyncMiddleware(listUsers)
92 usersRouter.get('/:id',
94 ensureUserHasRight(UserRight.MANAGE_USERS),
95 asyncMiddleware(usersGetValidator),
101 ensureUserHasRight(UserRight.MANAGE_USERS),
102 asyncMiddleware(usersAddValidator),
103 asyncMiddleware(createUserRetryWrapper)
106 usersRouter.post('/register',
107 asyncMiddleware(ensureUserRegistrationAllowed),
108 asyncMiddleware(usersRegisterValidator),
109 asyncMiddleware(registerUserRetryWrapper)
112 usersRouter.put('/me',
114 usersUpdateMeValidator,
115 asyncMiddleware(updateMe)
118 usersRouter.post('/me/avatar/pick',
121 usersUpdateMyAvatarValidator,
122 asyncMiddleware(updateMyAvatar)
125 usersRouter.put('/:id',
127 ensureUserHasRight(UserRight.MANAGE_USERS),
128 asyncMiddleware(usersUpdateValidator),
129 asyncMiddleware(updateUser)
132 usersRouter.delete('/:id',
134 ensureUserHasRight(UserRight.MANAGE_USERS),
135 asyncMiddleware(usersRemoveValidator),
136 asyncMiddleware(removeUser)
139 usersRouter.post('/ask-reset-password',
140 asyncMiddleware(usersAskResetPasswordValidator),
141 asyncMiddleware(askResetUserPassword)
144 usersRouter.post('/:id/reset-password',
145 asyncMiddleware(usersResetPasswordValidator),
146 asyncMiddleware(resetUserPassword)
149 usersRouter.post('/token',
154 // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
156 // ---------------------------------------------------------------------------
162 // ---------------------------------------------------------------------------
164 async function getUserVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
165 const user = res.locals.oauth.token.User as UserModel
166 const resultList = await VideoModel.listAccountVideosForApi(
168 req.query.start as number,
169 req.query.count as number,
170 req.query.sort as VideoSortField,
171 false // Display my NSFW videos
174 return res.json(getFormattedObjects(resultList.data, resultList.total))
177 async function createUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
180 errorMessage: 'Cannot insert the user with many retries.'
183 const { user, account } = await retryTransactionWrapper(createUser, options)
190 uuid: account.Actor.uuid
196 async function createUser (req: express.Request) {
197 const body: UserCreate = req.body
198 const userToCreate = new UserModel({
199 username: body.username,
200 password: body.password,
202 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
205 videoQuota: body.videoQuota
208 const { user, account } = await createUserAccountAndChannel(userToCreate)
210 logger.info('User %s with its channel and account created.', body.username)
212 return { user, account }
215 async function registerUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
218 errorMessage: 'Cannot insert the user with many retries.'
221 await retryTransactionWrapper(registerUser, options)
223 return res.type('json').status(204).end()
226 async function registerUser (req: express.Request) {
227 const body: UserCreate = req.body
229 const user = new UserModel({
230 username: body.username,
231 password: body.password,
233 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
236 videoQuota: CONFIG.USER.VIDEO_QUOTA
239 await createUserAccountAndChannel(user)
241 logger.info('User %s with its channel and account registered.', body.username)
244 async function getUserInformation (req: express.Request, res: express.Response, next: express.NextFunction) {
245 // We did not load channels in res.locals.user
246 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
248 return res.json(user.toFormattedJSON())
251 async function getUserVideoQuotaUsed (req: express.Request, res: express.Response, next: express.NextFunction) {
252 // We did not load channels in res.locals.user
253 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
254 const videoQuotaUsed = await UserModel.getOriginalVideoFileTotalFromUser(user)
261 function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
262 return res.json((res.locals.user as UserModel).toFormattedJSON())
265 async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) {
266 const videoId = +req.params.videoId
267 const accountId = +res.locals.oauth.token.User.Account.id
269 const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null)
270 const rating = ratingObj ? ratingObj.type : 'none'
272 const json: FormattedUserVideoRate = {
279 async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
280 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort)
282 return res.json(getFormattedObjects(resultList.data, resultList.total))
285 async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
286 const user = await UserModel.loadById(req.params.id)
290 return res.sendStatus(204)
293 async function updateMe (req: express.Request, res: express.Response, next: express.NextFunction) {
294 const body: UserUpdateMe = req.body
296 const user: UserModel = res.locals.oauth.token.user
298 if (body.password !== undefined) user.password = body.password
299 if (body.email !== undefined) user.email = body.email
300 if (body.nsfwPolicy !== undefined) user.nsfwPolicy = body.nsfwPolicy
301 if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo
303 await sequelizeTypescript.transaction(async t => {
304 await user.save({ transaction: t })
306 if (body.description !== undefined) user.Account.description = body.description
307 await user.Account.save({ transaction: t })
309 await sendUpdateActor(user.Account, t)
312 return res.sendStatus(204)
315 async function updateMyAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
316 const avatarPhysicalFile = req.files['avatarfile'][0]
317 const user = res.locals.oauth.token.user
318 const actor = user.Account.Actor
320 const extension = extname(avatarPhysicalFile.filename)
321 const avatarName = uuidv4() + extension
322 const destination = join(CONFIG.STORAGE.AVATARS_DIR, avatarName)
323 await processImage(avatarPhysicalFile, destination, AVATARS_SIZE)
325 const avatar = await sequelizeTypescript.transaction(async t => {
326 const updatedActor = await updateActorAvatarInstance(actor, avatarName, t)
327 await updatedActor.save({ transaction: t })
329 await sendUpdateActor(user.Account, t)
331 return updatedActor.Avatar
336 avatar: avatar.toFormattedJSON()
341 async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) {
342 const body: UserUpdate = req.body
343 const user = res.locals.user as UserModel
344 const roleChanged = body.role !== undefined && body.role !== user.role
346 if (body.email !== undefined) user.email = body.email
347 if (body.videoQuota !== undefined) user.videoQuota = body.videoQuota
348 if (body.role !== undefined) user.role = body.role
352 // Destroy user token to refresh rights
354 await OAuthTokenModel.deleteUserToken(user.id)
357 // Don't need to send this update to followers, these attributes are not propagated
359 return res.sendStatus(204)
362 async function askResetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
363 const user = res.locals.user as UserModel
365 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
366 const url = CONFIG.WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
367 await Emailer.Instance.addForgetPasswordEmailJob(user.email, url)
369 return res.status(204).end()
372 async function resetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
373 const user = res.locals.user as UserModel
374 user.password = req.body.password
378 return res.status(204).end()
381 function success (req: express.Request, res: express.Response, next: express.NextFunction) {