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