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