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