]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/users.ts
Implement support field in video and video channel
[github/Chocobozzz/PeerTube.git] / server / controllers / api / users.ts
1 import * as express from 'express'
2 import 'multer'
3 import { extname, join } from 'path'
4 import * as uuidv4 from 'uuid/v4'
5 import { UserCreate, UserRight, UserRole, UserUpdate, UserUpdateMe, UserVideoRate as FormattedUserVideoRate } from '../../../shared'
6 import { retryTransactionWrapper } from '../../helpers/database-utils'
7 import { processImage } from '../../helpers/image-utils'
8 import { logger } from '../../helpers/logger'
9 import { createReqFiles, getFormattedObjects } from '../../helpers/utils'
10 import { AVATARS_SIZE, CONFIG, IMAGE_MIMETYPE_EXT, sequelizeTypescript } from '../../initializers'
11 import { updateActorAvatarInstance } from '../../lib/activitypub'
12 import { sendUpdateActor } from '../../lib/activitypub/send'
13 import { Emailer } from '../../lib/emailer'
14 import { Redis } from '../../lib/redis'
15 import { createUserAccountAndChannel } from '../../lib/user'
16 import {
17 asyncMiddleware,
18 authenticate,
19 ensureUserHasRight,
20 ensureUserRegistrationAllowed,
21 paginationValidator,
22 setDefaultPagination,
23 setDefaultSort,
24 token,
25 usersAddValidator,
26 usersGetValidator,
27 usersRegisterValidator,
28 usersRemoveValidator,
29 usersSortValidator,
30 usersUpdateMeValidator,
31 usersUpdateValidator,
32 usersVideoRatingValidator
33 } from '../../middlewares'
34 import {
35 usersAskResetPasswordValidator,
36 usersResetPasswordValidator,
37 usersUpdateMyAvatarValidator,
38 videosSortValidator
39 } from '../../middlewares/validators'
40 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
41 import { UserModel } from '../../models/account/user'
42 import { OAuthTokenModel } from '../../models/oauth/oauth-token'
43 import { VideoModel } from '../../models/video/video'
44
45 const reqAvatarFile = createReqFiles([ 'avatarfile' ], IMAGE_MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.AVATARS_DIR })
46
47 const usersRouter = express.Router()
48
49 usersRouter.get('/me',
50 authenticate,
51 asyncMiddleware(getUserInformation)
52 )
53
54 usersRouter.get('/me/video-quota-used',
55 authenticate,
56 asyncMiddleware(getUserVideoQuotaUsed)
57 )
58
59 usersRouter.get('/me/videos',
60 authenticate,
61 paginationValidator,
62 videosSortValidator,
63 setDefaultSort,
64 setDefaultPagination,
65 asyncMiddleware(getUserVideos)
66 )
67
68 usersRouter.get('/me/videos/:videoId/rating',
69 authenticate,
70 asyncMiddleware(usersVideoRatingValidator),
71 asyncMiddleware(getUserVideoRating)
72 )
73
74 usersRouter.get('/',
75 authenticate,
76 ensureUserHasRight(UserRight.MANAGE_USERS),
77 paginationValidator,
78 usersSortValidator,
79 setDefaultSort,
80 setDefaultPagination,
81 asyncMiddleware(listUsers)
82 )
83
84 usersRouter.get('/:id',
85 asyncMiddleware(usersGetValidator),
86 getUser
87 )
88
89 usersRouter.post('/',
90 authenticate,
91 ensureUserHasRight(UserRight.MANAGE_USERS),
92 asyncMiddleware(usersAddValidator),
93 asyncMiddleware(createUserRetryWrapper)
94 )
95
96 usersRouter.post('/register',
97 asyncMiddleware(ensureUserRegistrationAllowed),
98 asyncMiddleware(usersRegisterValidator),
99 asyncMiddleware(registerUserRetryWrapper)
100 )
101
102 usersRouter.put('/me',
103 authenticate,
104 usersUpdateMeValidator,
105 asyncMiddleware(updateMe)
106 )
107
108 usersRouter.post('/me/avatar/pick',
109 authenticate,
110 reqAvatarFile,
111 usersUpdateMyAvatarValidator,
112 asyncMiddleware(updateMyAvatar)
113 )
114
115 usersRouter.put('/:id',
116 authenticate,
117 ensureUserHasRight(UserRight.MANAGE_USERS),
118 asyncMiddleware(usersUpdateValidator),
119 asyncMiddleware(updateUser)
120 )
121
122 usersRouter.delete('/:id',
123 authenticate,
124 ensureUserHasRight(UserRight.MANAGE_USERS),
125 asyncMiddleware(usersRemoveValidator),
126 asyncMiddleware(removeUser)
127 )
128
129 usersRouter.post('/ask-reset-password',
130 asyncMiddleware(usersAskResetPasswordValidator),
131 asyncMiddleware(askResetUserPassword)
132 )
133
134 usersRouter.post('/:id/reset-password',
135 asyncMiddleware(usersResetPasswordValidator),
136 asyncMiddleware(resetUserPassword)
137 )
138
139 usersRouter.post('/token', token, success)
140 // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
141
142 // ---------------------------------------------------------------------------
143
144 export {
145 usersRouter
146 }
147
148 // ---------------------------------------------------------------------------
149
150 async function getUserVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
151 const user = res.locals.oauth.token.User as UserModel
152 const resultList = await VideoModel.listUserVideosForApi(user.id ,req.query.start, req.query.count, req.query.sort)
153
154 return res.json(getFormattedObjects(resultList.data, resultList.total))
155 }
156
157 async function createUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
158 const options = {
159 arguments: [ req ],
160 errorMessage: 'Cannot insert the user with many retries.'
161 }
162
163 const { user, account } = await retryTransactionWrapper(createUser, options)
164
165 return res.json({
166 user: {
167 id: user.id,
168 uuid: account.uuid
169 }
170 }).end()
171 }
172
173 async function createUser (req: express.Request) {
174 const body: UserCreate = req.body
175 const userToCreate = new UserModel({
176 username: body.username,
177 password: body.password,
178 email: body.email,
179 displayNSFW: false,
180 autoPlayVideo: true,
181 role: body.role,
182 videoQuota: body.videoQuota
183 })
184
185 const { user, account } = await createUserAccountAndChannel(userToCreate)
186
187 logger.info('User %s with its channel and account created.', body.username)
188
189 return { user, account }
190 }
191
192 async function registerUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
193 const options = {
194 arguments: [ req ],
195 errorMessage: 'Cannot insert the user with many retries.'
196 }
197
198 await retryTransactionWrapper(registerUser, options)
199
200 return res.type('json').status(204).end()
201 }
202
203 async function registerUser (req: express.Request) {
204 const body: UserCreate = req.body
205
206 const user = new UserModel({
207 username: body.username,
208 password: body.password,
209 email: body.email,
210 displayNSFW: false,
211 autoPlayVideo: true,
212 role: UserRole.USER,
213 videoQuota: CONFIG.USER.VIDEO_QUOTA
214 })
215
216 await createUserAccountAndChannel(user)
217
218 logger.info('User %s with its channel and account registered.', body.username)
219 }
220
221 async function getUserInformation (req: express.Request, res: express.Response, next: express.NextFunction) {
222 // We did not load channels in res.locals.user
223 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
224
225 return res.json(user.toFormattedJSON())
226 }
227
228 async function getUserVideoQuotaUsed (req: express.Request, res: express.Response, next: express.NextFunction) {
229 // We did not load channels in res.locals.user
230 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
231 const videoQuotaUsed = await UserModel.getOriginalVideoFileTotalFromUser(user)
232
233 return res.json({
234 videoQuotaUsed
235 })
236 }
237
238 function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
239 return res.json((res.locals.user as UserModel).toFormattedJSON())
240 }
241
242 async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) {
243 const videoId = +req.params.videoId
244 const accountId = +res.locals.oauth.token.User.Account.id
245
246 const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null)
247 const rating = ratingObj ? ratingObj.type : 'none'
248
249 const json: FormattedUserVideoRate = {
250 videoId,
251 rating
252 }
253 res.json(json)
254 }
255
256 async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
257 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort)
258
259 return res.json(getFormattedObjects(resultList.data, resultList.total))
260 }
261
262 async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
263 const user = await UserModel.loadById(req.params.id)
264
265 await user.destroy()
266
267 return res.sendStatus(204)
268 }
269
270 async function updateMe (req: express.Request, res: express.Response, next: express.NextFunction) {
271 const body: UserUpdateMe = req.body
272
273 const user: UserModel = res.locals.oauth.token.user
274
275 if (body.password !== undefined) user.password = body.password
276 if (body.email !== undefined) user.email = body.email
277 if (body.displayNSFW !== undefined) user.displayNSFW = body.displayNSFW
278 if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo
279
280 await sequelizeTypescript.transaction(async t => {
281 await user.save({ transaction: t })
282
283 if (body.description !== undefined) user.Account.description = body.description
284 await user.Account.save({ transaction: t })
285
286 await sendUpdateActor(user.Account, t)
287 })
288
289 return res.sendStatus(204)
290 }
291
292 async function updateMyAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
293 const avatarPhysicalFile = req.files['avatarfile'][0]
294 const user = res.locals.oauth.token.user
295 const actor = user.Account.Actor
296
297 const extension = extname(avatarPhysicalFile.filename)
298 const avatarName = uuidv4() + extension
299 const destination = join(CONFIG.STORAGE.AVATARS_DIR, avatarName)
300 await processImage(avatarPhysicalFile, destination, AVATARS_SIZE)
301
302 const avatar = await sequelizeTypescript.transaction(async t => {
303 const updatedActor = await updateActorAvatarInstance(actor, avatarName, t)
304 await updatedActor.save({ transaction: t })
305
306 await sendUpdateActor(user.Account, t)
307
308 return updatedActor.Avatar
309 })
310
311 return res
312 .json({
313 avatar: avatar.toFormattedJSON()
314 })
315 .end()
316 }
317
318 async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) {
319 const body: UserUpdate = req.body
320 const user = res.locals.user as UserModel
321 const roleChanged = body.role !== undefined && body.role !== user.role
322
323 if (body.email !== undefined) user.email = body.email
324 if (body.videoQuota !== undefined) user.videoQuota = body.videoQuota
325 if (body.role !== undefined) user.role = body.role
326
327 await user.save()
328
329 // Destroy user token to refresh rights
330 if (roleChanged) {
331 await OAuthTokenModel.deleteUserToken(user.id)
332 }
333
334 // Don't need to send this update to followers, these attributes are not propagated
335
336 return res.sendStatus(204)
337 }
338
339 async function askResetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
340 const user = res.locals.user as UserModel
341
342 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
343 const url = CONFIG.WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
344 await Emailer.Instance.addForgetPasswordEmailJob(user.email, url)
345
346 return res.status(204).end()
347 }
348
349 async function resetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
350 const user = res.locals.user as UserModel
351 user.password = req.body.password
352
353 await user.save()
354
355 return res.status(204).end()
356 }
357
358 function success (req: express.Request, res: express.Response, next: express.NextFunction) {
359 res.end()
360 }