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'
42 import { auditLoggerFactory, UserAuditView } from '../../helpers/audit-logger'
44 const auditLogger = auditLoggerFactory('users')
46 const reqAvatarFile = createReqFiles([ 'avatarfile' ], IMAGE_MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.AVATARS_DIR })
47 const loginRateLimiter = new RateLimit({
48 windowMs: RATES_LIMIT.LOGIN.WINDOW_MS,
49 max: RATES_LIMIT.LOGIN.MAX,
53 const usersRouter = express.Router()
55 usersRouter.get('/me',
57 asyncMiddleware(getUserInformation)
60 usersRouter.get('/me/video-quota-used',
62 asyncMiddleware(getUserVideoQuotaUsed)
65 usersRouter.get('/me/videos',
71 asyncMiddleware(getUserVideos)
74 usersRouter.get('/me/videos/:videoId/rating',
76 asyncMiddleware(usersVideoRatingValidator),
77 asyncMiddleware(getUserVideoRating)
82 ensureUserHasRight(UserRight.MANAGE_USERS),
87 asyncMiddleware(listUsers)
90 usersRouter.get('/:id',
92 ensureUserHasRight(UserRight.MANAGE_USERS),
93 asyncMiddleware(usersGetValidator),
99 ensureUserHasRight(UserRight.MANAGE_USERS),
100 asyncMiddleware(usersAddValidator),
101 asyncRetryTransactionMiddleware(createUser)
104 usersRouter.post('/register',
105 asyncMiddleware(ensureUserRegistrationAllowed),
106 ensureUserRegistrationAllowedForIP,
107 asyncMiddleware(usersRegisterValidator),
108 asyncRetryTransactionMiddleware(registerUser)
111 usersRouter.put('/me',
113 usersUpdateMeValidator,
114 asyncMiddleware(updateMe)
117 usersRouter.post('/me/avatar/pick',
120 updateAvatarValidator,
121 asyncMiddleware(updateMyAvatar)
124 usersRouter.put('/:id',
126 ensureUserHasRight(UserRight.MANAGE_USERS),
127 asyncMiddleware(usersUpdateValidator),
128 asyncMiddleware(updateUser)
131 usersRouter.delete('/:id',
133 ensureUserHasRight(UserRight.MANAGE_USERS),
134 asyncMiddleware(usersRemoveValidator),
135 asyncMiddleware(removeUser)
138 usersRouter.post('/ask-reset-password',
139 asyncMiddleware(usersAskResetPasswordValidator),
140 asyncMiddleware(askResetUserPassword)
143 usersRouter.post('/:id/reset-password',
144 asyncMiddleware(usersResetPasswordValidator),
145 asyncMiddleware(resetUserPassword)
148 usersRouter.post('/token',
153 // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
155 // ---------------------------------------------------------------------------
161 // ---------------------------------------------------------------------------
163 async function getUserVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
164 const user = res.locals.oauth.token.User as UserModel
165 const resultList = await VideoModel.listUserVideosForApi(
167 req.query.start as number,
168 req.query.count as number,
169 req.query.sort as VideoSortField,
170 false // Display my NSFW videos
173 const additionalAttributes = {
174 waitTranscoding: true,
176 scheduledUpdate: true
178 return res.json(getFormattedObjects(resultList.data, resultList.total, { additionalAttributes }))
181 async function createUser (req: express.Request, res: express.Response) {
182 const body: UserCreate = req.body
183 const userToCreate = new UserModel({
184 username: body.username,
185 password: body.password,
187 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
190 videoQuota: body.videoQuota
193 const { user, account } = await createUserAccountAndChannel(userToCreate)
195 auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new UserAuditView(user.toFormattedJSON()))
196 logger.info('User %s with its channel and account created.', body.username)
203 uuid: account.Actor.uuid
209 async function registerUser (req: express.Request, res: express.Response) {
210 const body: UserCreate = req.body
212 const userToCreate = new UserModel({
213 username: body.username,
214 password: body.password,
216 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
219 videoQuota: CONFIG.USER.VIDEO_QUOTA
222 const { user } = await createUserAccountAndChannel(userToCreate)
224 auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON()))
225 logger.info('User %s with its channel and account registered.', body.username)
227 return res.type('json').status(204).end()
230 async function getUserInformation (req: express.Request, res: express.Response, next: express.NextFunction) {
231 // We did not load channels in res.locals.user
232 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
234 return res.json(user.toFormattedJSON())
237 async function getUserVideoQuotaUsed (req: express.Request, res: express.Response, next: express.NextFunction) {
238 // We did not load channels in res.locals.user
239 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
240 const videoQuotaUsed = await UserModel.getOriginalVideoFileTotalFromUser(user)
242 const data: UserVideoQuota = {
245 return res.json(data)
248 function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
249 return res.json((res.locals.user as UserModel).toFormattedJSON())
252 async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) {
253 const videoId = +req.params.videoId
254 const accountId = +res.locals.oauth.token.User.Account.id
256 const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null)
257 const rating = ratingObj ? ratingObj.type : 'none'
259 const json: FormattedUserVideoRate = {
266 async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
267 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort)
269 return res.json(getFormattedObjects(resultList.data, resultList.total))
272 async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
273 const user = await UserModel.loadById(req.params.id)
277 auditLogger.delete(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new UserAuditView(user.toFormattedJSON()))
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
286 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
288 if (body.password !== undefined) user.password = body.password
289 if (body.email !== undefined) user.email = body.email
290 if (body.nsfwPolicy !== undefined) user.nsfwPolicy = body.nsfwPolicy
291 if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo
293 await sequelizeTypescript.transaction(async t => {
294 await user.save({ transaction: t })
296 if (body.displayName !== undefined) user.Account.name = body.displayName
297 if (body.description !== undefined) user.Account.description = body.description
298 await user.Account.save({ transaction: t })
300 await sendUpdateActor(user.Account, t)
303 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
304 new UserAuditView(user.toFormattedJSON()),
309 return res.sendStatus(204)
312 async function updateMyAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
313 const avatarPhysicalFile = req.files[ 'avatarfile' ][ 0 ]
314 const user: UserModel = res.locals.oauth.token.user
315 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
316 const account = user.Account
318 const avatar = await updateActorAvatarFile(avatarPhysicalFile, account.Actor, account)
321 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
322 new UserAuditView(user.toFormattedJSON()),
328 avatar: avatar.toFormattedJSON()
333 async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) {
334 const body: UserUpdate = req.body
335 const userToUpdate = res.locals.user as UserModel
336 const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON())
337 const roleChanged = body.role !== undefined && body.role !== userToUpdate.role
339 if (body.email !== undefined) userToUpdate.email = body.email
340 if (body.videoQuota !== undefined) userToUpdate.videoQuota = body.videoQuota
341 if (body.role !== undefined) userToUpdate.role = body.role
343 const user = await userToUpdate.save()
345 // Destroy user token to refresh rights
347 await OAuthTokenModel.deleteUserToken(userToUpdate.id)
351 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
352 new UserAuditView(user.toFormattedJSON()),
356 // Don't need to send this update to followers, these attributes are not propagated
358 return res.sendStatus(204)
361 async function askResetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
362 const user = res.locals.user as UserModel
364 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
365 const url = CONFIG.WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
366 await Emailer.Instance.addForgetPasswordEmailJob(user.email, url)
368 return res.status(204).end()
371 async function resetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
372 const user = res.locals.user as UserModel
373 user.password = req.body.password
377 return res.status(204).end()
380 function success (req: express.Request, res: express.Response, next: express.NextFunction) {