]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/users.ts
Redirect to uuid video route after upload
[github/Chocobozzz/PeerTube.git] / server / controllers / api / users.ts
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 } from '../../initializers'
5 import { createUserAccountAndChannel } from '../../lib/user'
6 import {
7 asyncMiddleware,
8 authenticate,
9 ensureUserHasRight,
10 ensureUserRegistrationAllowed,
11 paginationValidator,
12 setPagination,
13 setUsersSort,
14 setVideosSort,
15 token,
16 usersAddValidator,
17 usersGetValidator,
18 usersRegisterValidator,
19 usersRemoveValidator,
20 usersSortValidator,
21 usersUpdateMeValidator,
22 usersUpdateValidator,
23 usersVideoRatingValidator
24 } from '../../middlewares'
25 import { videosSortValidator } from '../../middlewares/validators'
26 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
27 import { UserModel } from '../../models/account/user'
28 import { VideoModel } from '../../models/video/video'
29
30 const usersRouter = express.Router()
31
32 usersRouter.get('/me',
33 authenticate,
34 asyncMiddleware(getUserInformation)
35 )
36
37 usersRouter.get('/me/videos',
38 authenticate,
39 paginationValidator,
40 videosSortValidator,
41 setVideosSort,
42 setPagination,
43 asyncMiddleware(getUserVideos)
44 )
45
46 usersRouter.get('/me/videos/:videoId/rating',
47 authenticate,
48 asyncMiddleware(usersVideoRatingValidator),
49 asyncMiddleware(getUserVideoRating)
50 )
51
52 usersRouter.get('/',
53 authenticate,
54 ensureUserHasRight(UserRight.MANAGE_USERS),
55 paginationValidator,
56 usersSortValidator,
57 setUsersSort,
58 setPagination,
59 asyncMiddleware(listUsers)
60 )
61
62 usersRouter.get('/:id',
63 asyncMiddleware(usersGetValidator),
64 getUser
65 )
66
67 usersRouter.post('/',
68 authenticate,
69 ensureUserHasRight(UserRight.MANAGE_USERS),
70 asyncMiddleware(usersAddValidator),
71 asyncMiddleware(createUserRetryWrapper)
72 )
73
74 usersRouter.post('/register',
75 asyncMiddleware(ensureUserRegistrationAllowed),
76 asyncMiddleware(usersRegisterValidator),
77 asyncMiddleware(registerUserRetryWrapper)
78 )
79
80 usersRouter.put('/me',
81 authenticate,
82 usersUpdateMeValidator,
83 asyncMiddleware(updateMe)
84 )
85
86 usersRouter.put('/:id',
87 authenticate,
88 ensureUserHasRight(UserRight.MANAGE_USERS),
89 asyncMiddleware(usersUpdateValidator),
90 asyncMiddleware(updateUser)
91 )
92
93 usersRouter.delete('/:id',
94 authenticate,
95 ensureUserHasRight(UserRight.MANAGE_USERS),
96 asyncMiddleware(usersRemoveValidator),
97 asyncMiddleware(removeUser)
98 )
99
100 usersRouter.post('/token', token, success)
101 // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
102
103 // ---------------------------------------------------------------------------
104
105 export {
106 usersRouter
107 }
108
109 // ---------------------------------------------------------------------------
110
111 async function getUserVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
112 const user = res.locals.oauth.token.User as UserModel
113 const resultList = await VideoModel.listUserVideosForApi(user.id ,req.query.start, req.query.count, req.query.sort)
114
115 return res.json(getFormattedObjects(resultList.data, resultList.total))
116 }
117
118 async function createUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
119 const options = {
120 arguments: [ req ],
121 errorMessage: 'Cannot insert the user with many retries.'
122 }
123
124 await retryTransactionWrapper(createUser, options)
125
126 // TODO : include Location of the new user -> 201
127 return res.type('json').status(204).end()
128 }
129
130 async function createUser (req: express.Request) {
131 const body: UserCreate = req.body
132 const user = new UserModel({
133 username: body.username,
134 password: body.password,
135 email: body.email,
136 displayNSFW: false,
137 autoPlayVideo: true,
138 role: body.role,
139 videoQuota: body.videoQuota
140 })
141
142 await createUserAccountAndChannel(user)
143
144 logger.info('User %s with its channel and account created.', body.username)
145 }
146
147 async function registerUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
148 const options = {
149 arguments: [ req ],
150 errorMessage: 'Cannot insert the user with many retries.'
151 }
152
153 await retryTransactionWrapper(registerUser, options)
154
155 return res.type('json').status(204).end()
156 }
157
158 async function registerUser (req: express.Request) {
159 const body: UserCreate = req.body
160
161 const user = new UserModel({
162 username: body.username,
163 password: body.password,
164 email: body.email,
165 displayNSFW: false,
166 autoPlayVideo: true,
167 role: UserRole.USER,
168 videoQuota: CONFIG.USER.VIDEO_QUOTA
169 })
170
171 await createUserAccountAndChannel(user)
172
173 logger.info('User %s with its channel and account registered.', body.username)
174 }
175
176 async function getUserInformation (req: express.Request, res: express.Response, next: express.NextFunction) {
177 // We did not load channels in res.locals.user
178 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
179
180 return res.json(user.toFormattedJSON())
181 }
182
183 function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
184 return res.json(res.locals.user.toFormattedJSON())
185 }
186
187 async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) {
188 const videoId = +req.params.videoId
189 const accountId = +res.locals.oauth.token.User.Account.id
190
191 const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null)
192 const rating = ratingObj ? ratingObj.type : 'none'
193
194 const json: FormattedUserVideoRate = {
195 videoId,
196 rating
197 }
198 res.json(json)
199 }
200
201 async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
202 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort)
203
204 return res.json(getFormattedObjects(resultList.data, resultList.total))
205 }
206
207 async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
208 const user = await UserModel.loadById(req.params.id)
209
210 await user.destroy()
211
212 return res.sendStatus(204)
213 }
214
215 async function updateMe (req: express.Request, res: express.Response, next: express.NextFunction) {
216 const body: UserUpdateMe = req.body
217
218 // FIXME: user is not already a Sequelize instance?
219 const user = res.locals.oauth.token.user
220
221 if (body.password !== undefined) user.password = body.password
222 if (body.email !== undefined) user.email = body.email
223 if (body.displayNSFW !== undefined) user.displayNSFW = body.displayNSFW
224 if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo
225
226 await user.save()
227
228 return res.sendStatus(204)
229 }
230
231 async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) {
232 const body: UserUpdate = req.body
233 const user = res.locals.user as UserModel
234
235 if (body.email !== undefined) user.email = body.email
236 if (body.videoQuota !== undefined) user.videoQuota = body.videoQuota
237 if (body.role !== undefined) user.role = body.role
238
239 await user.save()
240
241 return res.sendStatus(204)
242 }
243
244 function success (req: express.Request, res: express.Response, next: express.NextFunction) {
245 res.end()
246 }