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'
34 usersAskResetPasswordValidator,
35 usersResetPasswordValidator,
36 videoImportsSortValidator,
38 } from '../../middlewares/validators'
39 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
40 import { UserModel } from '../../models/account/user'
41 import { OAuthTokenModel } from '../../models/oauth/oauth-token'
42 import { VideoModel } from '../../models/video/video'
43 import { VideoSortField } from '../../../client/src/app/shared/video/sort-field.type'
44 import { createReqFiles } from '../../helpers/express-utils'
45 import { UserVideoQuota } from '../../../shared/models/users/user-video-quota.model'
46 import { updateAvatarValidator } from '../../middlewares/validators/avatar'
47 import { updateActorAvatarFile } from '../../lib/avatar'
48 import { auditLoggerFactory, UserAuditView } from '../../helpers/audit-logger'
49 import { VideoImportModel } from '../../models/video/video-import'
51 const auditLogger = auditLoggerFactory('users')
53 const reqAvatarFile = createReqFiles([ 'avatarfile' ], IMAGE_MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.AVATARS_DIR })
54 const loginRateLimiter = new RateLimit({
55 windowMs: RATES_LIMIT.LOGIN.WINDOW_MS,
56 max: RATES_LIMIT.LOGIN.MAX,
60 const usersRouter = express.Router()
62 usersRouter.get('/me',
64 asyncMiddleware(getUserInformation)
66 usersRouter.delete('/me',
68 asyncMiddleware(deleteMeValidator),
69 asyncMiddleware(deleteMe)
72 usersRouter.get('/me/video-quota-used',
74 asyncMiddleware(getUserVideoQuotaUsed)
77 usersRouter.get('/me/videos/imports',
80 videoImportsSortValidator,
83 asyncMiddleware(getUserVideoImports)
86 usersRouter.get('/me/videos',
92 asyncMiddleware(getUserVideos)
95 usersRouter.get('/me/videos/:videoId/rating',
97 asyncMiddleware(usersVideoRatingValidator),
98 asyncMiddleware(getUserVideoRating)
103 ensureUserHasRight(UserRight.MANAGE_USERS),
107 setDefaultPagination,
108 asyncMiddleware(listUsers)
111 usersRouter.get('/:id',
113 ensureUserHasRight(UserRight.MANAGE_USERS),
114 asyncMiddleware(usersGetValidator),
118 usersRouter.post('/',
120 ensureUserHasRight(UserRight.MANAGE_USERS),
121 asyncMiddleware(usersAddValidator),
122 asyncRetryTransactionMiddleware(createUser)
125 usersRouter.post('/register',
126 asyncMiddleware(ensureUserRegistrationAllowed),
127 ensureUserRegistrationAllowedForIP,
128 asyncMiddleware(usersRegisterValidator),
129 asyncRetryTransactionMiddleware(registerUser)
132 usersRouter.put('/me',
134 usersUpdateMeValidator,
135 asyncMiddleware(updateMe)
138 usersRouter.post('/me/avatar/pick',
141 updateAvatarValidator,
142 asyncMiddleware(updateMyAvatar)
145 usersRouter.put('/:id',
147 ensureUserHasRight(UserRight.MANAGE_USERS),
148 asyncMiddleware(usersUpdateValidator),
149 asyncMiddleware(updateUser)
152 usersRouter.delete('/:id',
154 ensureUserHasRight(UserRight.MANAGE_USERS),
155 asyncMiddleware(usersRemoveValidator),
156 asyncMiddleware(removeUser)
159 usersRouter.post('/ask-reset-password',
160 asyncMiddleware(usersAskResetPasswordValidator),
161 asyncMiddleware(askResetUserPassword)
164 usersRouter.post('/:id/reset-password',
165 asyncMiddleware(usersResetPasswordValidator),
166 asyncMiddleware(resetUserPassword)
169 usersRouter.post('/token',
174 // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
176 // ---------------------------------------------------------------------------
182 // ---------------------------------------------------------------------------
184 async function getUserVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
185 const user = res.locals.oauth.token.User as UserModel
186 const resultList = await VideoModel.listUserVideosForApi(
188 req.query.start as number,
189 req.query.count as number,
190 req.query.sort as VideoSortField,
191 false // Display my NSFW videos
194 const additionalAttributes = {
195 waitTranscoding: true,
197 scheduledUpdate: true
199 return res.json(getFormattedObjects(resultList.data, resultList.total, { additionalAttributes }))
202 async function getUserVideoImports (req: express.Request, res: express.Response, next: express.NextFunction) {
203 const user = res.locals.oauth.token.User as UserModel
204 const resultList = await VideoImportModel.listUserVideoImportsForApi(
206 req.query.start as number,
207 req.query.count as number,
211 return res.json(getFormattedObjects(resultList.data, resultList.total))
214 async function createUser (req: express.Request, res: express.Response) {
215 const body: UserCreate = req.body
216 const userToCreate = new UserModel({
217 username: body.username,
218 password: body.password,
220 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
223 videoQuota: body.videoQuota
226 const { user, account } = await createUserAccountAndChannel(userToCreate)
228 auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new UserAuditView(user.toFormattedJSON()))
229 logger.info('User %s with its channel and account created.', body.username)
236 uuid: account.Actor.uuid
242 async function registerUser (req: express.Request, res: express.Response) {
243 const body: UserCreate = req.body
245 const userToCreate = new UserModel({
246 username: body.username,
247 password: body.password,
249 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
252 videoQuota: CONFIG.USER.VIDEO_QUOTA
255 const { user } = await createUserAccountAndChannel(userToCreate)
257 auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON()))
258 logger.info('User %s with its channel and account registered.', body.username)
260 return res.type('json').status(204).end()
263 async function getUserInformation (req: express.Request, res: express.Response, next: express.NextFunction) {
264 // We did not load channels in res.locals.user
265 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
267 return res.json(user.toFormattedJSON())
270 async function getUserVideoQuotaUsed (req: express.Request, res: express.Response, next: express.NextFunction) {
271 // We did not load channels in res.locals.user
272 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
273 const videoQuotaUsed = await UserModel.getOriginalVideoFileTotalFromUser(user)
275 const data: UserVideoQuota = {
278 return res.json(data)
281 function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
282 return res.json((res.locals.user as UserModel).toFormattedJSON())
285 async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) {
286 const videoId = +req.params.videoId
287 const accountId = +res.locals.oauth.token.User.Account.id
289 const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null)
290 const rating = ratingObj ? ratingObj.type : 'none'
292 const json: FormattedUserVideoRate = {
299 async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
300 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort)
302 return res.json(getFormattedObjects(resultList.data, resultList.total))
305 async function deleteMe (req: express.Request, res: express.Response) {
306 const user: UserModel = res.locals.oauth.token.User
310 auditLogger.delete(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new UserAuditView(user.toFormattedJSON()))
312 return res.sendStatus(204)
315 async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
316 const user: UserModel = res.locals.user
320 auditLogger.delete(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new UserAuditView(user.toFormattedJSON()))
322 return res.sendStatus(204)
325 async function updateMe (req: express.Request, res: express.Response, next: express.NextFunction) {
326 const body: UserUpdateMe = req.body
328 const user: UserModel = res.locals.oauth.token.user
329 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
331 if (body.password !== undefined) user.password = body.password
332 if (body.email !== undefined) user.email = body.email
333 if (body.nsfwPolicy !== undefined) user.nsfwPolicy = body.nsfwPolicy
334 if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo
336 await sequelizeTypescript.transaction(async t => {
337 await user.save({ transaction: t })
339 if (body.displayName !== undefined) user.Account.name = body.displayName
340 if (body.description !== undefined) user.Account.description = body.description
341 await user.Account.save({ transaction: t })
343 await sendUpdateActor(user.Account, t)
346 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
347 new UserAuditView(user.toFormattedJSON()),
352 return res.sendStatus(204)
355 async function updateMyAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
356 const avatarPhysicalFile = req.files[ 'avatarfile' ][ 0 ]
357 const user: UserModel = res.locals.oauth.token.user
358 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
359 const account = user.Account
361 const avatar = await updateActorAvatarFile(avatarPhysicalFile, account.Actor, account)
364 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
365 new UserAuditView(user.toFormattedJSON()),
371 avatar: avatar.toFormattedJSON()
376 async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) {
377 const body: UserUpdate = req.body
378 const userToUpdate = res.locals.user as UserModel
379 const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON())
380 const roleChanged = body.role !== undefined && body.role !== userToUpdate.role
382 if (body.email !== undefined) userToUpdate.email = body.email
383 if (body.videoQuota !== undefined) userToUpdate.videoQuota = body.videoQuota
384 if (body.role !== undefined) userToUpdate.role = body.role
386 const user = await userToUpdate.save()
388 // Destroy user token to refresh rights
390 await OAuthTokenModel.deleteUserToken(userToUpdate.id)
394 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
395 new UserAuditView(user.toFormattedJSON()),
399 // Don't need to send this update to followers, these attributes are not propagated
401 return res.sendStatus(204)
404 async function askResetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
405 const user = res.locals.user as UserModel
407 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
408 const url = CONFIG.WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
409 await Emailer.Instance.addForgetPasswordEmailJob(user.email, url)
411 return res.status(204).end()
414 async function resetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
415 const user = res.locals.user as UserModel
416 user.password = req.body.password
420 return res.status(204).end()
423 function success (req: express.Request, res: express.Response, next: express.NextFunction) {