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