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 { processImage } from '../../helpers/image-utils'
8 import { logger } from '../../helpers/logger'
9 import { getFormattedObjects } from '../../helpers/utils'
10 import { AVATARS_SIZE, CONFIG, IMAGE_MIMETYPE_EXT, RATES_LIMIT, sequelizeTypescript } from '../../initializers'
11 import { updateActorAvatarInstance } from '../../lib/activitypub'
12 import { sendUpdateActor } from '../../lib/activitypub/send'
13 import { Emailer } from '../../lib/emailer'
14 import { Redis } from '../../lib/redis'
15 import { createUserAccountAndChannel } from '../../lib/user'
18 asyncRetryTransactionMiddleware,
21 ensureUserRegistrationAllowed,
22 ensureUserRegistrationAllowedForIP,
29 usersRegisterValidator,
32 usersUpdateMeValidator,
34 usersVideoRatingValidator
35 } from '../../middlewares'
37 usersAskResetPasswordValidator,
38 usersResetPasswordValidator,
39 usersUpdateMyAvatarValidator,
41 } from '../../middlewares/validators'
42 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
43 import { UserModel } from '../../models/account/user'
44 import { OAuthTokenModel } from '../../models/oauth/oauth-token'
45 import { VideoModel } from '../../models/video/video'
46 import { VideoSortField } from '../../../client/src/app/shared/video/sort-field.type'
47 import { createReqFiles } from '../../helpers/express-utils'
48 import { UserVideoQuota } from '../../../shared/models/users/user-video-quota.model'
50 const reqAvatarFile = createReqFiles([ 'avatarfile' ], IMAGE_MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.AVATARS_DIR })
51 const loginRateLimiter = new RateLimit({
52 windowMs: RATES_LIMIT.LOGIN.WINDOW_MS,
53 max: RATES_LIMIT.LOGIN.MAX,
57 const usersRouter = express.Router()
59 usersRouter.get('/me',
61 asyncMiddleware(getUserInformation)
64 usersRouter.get('/me/video-quota-used',
66 asyncMiddleware(getUserVideoQuotaUsed)
69 usersRouter.get('/me/videos',
75 asyncMiddleware(getUserVideos)
78 usersRouter.get('/me/videos/:videoId/rating',
80 asyncMiddleware(usersVideoRatingValidator),
81 asyncMiddleware(getUserVideoRating)
86 ensureUserHasRight(UserRight.MANAGE_USERS),
91 asyncMiddleware(listUsers)
94 usersRouter.get('/:id',
96 ensureUserHasRight(UserRight.MANAGE_USERS),
97 asyncMiddleware(usersGetValidator),
101 usersRouter.post('/',
103 ensureUserHasRight(UserRight.MANAGE_USERS),
104 asyncMiddleware(usersAddValidator),
105 asyncRetryTransactionMiddleware(createUser)
108 usersRouter.post('/register',
109 asyncMiddleware(ensureUserRegistrationAllowed),
110 ensureUserRegistrationAllowedForIP,
111 asyncMiddleware(usersRegisterValidator),
112 asyncRetryTransactionMiddleware(registerUser)
115 usersRouter.put('/me',
117 usersUpdateMeValidator,
118 asyncMiddleware(updateMe)
121 usersRouter.post('/me/avatar/pick',
124 usersUpdateMyAvatarValidator,
125 asyncMiddleware(updateMyAvatar)
128 usersRouter.put('/:id',
130 ensureUserHasRight(UserRight.MANAGE_USERS),
131 asyncMiddleware(usersUpdateValidator),
132 asyncMiddleware(updateUser)
135 usersRouter.delete('/:id',
137 ensureUserHasRight(UserRight.MANAGE_USERS),
138 asyncMiddleware(usersRemoveValidator),
139 asyncMiddleware(removeUser)
142 usersRouter.post('/ask-reset-password',
143 asyncMiddleware(usersAskResetPasswordValidator),
144 asyncMiddleware(askResetUserPassword)
147 usersRouter.post('/:id/reset-password',
148 asyncMiddleware(usersResetPasswordValidator),
149 asyncMiddleware(resetUserPassword)
152 usersRouter.post('/token',
157 // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
159 // ---------------------------------------------------------------------------
165 // ---------------------------------------------------------------------------
167 async function getUserVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
168 const user = res.locals.oauth.token.User as UserModel
169 const resultList = await VideoModel.listUserVideosForApi(
171 req.query.start as number,
172 req.query.count as number,
173 req.query.sort as VideoSortField,
174 false // Display my NSFW videos
177 const additionalAttributes = {
178 waitTranscoding: true,
180 scheduledUpdate: true
182 return res.json(getFormattedObjects(resultList.data, resultList.total, { additionalAttributes }))
185 async function createUser (req: express.Request, res: express.Response) {
186 const body: UserCreate = req.body
187 const userToCreate = new UserModel({
188 username: body.username,
189 password: body.password,
191 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
194 videoQuota: body.videoQuota
197 const { user, account } = await createUserAccountAndChannel(userToCreate)
199 logger.info('User %s with its channel and account created.', body.username)
206 uuid: account.Actor.uuid
212 async function registerUser (req: express.Request, res: express.Response) {
213 const body: UserCreate = req.body
215 const user = new UserModel({
216 username: body.username,
217 password: body.password,
219 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
222 videoQuota: CONFIG.USER.VIDEO_QUOTA
225 await createUserAccountAndChannel(user)
227 logger.info('User %s with its channel and account registered.', body.username)
229 return res.type('json').status(204).end()
232 async function getUserInformation (req: express.Request, res: express.Response, next: express.NextFunction) {
233 // We did not load channels in res.locals.user
234 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
236 return res.json(user.toFormattedJSON())
239 async function getUserVideoQuotaUsed (req: express.Request, res: express.Response, next: express.NextFunction) {
240 // We did not load channels in res.locals.user
241 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
242 const videoQuotaUsed = await UserModel.getOriginalVideoFileTotalFromUser(user)
244 const data: UserVideoQuota = {
247 return res.json(data)
250 function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
251 return res.json((res.locals.user as UserModel).toFormattedJSON())
254 async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) {
255 const videoId = +req.params.videoId
256 const accountId = +res.locals.oauth.token.User.Account.id
258 const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null)
259 const rating = ratingObj ? ratingObj.type : 'none'
261 const json: FormattedUserVideoRate = {
268 async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
269 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort)
271 return res.json(getFormattedObjects(resultList.data, resultList.total))
274 async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
275 const user = await UserModel.loadById(req.params.id)
279 return res.sendStatus(204)
282 async function updateMe (req: express.Request, res: express.Response, next: express.NextFunction) {
283 const body: UserUpdateMe = req.body
285 const user: UserModel = res.locals.oauth.token.user
287 if (body.password !== undefined) user.password = body.password
288 if (body.email !== undefined) user.email = body.email
289 if (body.nsfwPolicy !== undefined) user.nsfwPolicy = body.nsfwPolicy
290 if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo
292 await sequelizeTypescript.transaction(async t => {
293 await user.save({ transaction: t })
295 if (body.displayName !== undefined) user.Account.name = body.displayName
296 if (body.description !== undefined) user.Account.description = body.description
297 await user.Account.save({ transaction: t })
299 await sendUpdateActor(user.Account, t)
302 return res.sendStatus(204)
305 async function updateMyAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
306 const avatarPhysicalFile = req.files[ 'avatarfile' ][ 0 ]
307 const user = res.locals.oauth.token.user
308 const actor = user.Account.Actor
310 const extension = extname(avatarPhysicalFile.filename)
311 const avatarName = uuidv4() + extension
312 const destination = join(CONFIG.STORAGE.AVATARS_DIR, avatarName)
313 await processImage(avatarPhysicalFile, destination, AVATARS_SIZE)
315 const avatar = await sequelizeTypescript.transaction(async t => {
316 const updatedActor = await updateActorAvatarInstance(actor, avatarName, t)
317 await updatedActor.save({ transaction: t })
319 await sendUpdateActor(user.Account, t)
321 return updatedActor.Avatar
326 avatar: avatar.toFormattedJSON()
331 async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) {
332 const body: UserUpdate = req.body
333 const user = res.locals.user as UserModel
334 const roleChanged = body.role !== undefined && body.role !== user.role
336 if (body.email !== undefined) user.email = body.email
337 if (body.videoQuota !== undefined) user.videoQuota = body.videoQuota
338 if (body.role !== undefined) user.role = body.role
342 // Destroy user token to refresh rights
344 await OAuthTokenModel.deleteUserToken(user.id)
347 // Don't need to send this update to followers, these attributes are not propagated
349 return res.sendStatus(204)
352 async function askResetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
353 const user = res.locals.user as UserModel
355 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
356 const url = CONFIG.WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
357 await Emailer.Instance.addForgetPasswordEmailJob(user.email, url)
359 return res.status(204).end()
362 async function resetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
363 const user = res.locals.user as UserModel
364 user.password = req.body.password
368 return res.status(204).end()
371 function success (req: express.Request, res: express.Response, next: express.NextFunction) {