]>
Commit | Line | Data |
---|---|---|
1 | import express from 'express' | |
2 | import { tokensRouter } from '@server/controllers/api/users/token' | |
3 | import { Hooks } from '@server/lib/plugins/hooks' | |
4 | import { OAuthTokenModel } from '@server/models/oauth/oauth-token' | |
5 | import { MUserAccountDefault } from '@server/types/models' | |
6 | import { pick } from '@shared/core-utils' | |
7 | import { HttpStatusCode, UserCreate, UserCreateResult, UserRight, UserUpdate } from '@shared/models' | |
8 | import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger' | |
9 | import { logger } from '../../../helpers/logger' | |
10 | import { generateRandomString, getFormattedObjects } from '../../../helpers/utils' | |
11 | import { WEBSERVER } from '../../../initializers/constants' | |
12 | import { sequelizeTypescript } from '../../../initializers/database' | |
13 | import { Emailer } from '../../../lib/emailer' | |
14 | import { Redis } from '../../../lib/redis' | |
15 | import { buildUser, createUserAccountAndChannelAndPlaylist } from '../../../lib/user' | |
16 | import { | |
17 | adminUsersSortValidator, | |
18 | apiRateLimiter, | |
19 | asyncMiddleware, | |
20 | asyncRetryTransactionMiddleware, | |
21 | authenticate, | |
22 | ensureUserHasRight, | |
23 | paginationValidator, | |
24 | setDefaultPagination, | |
25 | setDefaultSort, | |
26 | userAutocompleteValidator, | |
27 | usersAddValidator, | |
28 | usersGetValidator, | |
29 | usersListValidator, | |
30 | usersRemoveValidator, | |
31 | usersUpdateValidator | |
32 | } from '../../../middlewares' | |
33 | import { | |
34 | ensureCanModerateUser, | |
35 | usersAskResetPasswordValidator, | |
36 | usersBlockingValidator, | |
37 | usersResetPasswordValidator | |
38 | } from '../../../middlewares/validators' | |
39 | import { UserModel } from '../../../models/user/user' | |
40 | import { emailVerificationRouter } from './email-verification' | |
41 | import { meRouter } from './me' | |
42 | import { myAbusesRouter } from './my-abuses' | |
43 | import { myBlocklistRouter } from './my-blocklist' | |
44 | import { myVideosHistoryRouter } from './my-history' | |
45 | import { myNotificationsRouter } from './my-notifications' | |
46 | import { mySubscriptionsRouter } from './my-subscriptions' | |
47 | import { myVideoPlaylistsRouter } from './my-video-playlists' | |
48 | import { registrationsRouter } from './registrations' | |
49 | import { twoFactorRouter } from './two-factor' | |
50 | ||
51 | const auditLogger = auditLoggerFactory('users') | |
52 | ||
53 | const usersRouter = express.Router() | |
54 | ||
55 | usersRouter.use(apiRateLimiter) | |
56 | ||
57 | usersRouter.use('/', emailVerificationRouter) | |
58 | usersRouter.use('/', registrationsRouter) | |
59 | usersRouter.use('/', twoFactorRouter) | |
60 | usersRouter.use('/', tokensRouter) | |
61 | usersRouter.use('/', myNotificationsRouter) | |
62 | usersRouter.use('/', mySubscriptionsRouter) | |
63 | usersRouter.use('/', myBlocklistRouter) | |
64 | usersRouter.use('/', myVideosHistoryRouter) | |
65 | usersRouter.use('/', myVideoPlaylistsRouter) | |
66 | usersRouter.use('/', myAbusesRouter) | |
67 | usersRouter.use('/', meRouter) | |
68 | ||
69 | usersRouter.get('/autocomplete', | |
70 | userAutocompleteValidator, | |
71 | asyncMiddleware(autocompleteUsers) | |
72 | ) | |
73 | ||
74 | usersRouter.get('/', | |
75 | authenticate, | |
76 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
77 | paginationValidator, | |
78 | adminUsersSortValidator, | |
79 | setDefaultSort, | |
80 | setDefaultPagination, | |
81 | usersListValidator, | |
82 | asyncMiddleware(listUsers) | |
83 | ) | |
84 | ||
85 | usersRouter.post('/:id/block', | |
86 | authenticate, | |
87 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
88 | asyncMiddleware(usersBlockingValidator), | |
89 | ensureCanModerateUser, | |
90 | asyncMiddleware(blockUser) | |
91 | ) | |
92 | usersRouter.post('/:id/unblock', | |
93 | authenticate, | |
94 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
95 | asyncMiddleware(usersBlockingValidator), | |
96 | ensureCanModerateUser, | |
97 | asyncMiddleware(unblockUser) | |
98 | ) | |
99 | ||
100 | usersRouter.get('/:id', | |
101 | authenticate, | |
102 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
103 | asyncMiddleware(usersGetValidator), | |
104 | getUser | |
105 | ) | |
106 | ||
107 | usersRouter.post('/', | |
108 | authenticate, | |
109 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
110 | asyncMiddleware(usersAddValidator), | |
111 | asyncRetryTransactionMiddleware(createUser) | |
112 | ) | |
113 | ||
114 | usersRouter.put('/:id', | |
115 | authenticate, | |
116 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
117 | asyncMiddleware(usersUpdateValidator), | |
118 | ensureCanModerateUser, | |
119 | asyncMiddleware(updateUser) | |
120 | ) | |
121 | ||
122 | usersRouter.delete('/:id', | |
123 | authenticate, | |
124 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
125 | asyncMiddleware(usersRemoveValidator), | |
126 | ensureCanModerateUser, | |
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 | // --------------------------------------------------------------------------- | |
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 | ||
151 | const userToCreate = buildUser({ | |
152 | ...pick(body, [ 'username', 'password', 'email', 'role', 'videoQuota', 'videoQuotaDaily', 'adminFlags' ]), | |
153 | ||
154 | emailVerified: null | |
155 | }) | |
156 | ||
157 | // NB: due to the validator usersAddValidator, password==='' can only be true if we can send the mail. | |
158 | const createPassword = userToCreate.password === '' | |
159 | if (createPassword) { | |
160 | userToCreate.password = await generateRandomString(20) | |
161 | } | |
162 | ||
163 | const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({ | |
164 | userToCreate, | |
165 | channelNames: body.channelName && { name: body.channelName, displayName: body.channelName } | |
166 | }) | |
167 | ||
168 | auditLogger.create(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON())) | |
169 | logger.info('User %s with its channel and account created.', body.username) | |
170 | ||
171 | if (createPassword) { | |
172 | // this will send an email for newly created users, so then can set their first password. | |
173 | logger.info('Sending to user %s a create password email', body.username) | |
174 | const verificationString = await Redis.Instance.setCreatePasswordVerificationString(user.id) | |
175 | const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString | |
176 | Emailer.Instance.addPasswordCreateEmailJob(userToCreate.username, user.email, url) | |
177 | } | |
178 | ||
179 | Hooks.runAction('action:api.user.created', { body, user, account, videoChannel, req, res }) | |
180 | ||
181 | return res.json({ | |
182 | user: { | |
183 | id: user.id, | |
184 | account: { | |
185 | id: account.id | |
186 | } | |
187 | } as UserCreateResult | |
188 | }) | |
189 | } | |
190 | ||
191 | async function unblockUser (req: express.Request, res: express.Response) { | |
192 | const user = res.locals.user | |
193 | ||
194 | await changeUserBlock(res, user, false) | |
195 | ||
196 | Hooks.runAction('action:api.user.unblocked', { user, req, res }) | |
197 | ||
198 | return res.status(HttpStatusCode.NO_CONTENT_204).end() | |
199 | } | |
200 | ||
201 | async function blockUser (req: express.Request, res: express.Response) { | |
202 | const user = res.locals.user | |
203 | const reason = req.body.reason | |
204 | ||
205 | await changeUserBlock(res, user, true, reason) | |
206 | ||
207 | Hooks.runAction('action:api.user.blocked', { user, req, res }) | |
208 | ||
209 | return res.status(HttpStatusCode.NO_CONTENT_204).end() | |
210 | } | |
211 | ||
212 | function getUser (req: express.Request, res: express.Response) { | |
213 | return res.json(res.locals.user.toFormattedJSON({ withAdminFlags: true })) | |
214 | } | |
215 | ||
216 | async function autocompleteUsers (req: express.Request, res: express.Response) { | |
217 | const resultList = await UserModel.autoComplete(req.query.search as string) | |
218 | ||
219 | return res.json(resultList) | |
220 | } | |
221 | ||
222 | async function listUsers (req: express.Request, res: express.Response) { | |
223 | const resultList = await UserModel.listForAdminApi({ | |
224 | start: req.query.start, | |
225 | count: req.query.count, | |
226 | sort: req.query.sort, | |
227 | search: req.query.search, | |
228 | blocked: req.query.blocked | |
229 | }) | |
230 | ||
231 | return res.json(getFormattedObjects(resultList.data, resultList.total, { withAdminFlags: true })) | |
232 | } | |
233 | ||
234 | async function removeUser (req: express.Request, res: express.Response) { | |
235 | const user = res.locals.user | |
236 | ||
237 | auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON())) | |
238 | ||
239 | await sequelizeTypescript.transaction(async t => { | |
240 | // Use a transaction to avoid inconsistencies with hooks (account/channel deletion & federation) | |
241 | await user.destroy({ transaction: t }) | |
242 | }) | |
243 | ||
244 | Hooks.runAction('action:api.user.deleted', { user, req, res }) | |
245 | ||
246 | return res.status(HttpStatusCode.NO_CONTENT_204).end() | |
247 | } | |
248 | ||
249 | async function updateUser (req: express.Request, res: express.Response) { | |
250 | const body: UserUpdate = req.body | |
251 | const userToUpdate = res.locals.user | |
252 | const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON()) | |
253 | const roleChanged = body.role !== undefined && body.role !== userToUpdate.role | |
254 | ||
255 | const keysToUpdate: (keyof UserUpdate)[] = [ | |
256 | 'password', | |
257 | 'email', | |
258 | 'emailVerified', | |
259 | 'videoQuota', | |
260 | 'videoQuotaDaily', | |
261 | 'role', | |
262 | 'adminFlags', | |
263 | 'pluginAuth' | |
264 | ] | |
265 | ||
266 | for (const key of keysToUpdate) { | |
267 | if (body[key] !== undefined) userToUpdate.set(key, body[key]) | |
268 | } | |
269 | ||
270 | const user = await userToUpdate.save() | |
271 | ||
272 | // Destroy user token to refresh rights | |
273 | if (roleChanged || body.password !== undefined) await OAuthTokenModel.deleteUserToken(userToUpdate.id) | |
274 | ||
275 | auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView) | |
276 | ||
277 | Hooks.runAction('action:api.user.updated', { user, req, res }) | |
278 | ||
279 | // Don't need to send this update to followers, these attributes are not federated | |
280 | ||
281 | return res.status(HttpStatusCode.NO_CONTENT_204).end() | |
282 | } | |
283 | ||
284 | async function askResetUserPassword (req: express.Request, res: express.Response) { | |
285 | const user = res.locals.user | |
286 | ||
287 | const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id) | |
288 | const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString | |
289 | Emailer.Instance.addPasswordResetEmailJob(user.username, user.email, url) | |
290 | ||
291 | return res.status(HttpStatusCode.NO_CONTENT_204).end() | |
292 | } | |
293 | ||
294 | async function resetUserPassword (req: express.Request, res: express.Response) { | |
295 | const user = res.locals.user | |
296 | user.password = req.body.password | |
297 | ||
298 | await user.save() | |
299 | await Redis.Instance.removePasswordVerificationString(user.id) | |
300 | ||
301 | return res.status(HttpStatusCode.NO_CONTENT_204).end() | |
302 | } | |
303 | ||
304 | async function changeUserBlock (res: express.Response, user: MUserAccountDefault, block: boolean, reason?: string) { | |
305 | const oldUserAuditView = new UserAuditView(user.toFormattedJSON()) | |
306 | ||
307 | user.blocked = block | |
308 | user.blockedReason = reason || null | |
309 | ||
310 | await sequelizeTypescript.transaction(async t => { | |
311 | await OAuthTokenModel.deleteUserToken(user.id, t) | |
312 | ||
313 | await user.save({ transaction: t }) | |
314 | }) | |
315 | ||
316 | Emailer.Instance.addUserBlockJob(user, block, reason) | |
317 | ||
318 | auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView) | |
319 | } |