]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/users/index.ts
add blocked filter in users list to filter banned users
[github/Chocobozzz/PeerTube.git] / server / controllers / api / users / index.ts
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 { generateRandomString, getFormattedObjects } from '../../../helpers/utils'
6 import { WEBSERVER } from '../../../initializers/constants'
7 import { Emailer } from '../../../lib/emailer'
8 import { Redis } from '../../../lib/redis'
9 import { createUserAccountAndChannelAndPlaylist, sendVerifyUserEmail } from '../../../lib/user'
10 import {
11 asyncMiddleware,
12 asyncRetryTransactionMiddleware,
13 authenticate,
14 ensureUserHasRight,
15 ensureUserRegistrationAllowed,
16 ensureUserRegistrationAllowedForIP,
17 paginationValidator,
18 setDefaultPagination,
19 setDefaultSort,
20 userAutocompleteValidator,
21 usersListValidator,
22 usersAddValidator,
23 usersGetValidator,
24 usersRegisterValidator,
25 usersRemoveValidator,
26 usersSortValidator,
27 usersUpdateValidator
28 } from '../../../middlewares'
29 import {
30 ensureCanManageUser,
31 usersAskResetPasswordValidator,
32 usersAskSendVerifyEmailValidator,
33 usersBlockingValidator,
34 usersResetPasswordValidator,
35 usersVerifyEmailValidator
36 } from '../../../middlewares/validators'
37 import { UserModel } from '../../../models/account/user'
38 import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger'
39 import { meRouter } from './me'
40 import { deleteUserToken } from '../../../lib/oauth-model'
41 import { myBlocklistRouter } from './my-blocklist'
42 import { myVideoPlaylistsRouter } from './my-video-playlists'
43 import { myVideosHistoryRouter } from './my-history'
44 import { myNotificationsRouter } from './my-notifications'
45 import { Notifier } from '../../../lib/notifier'
46 import { mySubscriptionsRouter } from './my-subscriptions'
47 import { CONFIG } from '../../../initializers/config'
48 import { sequelizeTypescript } from '../../../initializers/database'
49 import { UserAdminFlag } from '../../../../shared/models/users/user-flag.model'
50 import { UserRegister } from '../../../../shared/models/users/user-register.model'
51 import { MUser, MUserAccountDefault } from '@server/types/models'
52 import { Hooks } from '@server/lib/plugins/hooks'
53 import { tokensRouter } from '@server/controllers/api/users/token'
54
55 const auditLogger = auditLoggerFactory('users')
56
57 const signupRateLimiter = RateLimit({
58 windowMs: CONFIG.RATES_LIMIT.SIGNUP.WINDOW_MS,
59 max: CONFIG.RATES_LIMIT.SIGNUP.MAX,
60 skipFailedRequests: true
61 })
62
63 const askSendEmailLimiter = RateLimit({
64 windowMs: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.WINDOW_MS,
65 max: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.MAX
66 })
67
68 const usersRouter = express.Router()
69 usersRouter.use('/', tokensRouter)
70 usersRouter.use('/', myNotificationsRouter)
71 usersRouter.use('/', mySubscriptionsRouter)
72 usersRouter.use('/', myBlocklistRouter)
73 usersRouter.use('/', myVideosHistoryRouter)
74 usersRouter.use('/', myVideoPlaylistsRouter)
75 usersRouter.use('/', meRouter)
76
77 usersRouter.get('/autocomplete',
78 userAutocompleteValidator,
79 asyncMiddleware(autocompleteUsers)
80 )
81
82 usersRouter.get('/',
83 authenticate,
84 ensureUserHasRight(UserRight.MANAGE_USERS),
85 paginationValidator,
86 usersSortValidator,
87 setDefaultSort,
88 setDefaultPagination,
89 asyncMiddleware(usersListValidator),
90 asyncMiddleware(listUsers)
91 )
92
93 usersRouter.post('/:id/block',
94 authenticate,
95 ensureUserHasRight(UserRight.MANAGE_USERS),
96 asyncMiddleware(usersBlockingValidator),
97 ensureCanManageUser,
98 asyncMiddleware(blockUser)
99 )
100 usersRouter.post('/:id/unblock',
101 authenticate,
102 ensureUserHasRight(UserRight.MANAGE_USERS),
103 asyncMiddleware(usersBlockingValidator),
104 ensureCanManageUser,
105 asyncMiddleware(unblockUser)
106 )
107
108 usersRouter.get('/:id',
109 authenticate,
110 ensureUserHasRight(UserRight.MANAGE_USERS),
111 asyncMiddleware(usersGetValidator),
112 getUser
113 )
114
115 usersRouter.post('/',
116 authenticate,
117 ensureUserHasRight(UserRight.MANAGE_USERS),
118 asyncMiddleware(usersAddValidator),
119 asyncRetryTransactionMiddleware(createUser)
120 )
121
122 usersRouter.post('/register',
123 signupRateLimiter,
124 asyncMiddleware(ensureUserRegistrationAllowed),
125 ensureUserRegistrationAllowedForIP,
126 asyncMiddleware(usersRegisterValidator),
127 asyncRetryTransactionMiddleware(registerUser)
128 )
129
130 usersRouter.put('/:id',
131 authenticate,
132 ensureUserHasRight(UserRight.MANAGE_USERS),
133 asyncMiddleware(usersUpdateValidator),
134 ensureCanManageUser,
135 asyncMiddleware(updateUser)
136 )
137
138 usersRouter.delete('/:id',
139 authenticate,
140 ensureUserHasRight(UserRight.MANAGE_USERS),
141 asyncMiddleware(usersRemoveValidator),
142 ensureCanManageUser,
143 asyncMiddleware(removeUser)
144 )
145
146 usersRouter.post('/ask-reset-password',
147 asyncMiddleware(usersAskResetPasswordValidator),
148 asyncMiddleware(askResetUserPassword)
149 )
150
151 usersRouter.post('/:id/reset-password',
152 asyncMiddleware(usersResetPasswordValidator),
153 asyncMiddleware(resetUserPassword)
154 )
155
156 usersRouter.post('/ask-send-verify-email',
157 askSendEmailLimiter,
158 asyncMiddleware(usersAskSendVerifyEmailValidator),
159 asyncMiddleware(reSendVerifyUserEmail)
160 )
161
162 usersRouter.post('/:id/verify-email',
163 asyncMiddleware(usersVerifyEmailValidator),
164 asyncMiddleware(verifyUserEmail)
165 )
166
167 // ---------------------------------------------------------------------------
168
169 export {
170 usersRouter
171 }
172
173 // ---------------------------------------------------------------------------
174
175 async function createUser (req: express.Request, res: express.Response) {
176 const body: UserCreate = req.body
177 const userToCreate = new UserModel({
178 username: body.username,
179 password: body.password,
180 email: body.email,
181 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
182 autoPlayVideo: true,
183 role: body.role,
184 videoQuota: body.videoQuota,
185 videoQuotaDaily: body.videoQuotaDaily,
186 adminFlags: body.adminFlags || UserAdminFlag.NONE
187 }) as MUser
188
189 // NB: due to the validator usersAddValidator, password==='' can only be true if we can send the mail.
190 const createPassword = userToCreate.password === ''
191 if (createPassword) {
192 userToCreate.password = await generateRandomString(20)
193 }
194
195 const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({ userToCreate: userToCreate })
196
197 auditLogger.create(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
198 logger.info('User %s with its channel and account created.', body.username)
199
200 if (createPassword) {
201 // this will send an email for newly created users, so then can set their first password.
202 logger.info('Sending to user %s a create password email', body.username)
203 const verificationString = await Redis.Instance.setCreatePasswordVerificationString(user.id)
204 const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
205 await Emailer.Instance.addPasswordCreateEmailJob(userToCreate.username, user.email, url)
206 }
207
208 Hooks.runAction('action:api.user.created', { body, user, account, videoChannel })
209
210 return res.json({
211 user: {
212 id: user.id,
213 account: {
214 id: account.id
215 }
216 }
217 }).end()
218 }
219
220 async function registerUser (req: express.Request, res: express.Response) {
221 const body: UserRegister = req.body
222
223 const userToCreate = new UserModel({
224 username: body.username,
225 password: body.password,
226 email: body.email,
227 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
228 autoPlayVideo: true,
229 role: UserRole.USER,
230 videoQuota: CONFIG.USER.VIDEO_QUOTA,
231 videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY,
232 emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null
233 })
234
235 const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({
236 userToCreate: userToCreate,
237 userDisplayName: body.displayName || undefined,
238 channelNames: body.channel
239 })
240
241 auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON()))
242 logger.info('User %s with its channel and account registered.', body.username)
243
244 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) {
245 await sendVerifyUserEmail(user)
246 }
247
248 Notifier.Instance.notifyOnNewUserRegistration(user)
249
250 Hooks.runAction('action:api.user.registered', { body, user, account, videoChannel })
251
252 return res.type('json').status(204).end()
253 }
254
255 async function unblockUser (req: express.Request, res: express.Response) {
256 const user = res.locals.user
257
258 await changeUserBlock(res, user, false)
259
260 Hooks.runAction('action:api.user.unblocked', { user })
261
262 return res.status(204).end()
263 }
264
265 async function blockUser (req: express.Request, res: express.Response) {
266 const user = res.locals.user
267 const reason = req.body.reason
268
269 await changeUserBlock(res, user, true, reason)
270
271 Hooks.runAction('action:api.user.blocked', { user })
272
273 return res.status(204).end()
274 }
275
276 function getUser (req: express.Request, res: express.Response) {
277 return res.json(res.locals.user.toFormattedJSON({ withAdminFlags: true }))
278 }
279
280 async function autocompleteUsers (req: express.Request, res: express.Response) {
281 const resultList = await UserModel.autoComplete(req.query.search as string)
282
283 return res.json(resultList)
284 }
285
286 async function listUsers (req: express.Request, res: express.Response) {
287 const resultList = await UserModel.listForApi({
288 start: req.query.start,
289 count: req.query.count,
290 sort: req.query.sort,
291 search: req.query.search,
292 blocked: req.query.blocked
293 })
294
295 return res.json(getFormattedObjects(resultList.data, resultList.total, { withAdminFlags: true }))
296 }
297
298 async function removeUser (req: express.Request, res: express.Response) {
299 const user = res.locals.user
300
301 await user.destroy()
302
303 auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
304
305 Hooks.runAction('action:api.user.deleted', { user })
306
307 return res.sendStatus(204)
308 }
309
310 async function updateUser (req: express.Request, res: express.Response) {
311 const body: UserUpdate = req.body
312 const userToUpdate = res.locals.user
313 const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON())
314 const roleChanged = body.role !== undefined && body.role !== userToUpdate.role
315
316 if (body.password !== undefined) userToUpdate.password = body.password
317 if (body.email !== undefined) userToUpdate.email = body.email
318 if (body.emailVerified !== undefined) userToUpdate.emailVerified = body.emailVerified
319 if (body.videoQuota !== undefined) userToUpdate.videoQuota = body.videoQuota
320 if (body.videoQuotaDaily !== undefined) userToUpdate.videoQuotaDaily = body.videoQuotaDaily
321 if (body.role !== undefined) userToUpdate.role = body.role
322 if (body.adminFlags !== undefined) userToUpdate.adminFlags = body.adminFlags
323
324 const user = await userToUpdate.save()
325
326 // Destroy user token to refresh rights
327 if (roleChanged || body.password !== undefined) await deleteUserToken(userToUpdate.id)
328
329 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
330
331 Hooks.runAction('action:api.user.updated', { user })
332
333 // Don't need to send this update to followers, these attributes are not federated
334
335 return res.sendStatus(204)
336 }
337
338 async function askResetUserPassword (req: express.Request, res: express.Response) {
339 const user = res.locals.user
340
341 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
342 const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
343 await Emailer.Instance.addPasswordResetEmailJob(user.email, url)
344
345 return res.status(204).end()
346 }
347
348 async function resetUserPassword (req: express.Request, res: express.Response) {
349 const user = res.locals.user
350 user.password = req.body.password
351
352 await user.save()
353
354 return res.status(204).end()
355 }
356
357 async function reSendVerifyUserEmail (req: express.Request, res: express.Response) {
358 const user = res.locals.user
359
360 await sendVerifyUserEmail(user)
361
362 return res.status(204).end()
363 }
364
365 async function verifyUserEmail (req: express.Request, res: express.Response) {
366 const user = res.locals.user
367 user.emailVerified = true
368
369 if (req.body.isPendingEmail === true) {
370 user.email = user.pendingEmail
371 user.pendingEmail = null
372 }
373
374 await user.save()
375
376 return res.status(204).end()
377 }
378
379 async function changeUserBlock (res: express.Response, user: MUserAccountDefault, block: boolean, reason?: string) {
380 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
381
382 user.blocked = block
383 user.blockedReason = reason || null
384
385 await sequelizeTypescript.transaction(async t => {
386 await deleteUserToken(user.id, t)
387
388 await user.save({ transaction: t })
389 })
390
391 await Emailer.Instance.addUserBlockJob(user, block, reason)
392
393 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
394 }