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