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