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