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