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