]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/controllers/api/users.ts
feature: IP filtering on signup page
[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 { retryTransactionWrapper } from '../../helpers/database-utils'
8import { processImage } from '../../helpers/image-utils'
9import { logger } from '../../helpers/logger'
10import { getFormattedObjects } from '../../helpers/utils'
11import { AVATARS_SIZE, CONFIG, IMAGE_MIMETYPE_EXT, RATES_LIMIT, sequelizeTypescript } from '../../initializers'
12import { updateActorAvatarInstance } from '../../lib/activitypub'
13import { sendUpdateActor } from '../../lib/activitypub/send'
14import { Emailer } from '../../lib/emailer'
15import { Redis } from '../../lib/redis'
16import { createUserAccountAndChannel } from '../../lib/user'
17import {
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'
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 asyncMiddleware(createUserRetryWrapper)
106)
107
108usersRouter.post('/register',
109 asyncMiddleware(ensureUserRegistrationAllowed),
110 ensureUserRegistrationAllowedForIP,
111 asyncMiddleware(usersRegisterValidator),
112 asyncMiddleware(registerUserRetryWrapper)
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.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 )
176
177 return res.json(getFormattedObjects(resultList.data, resultList.total))
178}
179
180async function createUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
181 const options = {
182 arguments: [ req ],
183 errorMessage: 'Cannot insert the user with many retries.'
184 }
185
186 const { user, account } = await retryTransactionWrapper(createUser, options)
187
188 return res.json({
189 user: {
190 id: user.id,
191 account: {
192 id: account.id,
193 uuid: account.Actor.uuid
194 }
195 }
196 }).end()
197}
198
199async function createUser (req: express.Request) {
200 const body: UserCreate = req.body
201 const userToCreate = new UserModel({
202 username: body.username,
203 password: body.password,
204 email: body.email,
205 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
206 autoPlayVideo: true,
207 role: body.role,
208 videoQuota: body.videoQuota
209 })
210
211 const { user, account } = await createUserAccountAndChannel(userToCreate)
212
213 logger.info('User %s with its channel and account created.', body.username)
214
215 return { user, account }
216}
217
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) {
230 const body: UserCreate = req.body
231
232 const user = new UserModel({
233 username: body.username,
234 password: body.password,
235 email: body.email,
236 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
237 autoPlayVideo: true,
238 role: UserRole.USER,
239 videoQuota: CONFIG.USER.VIDEO_QUOTA
240 })
241
242 await createUserAccountAndChannel(user)
243
244 logger.info('User %s with its channel and account registered.', body.username)
245}
246
247async function getUserInformation (req: express.Request, res: express.Response, next: express.NextFunction) {
248 // We did not load channels in res.locals.user
249 const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
250
251 return res.json(user.toFormattedJSON())
252}
253
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
259 const data: UserVideoQuota = {
260 videoQuotaUsed
261 }
262 return res.json(data)
263}
264
265function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
266 return res.json((res.locals.user as UserModel).toFormattedJSON())
267}
268
269async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) {
270 const videoId = +req.params.videoId
271 const accountId = +res.locals.oauth.token.User.Account.id
272
273 const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null)
274 const rating = ratingObj ? ratingObj.type : 'none'
275
276 const json: FormattedUserVideoRate = {
277 videoId,
278 rating
279 }
280 res.json(json)
281}
282
283async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
284 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort)
285
286 return res.json(getFormattedObjects(resultList.data, resultList.total))
287}
288
289async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
290 const user = await UserModel.loadById(req.params.id)
291
292 await user.destroy()
293
294 return res.sendStatus(204)
295}
296
297async function updateMe (req: express.Request, res: express.Response, next: express.NextFunction) {
298 const body: UserUpdateMe = req.body
299
300 const user: UserModel = res.locals.oauth.token.user
301
302 if (body.password !== undefined) user.password = body.password
303 if (body.email !== undefined) user.email = body.email
304 if (body.nsfwPolicy !== undefined) user.nsfwPolicy = body.nsfwPolicy
305 if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo
306
307 await sequelizeTypescript.transaction(async t => {
308 await user.save({ transaction: t })
309
310 if (body.displayName !== undefined) user.Account.name = body.displayName
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 })
316
317 return res.sendStatus(204)
318}
319
320async function updateMyAvatar (req: express.Request, res: express.Response, next: express.NextFunction) {
321 const avatarPhysicalFile = req.files['avatarfile'][0]
322 const user = res.locals.oauth.token.user
323 const actor = user.Account.Actor
324
325 const extension = extname(avatarPhysicalFile.filename)
326 const avatarName = uuidv4() + extension
327 const destination = join(CONFIG.STORAGE.AVATARS_DIR, avatarName)
328 await processImage(avatarPhysicalFile, destination, AVATARS_SIZE)
329
330 const avatar = await sequelizeTypescript.transaction(async t => {
331 const updatedActor = await updateActorAvatarInstance(actor, avatarName, t)
332 await updatedActor.save({ transaction: t })
333
334 await sendUpdateActor(user.Account, t)
335
336 return updatedActor.Avatar
337 })
338
339 return res
340 .json({
341 avatar: avatar.toFormattedJSON()
342 })
343 .end()
344}
345
346async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) {
347 const body: UserUpdate = req.body
348 const user = res.locals.user as UserModel
349 const roleChanged = body.role !== undefined && body.role !== user.role
350
351 if (body.email !== undefined) user.email = body.email
352 if (body.videoQuota !== undefined) user.videoQuota = body.videoQuota
353 if (body.role !== undefined) user.role = body.role
354
355 await user.save()
356
357 // Destroy user token to refresh rights
358 if (roleChanged) {
359 await OAuthTokenModel.deleteUserToken(user.id)
360 }
361
362 // Don't need to send this update to followers, these attributes are not propagated
363
364 return res.sendStatus(204)
365}
366
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
386function success (req: express.Request, res: express.Response, next: express.NextFunction) {
387 res.end()
388}