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