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