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