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'
47 import { UserVideoQuota } from '../../../shared/models/users/user-video-quota.model'
49 const reqAvatarFile = createReqFiles([ 'avatarfile' ], IMAGE_MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.AVATARS_DIR })
50 const loginRateLimiter = new RateLimit({
51 windowMs: RATES_LIMIT.LOGIN.WINDOW_MS,
52 max: RATES_LIMIT.LOGIN.MAX,
56 const usersRouter = express.Router()
58 usersRouter.get('/me',
60 asyncMiddleware(getUserInformation)
63 usersRouter.get('/me/video-quota-used',
65 asyncMiddleware(getUserVideoQuotaUsed)
68 usersRouter.get('/me/videos',
74 asyncMiddleware(getUserVideos)
77 usersRouter.get('/me/videos/:videoId/rating',
79 asyncMiddleware(usersVideoRatingValidator),
80 asyncMiddleware(getUserVideoRating)
85 ensureUserHasRight(UserRight.MANAGE_USERS),
90 asyncMiddleware(listUsers)
93 usersRouter.get('/:id',
95 ensureUserHasRight(UserRight.MANAGE_USERS),
96 asyncMiddleware(usersGetValidator),
100 usersRouter.post('/',
102 ensureUserHasRight(UserRight.MANAGE_USERS),
103 asyncMiddleware(usersAddValidator),
104 asyncMiddleware(createUserRetryWrapper)
107 usersRouter.post('/register',
108 asyncMiddleware(ensureUserRegistrationAllowed),
109 asyncMiddleware(usersRegisterValidator),
110 asyncMiddleware(registerUserRetryWrapper)
113 usersRouter.put('/me',
115 usersUpdateMeValidator,
116 asyncMiddleware(updateMe)
119 usersRouter.post('/me/avatar/pick',
122 usersUpdateMyAvatarValidator,
123 asyncMiddleware(updateMyAvatar)
126 usersRouter.put('/:id',
128 ensureUserHasRight(UserRight.MANAGE_USERS),
129 asyncMiddleware(usersUpdateValidator),
130 asyncMiddleware(updateUser)
133 usersRouter.delete('/:id',
135 ensureUserHasRight(UserRight.MANAGE_USERS),
136 asyncMiddleware(usersRemoveValidator),
137 asyncMiddleware(removeUser)
140 usersRouter.post('/ask-reset-password',
141 asyncMiddleware(usersAskResetPasswordValidator),
142 asyncMiddleware(askResetUserPassword)
145 usersRouter.post('/:id/reset-password',
146 asyncMiddleware(usersResetPasswordValidator),
147 asyncMiddleware(resetUserPassword)
150 usersRouter.post('/token',
155 // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
157 // ---------------------------------------------------------------------------
163 // ---------------------------------------------------------------------------
165 async function getUserVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
166 const user = res.locals.oauth.token.User as UserModel
167 const resultList = await VideoModel.listAccountVideosForApi(
169 req.query.start as number,
170 req.query.count as number,
171 req.query.sort as VideoSortField,
172 false // Display my NSFW videos
175 return res.json(getFormattedObjects(resultList.data, resultList.total))
178 async function createUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
181 errorMessage: 'Cannot insert the user with many retries.'
184 const { user, account } = await retryTransactionWrapper(createUser, options)
191 uuid: account.Actor.uuid
197 async function createUser (req: express.Request) {
198 const body: UserCreate = req.body
199 const userToCreate = new UserModel({
200 username: body.username,
201 password: body.password,
203 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
206 videoQuota: body.videoQuota
209 const { user, account } = await createUserAccountAndChannel(userToCreate)
211 logger.info('User %s with its channel and account created.', body.username)
213 return { user, account }
216 async function registerUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
219 errorMessage: 'Cannot insert the user with many retries.'
222 await retryTransactionWrapper(registerUser, options)
224 return res.type('json').status(204).end()
227 async function registerUser (req: express.Request) {
228 const body: UserCreate = req.body
230 const user = new UserModel({
231 username: body.username,
232 password: body.password,
234 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
237 videoQuota: CONFIG.USER.VIDEO_QUOTA
240 await createUserAccountAndChannel(user)
242 logger.info('User %s with its channel and account registered.', body.username)
245 async function getUserInformation (req: express.Request, res: express.Response, next: express.NextFunction) {
246 // We did not load channels in res.locals.user
247 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
249 return res.json(user.toFormattedJSON())
252 async function getUserVideoQuotaUsed (req: express.Request, res: express.Response, next: express.NextFunction) {
253 // We did not load channels in res.locals.user
254 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
255 const videoQuotaUsed = await UserModel.getOriginalVideoFileTotalFromUser(user)
257 const data: UserVideoQuota = {
260 return res.json(data)
263 function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
264 return res.json((res.locals.user as UserModel).toFormattedJSON())
267 async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) {
268 const videoId = +req.params.videoId
269 const accountId = +res.locals.oauth.token.User.Account.id
271 const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null)
272 const rating = ratingObj ? ratingObj.type : 'none'
274 const json: FormattedUserVideoRate = {
281 async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
282 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort)
284 return res.json(getFormattedObjects(resultList.data, resultList.total))
287 async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
288 const user = await UserModel.loadById(req.params.id)
292 return res.sendStatus(204)
295 async function updateMe (req: express.Request, res: express.Response, next: express.NextFunction) {
296 const body: UserUpdateMe = req.body
298 const user: UserModel = res.locals.oauth.token.user
300 if (body.password !== undefined) user.password = body.password
301 if (body.email !== undefined) user.email = body.email
302 if (body.nsfwPolicy !== undefined) user.nsfwPolicy = body.nsfwPolicy
303 if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo
305 await sequelizeTypescript.transaction(async t => {
306 await user.save({ transaction: t })
308 if (body.displayName !== undefined) user.Account.name = body.displayName
309 if (body.description !== undefined) user.Account.description = body.description
310 await user.Account.save({ transaction: t })
312 await sendUpdateActor(user.Account, t)
315 return res.sendStatus(204)
318 async function updateMyAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
319 const avatarPhysicalFile = req.files['avatarfile'][0]
320 const user = res.locals.oauth.token.user
321 const actor = user.Account.Actor
323 const extension = extname(avatarPhysicalFile.filename)
324 const avatarName = uuidv4() + extension
325 const destination = join(CONFIG.STORAGE.AVATARS_DIR, avatarName)
326 await processImage(avatarPhysicalFile, destination, AVATARS_SIZE)
328 const avatar = await sequelizeTypescript.transaction(async t => {
329 const updatedActor = await updateActorAvatarInstance(actor, avatarName, t)
330 await updatedActor.save({ transaction: t })
332 await sendUpdateActor(user.Account, t)
334 return updatedActor.Avatar
339 avatar: avatar.toFormattedJSON()
344 async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) {
345 const body: UserUpdate = req.body
346 const user = res.locals.user as UserModel
347 const roleChanged = body.role !== undefined && body.role !== user.role
349 if (body.email !== undefined) user.email = body.email
350 if (body.videoQuota !== undefined) user.videoQuota = body.videoQuota
351 if (body.role !== undefined) user.role = body.role
355 // Destroy user token to refresh rights
357 await OAuthTokenModel.deleteUserToken(user.id)
360 // Don't need to send this update to followers, these attributes are not propagated
362 return res.sendStatus(204)
365 async function askResetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
366 const user = res.locals.user as UserModel
368 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
369 const url = CONFIG.WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
370 await Emailer.Instance.addForgetPasswordEmailJob(user.email, url)
372 return res.status(204).end()
375 async function resetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
376 const user = res.locals.user as UserModel
377 user.password = req.body.password
381 return res.status(204).end()
384 function success (req: express.Request, res: express.Response, next: express.NextFunction) {