]>
Commit | Line | Data |
---|---|---|
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 | account: { | |
189 | id: account.id, | |
190 | uuid: account.Actor.uuid | |
191 | } | |
192 | } | |
193 | }).end() | |
194 | } | |
195 | ||
196 | async function createUser (req: express.Request) { | |
197 | const body: UserCreate = req.body | |
198 | const userToCreate = new UserModel({ | |
199 | username: body.username, | |
200 | password: body.password, | |
201 | email: body.email, | |
202 | nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY, | |
203 | autoPlayVideo: true, | |
204 | role: body.role, | |
205 | videoQuota: body.videoQuota | |
206 | }) | |
207 | ||
208 | const { user, account } = await createUserAccountAndChannel(userToCreate) | |
209 | ||
210 | logger.info('User %s with its channel and account created.', body.username) | |
211 | ||
212 | return { user, account } | |
213 | } | |
214 | ||
215 | async function registerUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) { | |
216 | const options = { | |
217 | arguments: [ req ], | |
218 | errorMessage: 'Cannot insert the user with many retries.' | |
219 | } | |
220 | ||
221 | await retryTransactionWrapper(registerUser, options) | |
222 | ||
223 | return res.type('json').status(204).end() | |
224 | } | |
225 | ||
226 | async function registerUser (req: express.Request) { | |
227 | const body: UserCreate = req.body | |
228 | ||
229 | const user = new UserModel({ | |
230 | username: body.username, | |
231 | password: body.password, | |
232 | email: body.email, | |
233 | nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY, | |
234 | autoPlayVideo: true, | |
235 | role: UserRole.USER, | |
236 | videoQuota: CONFIG.USER.VIDEO_QUOTA | |
237 | }) | |
238 | ||
239 | await createUserAccountAndChannel(user) | |
240 | ||
241 | logger.info('User %s with its channel and account registered.', body.username) | |
242 | } | |
243 | ||
244 | async function getUserInformation (req: express.Request, res: express.Response, next: express.NextFunction) { | |
245 | // We did not load channels in res.locals.user | |
246 | const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username) | |
247 | ||
248 | return res.json(user.toFormattedJSON()) | |
249 | } | |
250 | ||
251 | async function getUserVideoQuotaUsed (req: express.Request, res: express.Response, next: express.NextFunction) { | |
252 | // We did not load channels in res.locals.user | |
253 | const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username) | |
254 | const videoQuotaUsed = await UserModel.getOriginalVideoFileTotalFromUser(user) | |
255 | ||
256 | return res.json({ | |
257 | videoQuotaUsed | |
258 | }) | |
259 | } | |
260 | ||
261 | function getUser (req: express.Request, res: express.Response, next: express.NextFunction) { | |
262 | return res.json((res.locals.user as UserModel).toFormattedJSON()) | |
263 | } | |
264 | ||
265 | async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) { | |
266 | const videoId = +req.params.videoId | |
267 | const accountId = +res.locals.oauth.token.User.Account.id | |
268 | ||
269 | const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null) | |
270 | const rating = ratingObj ? ratingObj.type : 'none' | |
271 | ||
272 | const json: FormattedUserVideoRate = { | |
273 | videoId, | |
274 | rating | |
275 | } | |
276 | res.json(json) | |
277 | } | |
278 | ||
279 | async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) { | |
280 | const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort) | |
281 | ||
282 | return res.json(getFormattedObjects(resultList.data, resultList.total)) | |
283 | } | |
284 | ||
285 | async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) { | |
286 | const user = await UserModel.loadById(req.params.id) | |
287 | ||
288 | await user.destroy() | |
289 | ||
290 | return res.sendStatus(204) | |
291 | } | |
292 | ||
293 | async function updateMe (req: express.Request, res: express.Response, next: express.NextFunction) { | |
294 | const body: UserUpdateMe = req.body | |
295 | ||
296 | const user: UserModel = res.locals.oauth.token.user | |
297 | ||
298 | if (body.password !== undefined) user.password = body.password | |
299 | if (body.email !== undefined) user.email = body.email | |
300 | if (body.nsfwPolicy !== undefined) user.nsfwPolicy = body.nsfwPolicy | |
301 | if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo | |
302 | ||
303 | await sequelizeTypescript.transaction(async t => { | |
304 | await user.save({ transaction: t }) | |
305 | ||
306 | if (body.displayName !== undefined) user.Account.name = body.displayName | |
307 | if (body.description !== undefined) user.Account.description = body.description | |
308 | await user.Account.save({ transaction: t }) | |
309 | ||
310 | await sendUpdateActor(user.Account, t) | |
311 | }) | |
312 | ||
313 | return res.sendStatus(204) | |
314 | } | |
315 | ||
316 | async function updateMyAvatar (req: express.Request, res: express.Response, next: express.NextFunction) { | |
317 | const avatarPhysicalFile = req.files['avatarfile'][0] | |
318 | const user = res.locals.oauth.token.user | |
319 | const actor = user.Account.Actor | |
320 | ||
321 | const extension = extname(avatarPhysicalFile.filename) | |
322 | const avatarName = uuidv4() + extension | |
323 | const destination = join(CONFIG.STORAGE.AVATARS_DIR, avatarName) | |
324 | await processImage(avatarPhysicalFile, destination, AVATARS_SIZE) | |
325 | ||
326 | const avatar = await sequelizeTypescript.transaction(async t => { | |
327 | const updatedActor = await updateActorAvatarInstance(actor, avatarName, t) | |
328 | await updatedActor.save({ transaction: t }) | |
329 | ||
330 | await sendUpdateActor(user.Account, t) | |
331 | ||
332 | return updatedActor.Avatar | |
333 | }) | |
334 | ||
335 | return res | |
336 | .json({ | |
337 | avatar: avatar.toFormattedJSON() | |
338 | }) | |
339 | .end() | |
340 | } | |
341 | ||
342 | async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) { | |
343 | const body: UserUpdate = req.body | |
344 | const user = res.locals.user as UserModel | |
345 | const roleChanged = body.role !== undefined && body.role !== user.role | |
346 | ||
347 | if (body.email !== undefined) user.email = body.email | |
348 | if (body.videoQuota !== undefined) user.videoQuota = body.videoQuota | |
349 | if (body.role !== undefined) user.role = body.role | |
350 | ||
351 | await user.save() | |
352 | ||
353 | // Destroy user token to refresh rights | |
354 | if (roleChanged) { | |
355 | await OAuthTokenModel.deleteUserToken(user.id) | |
356 | } | |
357 | ||
358 | // Don't need to send this update to followers, these attributes are not propagated | |
359 | ||
360 | return res.sendStatus(204) | |
361 | } | |
362 | ||
363 | async function askResetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) { | |
364 | const user = res.locals.user as UserModel | |
365 | ||
366 | const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id) | |
367 | const url = CONFIG.WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString | |
368 | await Emailer.Instance.addForgetPasswordEmailJob(user.email, url) | |
369 | ||
370 | return res.status(204).end() | |
371 | } | |
372 | ||
373 | async function resetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) { | |
374 | const user = res.locals.user as UserModel | |
375 | user.password = req.body.password | |
376 | ||
377 | await user.save() | |
378 | ||
379 | return res.status(204).end() | |
380 | } | |
381 | ||
382 | function success (req: express.Request, res: express.Response, next: express.NextFunction) { | |
383 | res.end() | |
384 | } |