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