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