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'
32 import { usersAskResetPasswordValidator, usersResetPasswordValidator, videosSortValidator } from '../../middlewares/validators'
33 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
34 import { UserModel } from '../../models/account/user'
35 import { OAuthTokenModel } from '../../models/oauth/oauth-token'
36 import { VideoModel } from '../../models/video/video'
37 import { VideoSortField } from '../../../client/src/app/shared/video/sort-field.type'
38 import { createReqFiles } from '../../helpers/express-utils'
39 import { UserVideoQuota } from '../../../shared/models/users/user-video-quota.model'
40 import { updateAvatarValidator } from '../../middlewares/validators/avatar'
41 import { updateActorAvatarFile } from '../../lib/avatar'
43 const reqAvatarFile = createReqFiles([ 'avatarfile' ], IMAGE_MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.AVATARS_DIR })
44 const loginRateLimiter = new RateLimit({
45 windowMs: RATES_LIMIT.LOGIN.WINDOW_MS,
46 max: RATES_LIMIT.LOGIN.MAX,
50 const usersRouter = express.Router()
52 usersRouter.get('/me',
54 asyncMiddleware(getUserInformation)
57 usersRouter.get('/me/video-quota-used',
59 asyncMiddleware(getUserVideoQuotaUsed)
62 usersRouter.get('/me/videos',
68 asyncMiddleware(getUserVideos)
71 usersRouter.get('/me/videos/:videoId/rating',
73 asyncMiddleware(usersVideoRatingValidator),
74 asyncMiddleware(getUserVideoRating)
79 ensureUserHasRight(UserRight.MANAGE_USERS),
84 asyncMiddleware(listUsers)
87 usersRouter.get('/:id',
89 ensureUserHasRight(UserRight.MANAGE_USERS),
90 asyncMiddleware(usersGetValidator),
96 ensureUserHasRight(UserRight.MANAGE_USERS),
97 asyncMiddleware(usersAddValidator),
98 asyncRetryTransactionMiddleware(createUser)
101 usersRouter.post('/register',
102 asyncMiddleware(ensureUserRegistrationAllowed),
103 ensureUserRegistrationAllowedForIP,
104 asyncMiddleware(usersRegisterValidator),
105 asyncRetryTransactionMiddleware(registerUser)
108 usersRouter.put('/me',
110 usersUpdateMeValidator,
111 asyncMiddleware(updateMe)
114 usersRouter.post('/me/avatar/pick',
117 updateAvatarValidator,
118 asyncMiddleware(updateMyAvatar)
121 usersRouter.put('/:id',
123 ensureUserHasRight(UserRight.MANAGE_USERS),
124 asyncMiddleware(usersUpdateValidator),
125 asyncMiddleware(updateUser)
128 usersRouter.delete('/:id',
130 ensureUserHasRight(UserRight.MANAGE_USERS),
131 asyncMiddleware(usersRemoveValidator),
132 asyncMiddleware(removeUser)
135 usersRouter.post('/ask-reset-password',
136 asyncMiddleware(usersAskResetPasswordValidator),
137 asyncMiddleware(askResetUserPassword)
140 usersRouter.post('/:id/reset-password',
141 asyncMiddleware(usersResetPasswordValidator),
142 asyncMiddleware(resetUserPassword)
145 usersRouter.post('/token',
150 // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
152 // ---------------------------------------------------------------------------
158 // ---------------------------------------------------------------------------
160 async function getUserVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
161 const user = res.locals.oauth.token.User as UserModel
162 const resultList = await VideoModel.listUserVideosForApi(
164 req.query.start as number,
165 req.query.count as number,
166 req.query.sort as VideoSortField,
167 false // Display my NSFW videos
170 const additionalAttributes = {
171 waitTranscoding: true,
173 scheduledUpdate: true
175 return res.json(getFormattedObjects(resultList.data, resultList.total, { additionalAttributes }))
178 async function createUser (req: express.Request, res: express.Response) {
179 const body: UserCreate = req.body
180 const userToCreate = new UserModel({
181 username: body.username,
182 password: body.password,
184 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
187 videoQuota: body.videoQuota
190 const { user, account } = await createUserAccountAndChannel(userToCreate)
192 logger.info('User %s with its channel and account created.', body.username)
199 uuid: account.Actor.uuid
205 async function registerUser (req: express.Request, res: express.Response) {
206 const body: UserCreate = req.body
208 const user = new UserModel({
209 username: body.username,
210 password: body.password,
212 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
215 videoQuota: CONFIG.USER.VIDEO_QUOTA
218 await createUserAccountAndChannel(user)
220 logger.info('User %s with its channel and account registered.', body.username)
222 return res.type('json').status(204).end()
225 async function getUserInformation (req: express.Request, res: express.Response, next: express.NextFunction) {
226 // We did not load channels in res.locals.user
227 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
229 return res.json(user.toFormattedJSON())
232 async function getUserVideoQuotaUsed (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)
235 const videoQuotaUsed = await UserModel.getOriginalVideoFileTotalFromUser(user)
237 const data: UserVideoQuota = {
240 return res.json(data)
243 function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
244 return res.json((res.locals.user as UserModel).toFormattedJSON())
247 async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) {
248 const videoId = +req.params.videoId
249 const accountId = +res.locals.oauth.token.User.Account.id
251 const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null)
252 const rating = ratingObj ? ratingObj.type : 'none'
254 const json: FormattedUserVideoRate = {
261 async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
262 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort)
264 return res.json(getFormattedObjects(resultList.data, resultList.total))
267 async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
268 const user = await UserModel.loadById(req.params.id)
272 return res.sendStatus(204)
275 async function updateMe (req: express.Request, res: express.Response, next: express.NextFunction) {
276 const body: UserUpdateMe = req.body
278 const user: UserModel = res.locals.oauth.token.user
280 if (body.password !== undefined) user.password = body.password
281 if (body.email !== undefined) user.email = body.email
282 if (body.nsfwPolicy !== undefined) user.nsfwPolicy = body.nsfwPolicy
283 if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo
285 await sequelizeTypescript.transaction(async t => {
286 await user.save({ transaction: t })
288 if (body.displayName !== undefined) user.Account.name = body.displayName
289 if (body.description !== undefined) user.Account.description = body.description
290 await user.Account.save({ transaction: t })
292 await sendUpdateActor(user.Account, t)
295 return res.sendStatus(204)
298 async function updateMyAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
299 const avatarPhysicalFile = req.files[ 'avatarfile' ][ 0 ]
300 const account = res.locals.oauth.token.user.Account
302 const avatar = await updateActorAvatarFile(avatarPhysicalFile, account.Actor, account)
306 avatar: avatar.toFormattedJSON()
311 async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) {
312 const body: UserUpdate = req.body
313 const user = res.locals.user as UserModel
314 const roleChanged = body.role !== undefined && body.role !== user.role
316 if (body.email !== undefined) user.email = body.email
317 if (body.videoQuota !== undefined) user.videoQuota = body.videoQuota
318 if (body.role !== undefined) user.role = body.role
322 // Destroy user token to refresh rights
324 await OAuthTokenModel.deleteUserToken(user.id)
327 // Don't need to send this update to followers, these attributes are not propagated
329 return res.sendStatus(204)
332 async function askResetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
333 const user = res.locals.user as UserModel
335 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
336 const url = CONFIG.WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
337 await Emailer.Instance.addForgetPasswordEmailJob(user.email, url)
339 return res.status(204).end()
342 async function resetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
343 const user = res.locals.user as UserModel
344 user.password = req.body.password
348 return res.status(204).end()
351 function success (req: express.Request, res: express.Response, next: express.NextFunction) {