]>
Commit | Line | Data |
---|---|---|
1 | import * as express from 'express' | |
2 | import * as RateLimit from 'express-rate-limit' | |
3 | import { UserCreate, UserRight, UserRole, UserUpdate } from '../../../../shared' | |
4 | import { logger } from '../../../helpers/logger' | |
5 | import { getFormattedObjects } from '../../../helpers/utils' | |
6 | import { CONFIG, RATES_LIMIT, sequelizeTypescript } from '../../../initializers' | |
7 | import { Emailer } from '../../../lib/emailer' | |
8 | import { Redis } from '../../../lib/redis' | |
9 | import { createUserAccountAndChannelAndPlaylist } from '../../../lib/user' | |
10 | import { | |
11 | asyncMiddleware, | |
12 | asyncRetryTransactionMiddleware, | |
13 | authenticate, | |
14 | ensureUserHasRight, | |
15 | ensureUserRegistrationAllowed, | |
16 | ensureUserRegistrationAllowedForIP, | |
17 | paginationValidator, | |
18 | setDefaultPagination, | |
19 | setDefaultSort, | |
20 | token, | |
21 | userAutocompleteValidator, | |
22 | usersAddValidator, | |
23 | usersGetValidator, | |
24 | usersRegisterValidator, | |
25 | usersRemoveValidator, | |
26 | usersSortValidator, | |
27 | usersUpdateValidator | |
28 | } from '../../../middlewares' | |
29 | import { | |
30 | usersAskResetPasswordValidator, | |
31 | usersAskSendVerifyEmailValidator, | |
32 | usersBlockingValidator, | |
33 | usersResetPasswordValidator, | |
34 | usersVerifyEmailValidator | |
35 | } from '../../../middlewares/validators' | |
36 | import { UserModel } from '../../../models/account/user' | |
37 | import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger' | |
38 | import { meRouter } from './me' | |
39 | import { deleteUserToken } from '../../../lib/oauth-model' | |
40 | import { myBlocklistRouter } from './my-blocklist' | |
41 | import { myVideoPlaylistsRouter } from './my-video-playlists' | |
42 | import { myVideosHistoryRouter } from './my-history' | |
43 | import { myNotificationsRouter } from './my-notifications' | |
44 | import { Notifier } from '../../../lib/notifier' | |
45 | import { mySubscriptionsRouter } from './my-subscriptions' | |
46 | ||
47 | const auditLogger = auditLoggerFactory('users') | |
48 | ||
49 | const loginRateLimiter = new RateLimit({ | |
50 | windowMs: RATES_LIMIT.LOGIN.WINDOW_MS, | |
51 | max: RATES_LIMIT.LOGIN.MAX | |
52 | }) | |
53 | ||
54 | const askSendEmailLimiter = new RateLimit({ | |
55 | windowMs: RATES_LIMIT.ASK_SEND_EMAIL.WINDOW_MS, | |
56 | max: RATES_LIMIT.ASK_SEND_EMAIL.MAX | |
57 | }) | |
58 | ||
59 | const usersRouter = express.Router() | |
60 | usersRouter.use('/', myNotificationsRouter) | |
61 | usersRouter.use('/', mySubscriptionsRouter) | |
62 | usersRouter.use('/', myBlocklistRouter) | |
63 | usersRouter.use('/', myVideosHistoryRouter) | |
64 | usersRouter.use('/', myVideoPlaylistsRouter) | |
65 | usersRouter.use('/', meRouter) | |
66 | ||
67 | usersRouter.get('/autocomplete', | |
68 | userAutocompleteValidator, | |
69 | asyncMiddleware(autocompleteUsers) | |
70 | ) | |
71 | ||
72 | usersRouter.get('/', | |
73 | authenticate, | |
74 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
75 | paginationValidator, | |
76 | usersSortValidator, | |
77 | setDefaultSort, | |
78 | setDefaultPagination, | |
79 | asyncMiddleware(listUsers) | |
80 | ) | |
81 | ||
82 | usersRouter.post('/:id/block', | |
83 | authenticate, | |
84 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
85 | asyncMiddleware(usersBlockingValidator), | |
86 | asyncMiddleware(blockUser) | |
87 | ) | |
88 | usersRouter.post('/:id/unblock', | |
89 | authenticate, | |
90 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
91 | asyncMiddleware(usersBlockingValidator), | |
92 | asyncMiddleware(unblockUser) | |
93 | ) | |
94 | ||
95 | usersRouter.get('/:id', | |
96 | authenticate, | |
97 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
98 | asyncMiddleware(usersGetValidator), | |
99 | getUser | |
100 | ) | |
101 | ||
102 | usersRouter.post('/', | |
103 | authenticate, | |
104 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
105 | asyncMiddleware(usersAddValidator), | |
106 | asyncRetryTransactionMiddleware(createUser) | |
107 | ) | |
108 | ||
109 | usersRouter.post('/register', | |
110 | asyncMiddleware(ensureUserRegistrationAllowed), | |
111 | ensureUserRegistrationAllowedForIP, | |
112 | asyncMiddleware(usersRegisterValidator), | |
113 | asyncRetryTransactionMiddleware(registerUser) | |
114 | ) | |
115 | ||
116 | usersRouter.put('/:id', | |
117 | authenticate, | |
118 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
119 | asyncMiddleware(usersUpdateValidator), | |
120 | asyncMiddleware(updateUser) | |
121 | ) | |
122 | ||
123 | usersRouter.delete('/:id', | |
124 | authenticate, | |
125 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
126 | asyncMiddleware(usersRemoveValidator), | |
127 | asyncMiddleware(removeUser) | |
128 | ) | |
129 | ||
130 | usersRouter.post('/ask-reset-password', | |
131 | asyncMiddleware(usersAskResetPasswordValidator), | |
132 | asyncMiddleware(askResetUserPassword) | |
133 | ) | |
134 | ||
135 | usersRouter.post('/:id/reset-password', | |
136 | asyncMiddleware(usersResetPasswordValidator), | |
137 | asyncMiddleware(resetUserPassword) | |
138 | ) | |
139 | ||
140 | usersRouter.post('/ask-send-verify-email', | |
141 | askSendEmailLimiter, | |
142 | asyncMiddleware(usersAskSendVerifyEmailValidator), | |
143 | asyncMiddleware(askSendVerifyUserEmail) | |
144 | ) | |
145 | ||
146 | usersRouter.post('/:id/verify-email', | |
147 | asyncMiddleware(usersVerifyEmailValidator), | |
148 | asyncMiddleware(verifyUserEmail) | |
149 | ) | |
150 | ||
151 | usersRouter.post('/token', | |
152 | loginRateLimiter, | |
153 | token, | |
154 | success | |
155 | ) | |
156 | // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route | |
157 | ||
158 | // --------------------------------------------------------------------------- | |
159 | ||
160 | export { | |
161 | usersRouter | |
162 | } | |
163 | ||
164 | // --------------------------------------------------------------------------- | |
165 | ||
166 | async function createUser (req: express.Request, res: express.Response) { | |
167 | const body: UserCreate = req.body | |
168 | const userToCreate = new UserModel({ | |
169 | username: body.username, | |
170 | password: body.password, | |
171 | email: body.email, | |
172 | nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY, | |
173 | autoPlayVideo: true, | |
174 | role: body.role, | |
175 | videoQuota: body.videoQuota, | |
176 | videoQuotaDaily: body.videoQuotaDaily | |
177 | }) | |
178 | ||
179 | const { user, account } = await createUserAccountAndChannelAndPlaylist(userToCreate) | |
180 | ||
181 | auditLogger.create(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON())) | |
182 | logger.info('User %s with its channel and account created.', body.username) | |
183 | ||
184 | return res.json({ | |
185 | user: { | |
186 | id: user.id, | |
187 | account: { | |
188 | id: account.id, | |
189 | uuid: account.Actor.uuid | |
190 | } | |
191 | } | |
192 | }).end() | |
193 | } | |
194 | ||
195 | async function registerUser (req: express.Request, res: express.Response) { | |
196 | const body: UserCreate = req.body | |
197 | ||
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: UserRole.USER, | |
205 | videoQuota: CONFIG.USER.VIDEO_QUOTA, | |
206 | videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY, | |
207 | emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null | |
208 | }) | |
209 | ||
210 | const { user } = await createUserAccountAndChannelAndPlaylist(userToCreate) | |
211 | ||
212 | auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON())) | |
213 | logger.info('User %s with its channel and account registered.', body.username) | |
214 | ||
215 | if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) { | |
216 | await sendVerifyUserEmail(user) | |
217 | } | |
218 | ||
219 | Notifier.Instance.notifyOnNewUserRegistration(user) | |
220 | ||
221 | return res.type('json').status(204).end() | |
222 | } | |
223 | ||
224 | async function unblockUser (req: express.Request, res: express.Response, next: express.NextFunction) { | |
225 | const user: UserModel = res.locals.user | |
226 | ||
227 | await changeUserBlock(res, user, false) | |
228 | ||
229 | return res.status(204).end() | |
230 | } | |
231 | ||
232 | async function blockUser (req: express.Request, res: express.Response) { | |
233 | const user: UserModel = res.locals.user | |
234 | const reason = req.body.reason | |
235 | ||
236 | await changeUserBlock(res, user, true, reason) | |
237 | ||
238 | return res.status(204).end() | |
239 | } | |
240 | ||
241 | function getUser (req: express.Request, res: express.Response) { | |
242 | return res.json((res.locals.user as UserModel).toFormattedJSON()) | |
243 | } | |
244 | ||
245 | async function autocompleteUsers (req: express.Request, res: express.Response) { | |
246 | const resultList = await UserModel.autoComplete(req.query.search as string) | |
247 | ||
248 | return res.json(resultList) | |
249 | } | |
250 | ||
251 | async function listUsers (req: express.Request, res: express.Response) { | |
252 | const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort, req.query.search) | |
253 | ||
254 | return res.json(getFormattedObjects(resultList.data, resultList.total)) | |
255 | } | |
256 | ||
257 | async function removeUser (req: express.Request, res: express.Response) { | |
258 | const user: UserModel = res.locals.user | |
259 | ||
260 | await user.destroy() | |
261 | ||
262 | auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON())) | |
263 | ||
264 | return res.sendStatus(204) | |
265 | } | |
266 | ||
267 | async function updateUser (req: express.Request, res: express.Response) { | |
268 | const body: UserUpdate = req.body | |
269 | const userToUpdate = res.locals.user as UserModel | |
270 | const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON()) | |
271 | const roleChanged = body.role !== undefined && body.role !== userToUpdate.role | |
272 | ||
273 | if (body.password !== undefined) userToUpdate.password = body.password | |
274 | if (body.email !== undefined) userToUpdate.email = body.email | |
275 | if (body.emailVerified !== undefined) userToUpdate.emailVerified = body.emailVerified | |
276 | if (body.videoQuota !== undefined) userToUpdate.videoQuota = body.videoQuota | |
277 | if (body.videoQuotaDaily !== undefined) userToUpdate.videoQuotaDaily = body.videoQuotaDaily | |
278 | if (body.role !== undefined) userToUpdate.role = body.role | |
279 | ||
280 | const user = await userToUpdate.save() | |
281 | ||
282 | // Destroy user token to refresh rights | |
283 | if (roleChanged || body.password !== undefined) await deleteUserToken(userToUpdate.id) | |
284 | ||
285 | auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView) | |
286 | ||
287 | // Don't need to send this update to followers, these attributes are not federated | |
288 | ||
289 | return res.sendStatus(204) | |
290 | } | |
291 | ||
292 | async function askResetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) { | |
293 | const user = res.locals.user as UserModel | |
294 | ||
295 | const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id) | |
296 | const url = CONFIG.WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString | |
297 | await Emailer.Instance.addPasswordResetEmailJob(user.email, url) | |
298 | ||
299 | return res.status(204).end() | |
300 | } | |
301 | ||
302 | async function resetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) { | |
303 | const user = res.locals.user as UserModel | |
304 | user.password = req.body.password | |
305 | ||
306 | await user.save() | |
307 | ||
308 | return res.status(204).end() | |
309 | } | |
310 | ||
311 | async function sendVerifyUserEmail (user: UserModel) { | |
312 | const verificationString = await Redis.Instance.setVerifyEmailVerificationString(user.id) | |
313 | const url = CONFIG.WEBSERVER.URL + '/verify-account/email?userId=' + user.id + '&verificationString=' + verificationString | |
314 | await Emailer.Instance.addVerifyEmailJob(user.email, url) | |
315 | return | |
316 | } | |
317 | ||
318 | async function askSendVerifyUserEmail (req: express.Request, res: express.Response, next: express.NextFunction) { | |
319 | const user = res.locals.user as UserModel | |
320 | ||
321 | await sendVerifyUserEmail(user) | |
322 | ||
323 | return res.status(204).end() | |
324 | } | |
325 | ||
326 | async function verifyUserEmail (req: express.Request, res: express.Response, next: express.NextFunction) { | |
327 | const user = res.locals.user as UserModel | |
328 | user.emailVerified = true | |
329 | ||
330 | await user.save() | |
331 | ||
332 | return res.status(204).end() | |
333 | } | |
334 | ||
335 | function success (req: express.Request, res: express.Response, next: express.NextFunction) { | |
336 | res.end() | |
337 | } | |
338 | ||
339 | async function changeUserBlock (res: express.Response, user: UserModel, block: boolean, reason?: string) { | |
340 | const oldUserAuditView = new UserAuditView(user.toFormattedJSON()) | |
341 | ||
342 | user.blocked = block | |
343 | user.blockedReason = reason || null | |
344 | ||
345 | await sequelizeTypescript.transaction(async t => { | |
346 | await deleteUserToken(user.id, t) | |
347 | ||
348 | await user.save({ transaction: t }) | |
349 | }) | |
350 | ||
351 | await Emailer.Instance.addUserBlockJob(user, block, reason) | |
352 | ||
353 | auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView) | |
354 | } |