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