aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/controllers/api/users/index.ts
diff options
context:
space:
mode:
Diffstat (limited to 'server/controllers/api/users/index.ts')
-rw-r--r--server/controllers/api/users/index.ts319
1 files changed, 0 insertions, 319 deletions
diff --git a/server/controllers/api/users/index.ts b/server/controllers/api/users/index.ts
deleted file mode 100644
index 5eac6fd0f..000000000
--- a/server/controllers/api/users/index.ts
+++ /dev/null
@@ -1,319 +0,0 @@
1import express from 'express'
2import { tokensRouter } from '@server/controllers/api/users/token'
3import { Hooks } from '@server/lib/plugins/hooks'
4import { OAuthTokenModel } from '@server/models/oauth/oauth-token'
5import { MUserAccountDefault } from '@server/types/models'
6import { pick } from '@shared/core-utils'
7import { HttpStatusCode, UserCreate, UserCreateResult, UserRight, UserUpdate } from '@shared/models'
8import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger'
9import { logger } from '../../../helpers/logger'
10import { generateRandomString, getFormattedObjects } from '../../../helpers/utils'
11import { WEBSERVER } from '../../../initializers/constants'
12import { sequelizeTypescript } from '../../../initializers/database'
13import { Emailer } from '../../../lib/emailer'
14import { Redis } from '../../../lib/redis'
15import { buildUser, createUserAccountAndChannelAndPlaylist } from '../../../lib/user'
16import {
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'
33import {
34 ensureCanModerateUser,
35 usersAskResetPasswordValidator,
36 usersBlockingValidator,
37 usersResetPasswordValidator
38} from '../../../middlewares/validators'
39import { UserModel } from '../../../models/user/user'
40import { emailVerificationRouter } from './email-verification'
41import { meRouter } from './me'
42import { myAbusesRouter } from './my-abuses'
43import { myBlocklistRouter } from './my-blocklist'
44import { myVideosHistoryRouter } from './my-history'
45import { myNotificationsRouter } from './my-notifications'
46import { mySubscriptionsRouter } from './my-subscriptions'
47import { myVideoPlaylistsRouter } from './my-video-playlists'
48import { registrationsRouter } from './registrations'
49import { twoFactorRouter } from './two-factor'
50
51const auditLogger = auditLoggerFactory('users')
52
53const usersRouter = express.Router()
54
55usersRouter.use(apiRateLimiter)
56
57usersRouter.use('/', emailVerificationRouter)
58usersRouter.use('/', registrationsRouter)
59usersRouter.use('/', twoFactorRouter)
60usersRouter.use('/', tokensRouter)
61usersRouter.use('/', myNotificationsRouter)
62usersRouter.use('/', mySubscriptionsRouter)
63usersRouter.use('/', myBlocklistRouter)
64usersRouter.use('/', myVideosHistoryRouter)
65usersRouter.use('/', myVideoPlaylistsRouter)
66usersRouter.use('/', myAbusesRouter)
67usersRouter.use('/', meRouter)
68
69usersRouter.get('/autocomplete',
70 userAutocompleteValidator,
71 asyncMiddleware(autocompleteUsers)
72)
73
74usersRouter.get('/',
75 authenticate,
76 ensureUserHasRight(UserRight.MANAGE_USERS),
77 paginationValidator,
78 adminUsersSortValidator,
79 setDefaultSort,
80 setDefaultPagination,
81 usersListValidator,
82 asyncMiddleware(listUsers)
83)
84
85usersRouter.post('/:id/block',
86 authenticate,
87 ensureUserHasRight(UserRight.MANAGE_USERS),
88 asyncMiddleware(usersBlockingValidator),
89 ensureCanModerateUser,
90 asyncMiddleware(blockUser)
91)
92usersRouter.post('/:id/unblock',
93 authenticate,
94 ensureUserHasRight(UserRight.MANAGE_USERS),
95 asyncMiddleware(usersBlockingValidator),
96 ensureCanModerateUser,
97 asyncMiddleware(unblockUser)
98)
99
100usersRouter.get('/:id',
101 authenticate,
102 ensureUserHasRight(UserRight.MANAGE_USERS),
103 asyncMiddleware(usersGetValidator),
104 getUser
105)
106
107usersRouter.post('/',
108 authenticate,
109 ensureUserHasRight(UserRight.MANAGE_USERS),
110 asyncMiddleware(usersAddValidator),
111 asyncRetryTransactionMiddleware(createUser)
112)
113
114usersRouter.put('/:id',
115 authenticate,
116 ensureUserHasRight(UserRight.MANAGE_USERS),
117 asyncMiddleware(usersUpdateValidator),
118 ensureCanModerateUser,
119 asyncMiddleware(updateUser)
120)
121
122usersRouter.delete('/:id',
123 authenticate,
124 ensureUserHasRight(UserRight.MANAGE_USERS),
125 asyncMiddleware(usersRemoveValidator),
126 ensureCanModerateUser,
127 asyncMiddleware(removeUser)
128)
129
130usersRouter.post('/ask-reset-password',
131 asyncMiddleware(usersAskResetPasswordValidator),
132 asyncMiddleware(askResetUserPassword)
133)
134
135usersRouter.post('/:id/reset-password',
136 asyncMiddleware(usersResetPasswordValidator),
137 asyncMiddleware(resetUserPassword)
138)
139
140// ---------------------------------------------------------------------------
141
142export {
143 usersRouter
144}
145
146// ---------------------------------------------------------------------------
147
148async 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
191async 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
201async 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
212function getUser (req: express.Request, res: express.Response) {
213 return res.json(res.locals.user.toFormattedJSON({ withAdminFlags: true }))
214}
215
216async 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
222async 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
234async 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
249async 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
284async 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
294async 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
304async 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}