Put activity pub sends inside transactions
[oweals/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   asyncMiddleware(usersVideoRatingValidator),
47   asyncMiddleware(getUserVideoRating)
48 )
49
50 usersRouter.get('/',
51   authenticate,
52   ensureUserHasRight(UserRight.MANAGE_USERS),
53   paginationValidator,
54   usersSortValidator,
55   setUsersSort,
56   setPagination,
57   asyncMiddleware(listUsers)
58 )
59
60 usersRouter.get('/:id',
61   asyncMiddleware(usersGetValidator),
62   getUser
63 )
64
65 usersRouter.post('/',
66   authenticate,
67   ensureUserHasRight(UserRight.MANAGE_USERS),
68   asyncMiddleware(usersAddValidator),
69   asyncMiddleware(createUserRetryWrapper)
70 )
71
72 usersRouter.post('/register',
73   asyncMiddleware(ensureUserRegistrationAllowed),
74   asyncMiddleware(usersRegisterValidator),
75   asyncMiddleware(registerUserRetryWrapper)
76 )
77
78 usersRouter.put('/me',
79   authenticate,
80   usersUpdateMeValidator,
81   asyncMiddleware(updateMe)
82 )
83
84 usersRouter.put('/:id',
85   authenticate,
86   ensureUserHasRight(UserRight.MANAGE_USERS),
87   asyncMiddleware(usersUpdateValidator),
88   asyncMiddleware(updateUser)
89 )
90
91 usersRouter.delete('/:id',
92   authenticate,
93   ensureUserHasRight(UserRight.MANAGE_USERS),
94   asyncMiddleware(usersRemoveValidator),
95   asyncMiddleware(removeUser)
96 )
97
98 usersRouter.post('/token', token, success)
99 // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
100
101 // ---------------------------------------------------------------------------
102
103 export {
104   usersRouter
105 }
106
107 // ---------------------------------------------------------------------------
108
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)
112
113   return res.json(getFormattedObjects(resultList.data, resultList.total))
114 }
115
116 async function createUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
117   const options = {
118     arguments: [ req ],
119     errorMessage: 'Cannot insert the user with many retries.'
120   }
121
122   await retryTransactionWrapper(createUser, options)
123
124   // TODO : include Location of the new user -> 201
125   return res.type('json').status(204).end()
126 }
127
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,
133     email: body.email,
134     displayNSFW: false,
135     role: body.role,
136     videoQuota: body.videoQuota
137   })
138
139   await createUserAccountAndChannel(user)
140
141   logger.info('User %s with its channel and account created.', body.username)
142 }
143
144 async function registerUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
145   const options = {
146     arguments: [ req ],
147     errorMessage: 'Cannot insert the user with many retries.'
148   }
149
150   await retryTransactionWrapper(registerUser, options)
151
152   return res.type('json').status(204).end()
153 }
154
155 async function registerUser (req: express.Request) {
156   const body: UserCreate = req.body
157
158   const user = db.User.build({
159     username: body.username,
160     password: body.password,
161     email: body.email,
162     displayNSFW: false,
163     role: UserRole.USER,
164     videoQuota: CONFIG.USER.VIDEO_QUOTA
165   })
166
167   await createUserAccountAndChannel(user)
168
169   logger.info('User %s with its channel and account registered.', body.username)
170 }
171
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)
175
176   return res.json(user.toFormattedJSON())
177 }
178
179 function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
180   return res.json(res.locals.user.toFormattedJSON())
181 }
182
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
186
187   const ratingObj = await db.AccountVideoRate.load(accountId, videoId, null)
188   const rating = ratingObj ? ratingObj.type : 'none'
189
190   const json: FormattedUserVideoRate = {
191     videoId,
192     rating
193   }
194   res.json(json)
195 }
196
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)
199
200   return res.json(getFormattedObjects(resultList.data, resultList.total))
201 }
202
203 async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
204   const user = await db.User.loadById(req.params.id)
205
206   await user.destroy()
207
208   return res.sendStatus(204)
209 }
210
211 async function updateMe (req: express.Request, res: express.Response, next: express.NextFunction) {
212   const body: UserUpdateMe = req.body
213
214   // FIXME: user is not already a Sequelize instance?
215   const user = res.locals.oauth.token.user
216
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
220
221   await user.save()
222
223   return res.sendStatus(204)
224 }
225
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
229
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
233
234   await user.save()
235
236   return res.sendStatus(204)
237 }
238
239 function success (req: express.Request, res: express.Response, next: express.NextFunction) {
240   res.end()
241 }