1 import * as express from 'express'
2 import { extname, join } from 'path'
3 import * as uuidv4 from 'uuid/v4'
4 import { UserCreate, UserRight, UserRole, UserUpdate, UserUpdateMe, UserVideoRate as FormattedUserVideoRate } from '../../../shared'
5 import { renamePromise } from '../../helpers/core-utils'
6 import { retryTransactionWrapper } from '../../helpers/database-utils'
7 import { logger } from '../../helpers/logger'
8 import { createReqFiles, getFormattedObjects } from '../../helpers/utils'
9 import { AVATAR_MIMETYPE_EXT, CONFIG, sequelizeTypescript } from '../../initializers'
10 import { createUserAccountAndChannel } from '../../lib/user'
12 asyncMiddleware, authenticate, ensureUserHasRight, ensureUserRegistrationAllowed, paginationValidator, setPagination, setUsersSort,
13 setVideosSort, token, usersAddValidator, usersGetValidator, usersRegisterValidator, usersRemoveValidator, usersSortValidator,
14 usersUpdateMeValidator, usersUpdateValidator, usersVideoRatingValidator
15 } from '../../middlewares'
16 import { usersUpdateMyAvatarValidator, videosSortValidator } from '../../middlewares/validators'
17 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
18 import { UserModel } from '../../models/account/user'
19 import { AvatarModel } from '../../models/avatar/avatar'
20 import { VideoModel } from '../../models/video/video'
22 const reqAvatarFile = createReqFiles('avatarfile', CONFIG.STORAGE.AVATARS_DIR, AVATAR_MIMETYPE_EXT)
24 const usersRouter = express.Router()
26 usersRouter.get('/me',
28 asyncMiddleware(getUserInformation)
31 usersRouter.get('/me/videos',
37 asyncMiddleware(getUserVideos)
40 usersRouter.get('/me/videos/:videoId/rating',
42 asyncMiddleware(usersVideoRatingValidator),
43 asyncMiddleware(getUserVideoRating)
48 ensureUserHasRight(UserRight.MANAGE_USERS),
53 asyncMiddleware(listUsers)
56 usersRouter.get('/:id',
57 asyncMiddleware(usersGetValidator),
63 ensureUserHasRight(UserRight.MANAGE_USERS),
64 asyncMiddleware(usersAddValidator),
65 asyncMiddleware(createUserRetryWrapper)
68 usersRouter.post('/register',
69 asyncMiddleware(ensureUserRegistrationAllowed),
70 asyncMiddleware(usersRegisterValidator),
71 asyncMiddleware(registerUserRetryWrapper)
74 usersRouter.put('/me',
76 usersUpdateMeValidator,
77 asyncMiddleware(updateMe)
80 usersRouter.post('/me/avatar/pick',
83 usersUpdateMyAvatarValidator,
84 asyncMiddleware(updateMyAvatar)
87 usersRouter.put('/:id',
89 ensureUserHasRight(UserRight.MANAGE_USERS),
90 asyncMiddleware(usersUpdateValidator),
91 asyncMiddleware(updateUser)
94 usersRouter.delete('/:id',
96 ensureUserHasRight(UserRight.MANAGE_USERS),
97 asyncMiddleware(usersRemoveValidator),
98 asyncMiddleware(removeUser)
101 usersRouter.post('/token', token, success)
102 // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
104 // ---------------------------------------------------------------------------
110 // ---------------------------------------------------------------------------
112 async function getUserVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
113 const user = res.locals.oauth.token.User as UserModel
114 const resultList = await VideoModel.listUserVideosForApi(user.id ,req.query.start, req.query.count, req.query.sort)
116 return res.json(getFormattedObjects(resultList.data, resultList.total))
119 async function createUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
122 errorMessage: 'Cannot insert the user with many retries.'
125 await retryTransactionWrapper(createUser, options)
127 // TODO : include Location of the new user -> 201
128 return res.type('json').status(204).end()
131 async function createUser (req: express.Request) {
132 const body: UserCreate = req.body
133 const user = new UserModel({
134 username: body.username,
135 password: body.password,
140 videoQuota: body.videoQuota
143 await createUserAccountAndChannel(user)
145 logger.info('User %s with its channel and account created.', body.username)
148 async function registerUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
151 errorMessage: 'Cannot insert the user with many retries.'
154 await retryTransactionWrapper(registerUser, options)
156 return res.type('json').status(204).end()
159 async function registerUser (req: express.Request) {
160 const body: UserCreate = req.body
162 const user = new UserModel({
163 username: body.username,
164 password: body.password,
169 videoQuota: CONFIG.USER.VIDEO_QUOTA
172 await createUserAccountAndChannel(user)
174 logger.info('User %s with its channel and account registered.', body.username)
177 async function getUserInformation (req: express.Request, res: express.Response, next: express.NextFunction) {
178 // We did not load channels in res.locals.user
179 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
181 return res.json(user.toFormattedJSON())
184 function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
185 return res.json(res.locals.user.toFormattedJSON())
188 async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) {
189 const videoId = +req.params.videoId
190 const accountId = +res.locals.oauth.token.User.Account.id
192 const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null)
193 const rating = ratingObj ? ratingObj.type : 'none'
195 const json: FormattedUserVideoRate = {
202 async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
203 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort)
205 return res.json(getFormattedObjects(resultList.data, resultList.total))
208 async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
209 const user = await UserModel.loadById(req.params.id)
213 return res.sendStatus(204)
216 async function updateMe (req: express.Request, res: express.Response, next: express.NextFunction) {
217 const body: UserUpdateMe = req.body
219 // FIXME: user is not already a Sequelize instance?
220 const user = res.locals.oauth.token.user
222 if (body.password !== undefined) user.password = body.password
223 if (body.email !== undefined) user.email = body.email
224 if (body.displayNSFW !== undefined) user.displayNSFW = body.displayNSFW
225 if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo
229 return res.sendStatus(204)
232 async function updateMyAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
233 const avatarPhysicalFile = req.files['avatarfile'][0]
234 const actor = res.locals.oauth.token.user.Account.Actor
236 const avatarDir = CONFIG.STORAGE.AVATARS_DIR
237 const source = join(avatarDir, avatarPhysicalFile.filename)
238 const extension = extname(avatarPhysicalFile.filename)
239 const avatarName = uuidv4() + extension
240 const destination = join(avatarDir, avatarName)
242 await renamePromise(source, destination)
244 const { avatar } = await sequelizeTypescript.transaction(async t => {
245 const avatar = await AvatarModel.create({
247 }, { transaction: t })
250 await actor.Avatar.destroy({ transaction: t })
253 actor.set('avatarId', avatar.id)
254 await actor.save({ transaction: t })
256 return { actor, avatar }
261 avatar: avatar.toFormattedJSON()
266 async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) {
267 const body: UserUpdate = req.body
268 const user = res.locals.user as UserModel
270 if (body.email !== undefined) user.email = body.email
271 if (body.videoQuota !== undefined) user.videoQuota = body.videoQuota
272 if (body.role !== undefined) user.role = body.role
276 return res.sendStatus(204)
279 function success (req: express.Request, res: express.Response, next: express.NextFunction) {