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