]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/users.ts
Add blacklist reason field
[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,
26b7305a 204 req.query.sort as VideoSortField
0883b324 205 )
fd45e8f4 206
2baea0c7
C
207 const additionalAttributes = {
208 waitTranscoding: true,
209 state: true,
26b7305a
C
210 scheduledUpdate: true,
211 blacklistInfo: true
2baea0c7 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
eacb25c4 305 const reason = req.body.reason
e6921918 306
eacb25c4 307 await changeUserBlock(res, user, true, reason)
e6921918
C
308
309 return res.status(204).end()
310}
311
8094a898 312function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
ce5496d6 313 return res.json((res.locals.user as UserModel).toFormattedJSON())
8094a898
C
314}
315
eb080476 316async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) {
0a6658fd 317 const videoId = +req.params.videoId
571389d4 318 const accountId = +res.locals.oauth.token.User.Account.id
d38b8281 319
3fd3ab2d 320 const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null)
faab3a84
C
321 const rating = ratingObj ? ratingObj.type : 'none'
322
323 const json: FormattedUserVideoRate = {
324 videoId,
325 rating
326 }
327 res.json(json)
d38b8281
C
328}
329
eb080476 330async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
3fd3ab2d 331 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort)
eb080476
C
332
333 return res.json(getFormattedObjects(resultList.data, resultList.total))
9bd26629
C
334}
335
92b9d60c
C
336async function deleteMe (req: express.Request, res: express.Response) {
337 const user: UserModel = res.locals.oauth.token.User
338
339 await user.destroy()
340
341 auditLogger.delete(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new UserAuditView(user.toFormattedJSON()))
342
343 return res.sendStatus(204)
344}
345
eb080476 346async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
92b9d60c 347 const user: UserModel = res.locals.user
eb080476
C
348
349 await user.destroy()
350
80e36cd9
AB
351 auditLogger.delete(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new UserAuditView(user.toFormattedJSON()))
352
eb080476 353 return res.sendStatus(204)
9bd26629
C
354}
355
eb080476 356async function updateMe (req: express.Request, res: express.Response, next: express.NextFunction) {
8094a898 357 const body: UserUpdateMe = req.body
4771e000 358
2422c46b 359 const user: UserModel = res.locals.oauth.token.user
80e36cd9 360 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
1d49e1e2 361
eb080476
C
362 if (body.password !== undefined) user.password = body.password
363 if (body.email !== undefined) user.email = body.email
0883b324 364 if (body.nsfwPolicy !== undefined) user.nsfwPolicy = body.nsfwPolicy
7efe153b 365 if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo
eb080476 366
2422c46b
C
367 await sequelizeTypescript.transaction(async t => {
368 await user.save({ transaction: t })
369
ed56ad11 370 if (body.displayName !== undefined) user.Account.name = body.displayName
2422c46b
C
371 if (body.description !== undefined) user.Account.description = body.description
372 await user.Account.save({ transaction: t })
373
374 await sendUpdateActor(user.Account, t)
80e36cd9
AB
375
376 auditLogger.update(
377 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
378 new UserAuditView(user.toFormattedJSON()),
379 oldUserAuditView
380 )
2422c46b 381 })
eb080476 382
d412e80e 383 return res.sendStatus(204)
9bd26629
C
384}
385
c5911fd3 386async function updateMyAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
2186386c 387 const avatarPhysicalFile = req.files[ 'avatarfile' ][ 0 ]
80e36cd9
AB
388 const user: UserModel = res.locals.oauth.token.user
389 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
390 const account = user.Account
c5911fd3 391
4bbfc6c6 392 const avatar = await updateActorAvatarFile(avatarPhysicalFile, account.Actor, account)
c5911fd3 393
80e36cd9
AB
394 auditLogger.update(
395 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
396 new UserAuditView(user.toFormattedJSON()),
397 oldUserAuditView
398 )
399
c5911fd3
C
400 return res
401 .json({
402 avatar: avatar.toFormattedJSON()
403 })
404 .end()
405}
406
eb080476 407async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) {
8094a898 408 const body: UserUpdate = req.body
80e36cd9
AB
409 const userToUpdate = res.locals.user as UserModel
410 const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON())
411 const roleChanged = body.role !== undefined && body.role !== userToUpdate.role
8094a898 412
80e36cd9
AB
413 if (body.email !== undefined) userToUpdate.email = body.email
414 if (body.videoQuota !== undefined) userToUpdate.videoQuota = body.videoQuota
415 if (body.role !== undefined) userToUpdate.role = body.role
8094a898 416
80e36cd9 417 const user = await userToUpdate.save()
eb080476 418
f8b8c36b
C
419 // Destroy user token to refresh rights
420 if (roleChanged) {
80e36cd9 421 await OAuthTokenModel.deleteUserToken(userToUpdate.id)
f8b8c36b
C
422 }
423
80e36cd9
AB
424 auditLogger.update(
425 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
426 new UserAuditView(user.toFormattedJSON()),
427 oldUserAuditView
428 )
429
265ba139
C
430 // Don't need to send this update to followers, these attributes are not propagated
431
eb080476 432 return res.sendStatus(204)
8094a898
C
433}
434
ecb4e35f
C
435async function askResetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
436 const user = res.locals.user as UserModel
437
438 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
439 const url = CONFIG.WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
440 await Emailer.Instance.addForgetPasswordEmailJob(user.email, url)
441
442 return res.status(204).end()
443}
444
445async function resetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
446 const user = res.locals.user as UserModel
447 user.password = req.body.password
448
449 await user.save()
450
451 return res.status(204).end()
452}
453
69818c93 454function success (req: express.Request, res: express.Response, next: express.NextFunction) {
9457bf88
C
455 res.end()
456}
e6921918 457
eacb25c4 458async function changeUserBlock (res: express.Response, user: UserModel, block: boolean, reason?: string) {
e6921918
C
459 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
460
461 user.blocked = block
eacb25c4 462 user.blockedReason = reason || null
e6921918
C
463
464 await sequelizeTypescript.transaction(async t => {
465 await OAuthTokenModel.deleteUserToken(user.id, t)
466
467 await user.save({ transaction: t })
468 })
469
eacb25c4
C
470 await Emailer.Instance.addUserBlockJob(user, block, reason)
471
e6921918
C
472 auditLogger.update(
473 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
474 new UserAuditView(user.toFormattedJSON()),
475 oldUserAuditView
476 )
477}