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