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