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