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