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