]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/users.ts
Add avatar max size limit
[github/Chocobozzz/PeerTube.git] / server / controllers / api / users.ts
CommitLineData
4d4e5cd4 1import * as express from 'express'
c5911fd3
C
2import { extname, join } from 'path'
3import * as uuidv4 from 'uuid/v4'
571389d4 4import { UserCreate, UserRight, UserRole, UserUpdate, UserUpdateMe, UserVideoRate as FormattedUserVideoRate } from '../../../shared'
c5911fd3 5import { renamePromise } from '../../helpers/core-utils'
da854ddd
C
6import { retryTransactionWrapper } from '../../helpers/database-utils'
7import { logger } from '../../helpers/logger'
c5911fd3
C
8import { createReqFiles, getFormattedObjects } from '../../helpers/utils'
9import { AVATAR_MIMETYPE_EXT, CONFIG, sequelizeTypescript } from '../../initializers'
50d6de9c 10import { createUserAccountAndChannel } from '../../lib/user'
65fcc311 11import {
da854ddd
C
12 asyncMiddleware, authenticate, ensureUserHasRight, ensureUserRegistrationAllowed, paginationValidator, setPagination, setUsersSort,
13 setVideosSort, token, usersAddValidator, usersGetValidator, usersRegisterValidator, usersRemoveValidator, usersSortValidator,
14 usersUpdateMeValidator, usersUpdateValidator, usersVideoRatingValidator
65fcc311 15} from '../../middlewares'
c5911fd3 16import { usersUpdateMyAvatarValidator, videosSortValidator } from '../../middlewares/validators'
3fd3ab2d
C
17import { AccountVideoRateModel } from '../../models/account/account-video-rate'
18import { UserModel } from '../../models/account/user'
c5911fd3 19import { AvatarModel } from '../../models/avatar/avatar'
3fd3ab2d 20import { VideoModel } from '../../models/video/video'
65fcc311 21
c5911fd3
C
22const reqAvatarFile = createReqFiles('avatarfile', CONFIG.STORAGE.AVATARS_DIR, AVATAR_MIMETYPE_EXT)
23
65fcc311
C
24const usersRouter = express.Router()
25
26usersRouter.get('/me',
27 authenticate,
eb080476 28 asyncMiddleware(getUserInformation)
d38b8281
C
29)
30
fd45e8f4
C
31usersRouter.get('/me/videos',
32 authenticate,
33 paginationValidator,
34 videosSortValidator,
35 setVideosSort,
36 setPagination,
37 asyncMiddleware(getUserVideos)
38)
39
65fcc311
C
40usersRouter.get('/me/videos/:videoId/rating',
41 authenticate,
a2431b7d 42 asyncMiddleware(usersVideoRatingValidator),
eb080476 43 asyncMiddleware(getUserVideoRating)
d38b8281 44)
9bd26629 45
65fcc311 46usersRouter.get('/',
86d13ec2
C
47 authenticate,
48 ensureUserHasRight(UserRight.MANAGE_USERS),
65fcc311
C
49 paginationValidator,
50 usersSortValidator,
51 setUsersSort,
52 setPagination,
eb080476 53 asyncMiddleware(listUsers)
5c39adb7
C
54)
55
8094a898 56usersRouter.get('/:id',
a2431b7d 57 asyncMiddleware(usersGetValidator),
8094a898
C
58 getUser
59)
60
65fcc311
C
61usersRouter.post('/',
62 authenticate,
954605a8 63 ensureUserHasRight(UserRight.MANAGE_USERS),
a2431b7d
C
64 asyncMiddleware(usersAddValidator),
65 asyncMiddleware(createUserRetryWrapper)
9bd26629
C
66)
67
65fcc311 68usersRouter.post('/register',
a2431b7d
C
69 asyncMiddleware(ensureUserRegistrationAllowed),
70 asyncMiddleware(usersRegisterValidator),
47e0652b 71 asyncMiddleware(registerUserRetryWrapper)
2c2e9092
C
72)
73
8094a898
C
74usersRouter.put('/me',
75 authenticate,
76 usersUpdateMeValidator,
eb080476 77 asyncMiddleware(updateMe)
8094a898
C
78)
79
c5911fd3
C
80usersRouter.post('/me/avatar/pick',
81 authenticate,
82 reqAvatarFile,
83 usersUpdateMyAvatarValidator,
84 asyncMiddleware(updateMyAvatar)
85)
86
65fcc311
C
87usersRouter.put('/:id',
88 authenticate,
954605a8 89 ensureUserHasRight(UserRight.MANAGE_USERS),
a2431b7d 90 asyncMiddleware(usersUpdateValidator),
eb080476 91 asyncMiddleware(updateUser)
9bd26629
C
92)
93
65fcc311
C
94usersRouter.delete('/:id',
95 authenticate,
954605a8 96 ensureUserHasRight(UserRight.MANAGE_USERS),
a2431b7d 97 asyncMiddleware(usersRemoveValidator),
eb080476 98 asyncMiddleware(removeUser)
9bd26629 99)
6606150c 100
65fcc311 101usersRouter.post('/token', token, success)
9bd26629 102// TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
9457bf88
C
103
104// ---------------------------------------------------------------------------
105
65fcc311
C
106export {
107 usersRouter
108}
9457bf88
C
109
110// ---------------------------------------------------------------------------
111
fd45e8f4 112async function getUserVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
3fd3ab2d
C
113 const user = res.locals.oauth.token.User as UserModel
114 const resultList = await VideoModel.listUserVideosForApi(user.id ,req.query.start, req.query.count, req.query.sort)
fd45e8f4
C
115
116 return res.json(getFormattedObjects(resultList.data, resultList.total))
117}
118
eb080476 119async function createUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
72c7248b 120 const options = {
47e0652b 121 arguments: [ req ],
72c7248b
C
122 errorMessage: 'Cannot insert the user with many retries.'
123 }
124
eb080476
C
125 await retryTransactionWrapper(createUser, options)
126
127 // TODO : include Location of the new user -> 201
128 return res.type('json').status(204).end()
72c7248b
C
129}
130
47e0652b 131async function createUser (req: express.Request) {
4771e000 132 const body: UserCreate = req.body
3fd3ab2d 133 const user = new UserModel({
4771e000
C
134 username: body.username,
135 password: body.password,
136 email: body.email,
1d49e1e2 137 displayNSFW: false,
7efe153b 138 autoPlayVideo: true,
954605a8 139 role: body.role,
b0f9f39e 140 videoQuota: body.videoQuota
9bd26629
C
141 })
142
38fa2065 143 await createUserAccountAndChannel(user)
eb080476 144
38fa2065 145 logger.info('User %s with its channel and account created.', body.username)
9bd26629
C
146}
147
47e0652b
C
148async function registerUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
149 const options = {
150 arguments: [ req ],
151 errorMessage: 'Cannot insert the user with many retries.'
152 }
153
154 await retryTransactionWrapper(registerUser, options)
155
156 return res.type('json').status(204).end()
157}
158
159async function registerUser (req: express.Request) {
77a5501f
C
160 const body: UserCreate = req.body
161
3fd3ab2d 162 const user = new UserModel({
77a5501f
C
163 username: body.username,
164 password: body.password,
165 email: body.email,
166 displayNSFW: false,
7efe153b 167 autoPlayVideo: true,
954605a8 168 role: UserRole.USER,
77a5501f
C
169 videoQuota: CONFIG.USER.VIDEO_QUOTA
170 })
171
38fa2065 172 await createUserAccountAndChannel(user)
47e0652b
C
173
174 logger.info('User %s with its channel and account registered.', body.username)
77a5501f
C
175}
176
eb080476 177async function getUserInformation (req: express.Request, res: express.Response, next: express.NextFunction) {
fd45e8f4 178 // We did not load channels in res.locals.user
3fd3ab2d 179 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
eb080476
C
180
181 return res.json(user.toFormattedJSON())
99a64bfe
C
182}
183
8094a898 184function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
11474c3c 185 return res.json(res.locals.user.toFormattedJSON())
8094a898
C
186}
187
eb080476 188async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) {
0a6658fd 189 const videoId = +req.params.videoId
571389d4 190 const accountId = +res.locals.oauth.token.User.Account.id
d38b8281 191
3fd3ab2d 192 const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null)
faab3a84
C
193 const rating = ratingObj ? ratingObj.type : 'none'
194
195 const json: FormattedUserVideoRate = {
196 videoId,
197 rating
198 }
199 res.json(json)
d38b8281
C
200}
201
eb080476 202async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
3fd3ab2d 203 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort)
eb080476
C
204
205 return res.json(getFormattedObjects(resultList.data, resultList.total))
9bd26629
C
206}
207
eb080476 208async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
3fd3ab2d 209 const user = await UserModel.loadById(req.params.id)
eb080476
C
210
211 await user.destroy()
212
213 return res.sendStatus(204)
9bd26629
C
214}
215
eb080476 216async function updateMe (req: express.Request, res: express.Response, next: express.NextFunction) {
8094a898 217 const body: UserUpdateMe = req.body
4771e000 218
8094a898 219 // FIXME: user is not already a Sequelize instance?
eb080476 220 const user = res.locals.oauth.token.user
1d49e1e2 221
eb080476
C
222 if (body.password !== undefined) user.password = body.password
223 if (body.email !== undefined) user.email = body.email
224 if (body.displayNSFW !== undefined) user.displayNSFW = body.displayNSFW
7efe153b 225 if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo
eb080476
C
226
227 await user.save()
228
d412e80e 229 return res.sendStatus(204)
9bd26629
C
230}
231
c5911fd3
C
232async function updateMyAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
233 const avatarPhysicalFile = req.files['avatarfile'][0]
234 const actor = res.locals.oauth.token.user.Account.Actor
235
236 const avatarDir = CONFIG.STORAGE.AVATARS_DIR
237 const source = join(avatarDir, avatarPhysicalFile.filename)
238 const extension = extname(avatarPhysicalFile.filename)
239 const avatarName = uuidv4() + extension
240 const destination = join(avatarDir, avatarName)
241
242 await renamePromise(source, destination)
243
244 const { avatar } = await sequelizeTypescript.transaction(async t => {
245 const avatar = await AvatarModel.create({
246 filename: avatarName
247 }, { transaction: t })
248
249 if (actor.Avatar) {
250 await actor.Avatar.destroy({ transaction: t })
251 }
252
253 actor.set('avatarId', avatar.id)
254 await actor.save({ transaction: t })
255
256 return { actor, avatar }
257 })
258
259 return res
260 .json({
261 avatar: avatar.toFormattedJSON()
262 })
263 .end()
264}
265
eb080476 266async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) {
8094a898 267 const body: UserUpdate = req.body
3fd3ab2d 268 const user = res.locals.user as UserModel
8094a898
C
269
270 if (body.email !== undefined) user.email = body.email
271 if (body.videoQuota !== undefined) user.videoQuota = body.videoQuota
954605a8 272 if (body.role !== undefined) user.role = body.role
8094a898 273
eb080476
C
274 await user.save()
275
276 return res.sendStatus(204)
8094a898
C
277}
278
69818c93 279function success (req: express.Request, res: express.Response, next: express.NextFunction) {
9457bf88
C
280 res.end()
281}