1 import * as express from 'express'
2 import { UserCreate, UserRight, UserRole, UserUpdate, UserUpdateMe, UserVideoRate as FormattedUserVideoRate } from '../../../shared'
3 import { getFormattedObjects, logger, retryTransactionWrapper } from '../../helpers'
4 import { CONFIG, database as db } from '../../initializers'
5 import { createUserAccountAndChannel } from '../../lib'
10 ensureUserRegistrationAllowed,
17 usersRegisterValidator,
20 usersUpdateMeValidator,
22 usersVideoRatingValidator
23 } from '../../middlewares'
24 import { setVideosSort } from '../../middlewares/sort'
25 import { videosSortValidator } from '../../middlewares/validators/sort'
26 import { UserInstance } from '../../models'
28 const usersRouter = express.Router()
30 usersRouter.get('/me',
32 asyncMiddleware(getUserInformation)
35 usersRouter.get('/me/videos',
41 asyncMiddleware(getUserVideos)
44 usersRouter.get('/me/videos/:videoId/rating',
46 asyncMiddleware(usersVideoRatingValidator),
47 asyncMiddleware(getUserVideoRating)
52 ensureUserHasRight(UserRight.MANAGE_USERS),
57 asyncMiddleware(listUsers)
60 usersRouter.get('/:id',
61 asyncMiddleware(usersGetValidator),
67 ensureUserHasRight(UserRight.MANAGE_USERS),
68 asyncMiddleware(usersAddValidator),
69 asyncMiddleware(createUserRetryWrapper)
72 usersRouter.post('/register',
73 asyncMiddleware(ensureUserRegistrationAllowed),
74 asyncMiddleware(usersRegisterValidator),
75 asyncMiddleware(registerUserRetryWrapper)
78 usersRouter.put('/me',
80 usersUpdateMeValidator,
81 asyncMiddleware(updateMe)
84 usersRouter.put('/:id',
86 ensureUserHasRight(UserRight.MANAGE_USERS),
87 asyncMiddleware(usersUpdateValidator),
88 asyncMiddleware(updateUser)
91 usersRouter.delete('/:id',
93 ensureUserHasRight(UserRight.MANAGE_USERS),
94 asyncMiddleware(usersRemoveValidator),
95 asyncMiddleware(removeUser)
98 usersRouter.post('/token', token, success)
99 // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
101 // ---------------------------------------------------------------------------
107 // ---------------------------------------------------------------------------
109 async function getUserVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
110 const user = res.locals.oauth.token.User
111 const resultList = await db.Video.listUserVideosForApi(user.id ,req.query.start, req.query.count, req.query.sort)
113 return res.json(getFormattedObjects(resultList.data, resultList.total))
116 async function createUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
119 errorMessage: 'Cannot insert the user with many retries.'
122 await retryTransactionWrapper(createUser, options)
124 // TODO : include Location of the new user -> 201
125 return res.type('json').status(204).end()
128 async function createUser (req: express.Request) {
129 const body: UserCreate = req.body
130 const user = db.User.build({
131 username: body.username,
132 password: body.password,
136 videoQuota: body.videoQuota
139 await createUserAccountAndChannel(user)
141 logger.info('User %s with its channel and account created.', body.username)
144 async function registerUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
147 errorMessage: 'Cannot insert the user with many retries.'
150 await retryTransactionWrapper(registerUser, options)
152 return res.type('json').status(204).end()
155 async function registerUser (req: express.Request) {
156 const body: UserCreate = req.body
158 const user = db.User.build({
159 username: body.username,
160 password: body.password,
164 videoQuota: CONFIG.USER.VIDEO_QUOTA
167 await createUserAccountAndChannel(user)
169 logger.info('User %s with its channel and account registered.', body.username)
172 async function getUserInformation (req: express.Request, res: express.Response, next: express.NextFunction) {
173 // We did not load channels in res.locals.user
174 const user = await db.User.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
176 return res.json(user.toFormattedJSON())
179 function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
180 return res.json(res.locals.user.toFormattedJSON())
183 async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) {
184 const videoId = +req.params.videoId
185 const accountId = +res.locals.oauth.token.User.Account.id
187 const ratingObj = await db.AccountVideoRate.load(accountId, videoId, null)
188 const rating = ratingObj ? ratingObj.type : 'none'
190 const json: FormattedUserVideoRate = {
197 async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
198 const resultList = await db.User.listForApi(req.query.start, req.query.count, req.query.sort)
200 return res.json(getFormattedObjects(resultList.data, resultList.total))
203 async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
204 const user = await db.User.loadById(req.params.id)
208 return res.sendStatus(204)
211 async function updateMe (req: express.Request, res: express.Response, next: express.NextFunction) {
212 const body: UserUpdateMe = req.body
214 // FIXME: user is not already a Sequelize instance?
215 const user = res.locals.oauth.token.user
217 if (body.password !== undefined) user.password = body.password
218 if (body.email !== undefined) user.email = body.email
219 if (body.displayNSFW !== undefined) user.displayNSFW = body.displayNSFW
223 return res.sendStatus(204)
226 async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) {
227 const body: UserUpdate = req.body
228 const user: UserInstance = res.locals.user
230 if (body.email !== undefined) user.email = body.email
231 if (body.videoQuota !== undefined) user.videoQuota = body.videoQuota
232 if (body.role !== undefined) user.role = body.role
236 return res.sendStatus(204)
239 function success (req: express.Request, res: express.Response, next: express.NextFunction) {