]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/users/index.ts
Use different p2p policy for embeds and webapp
[github/Chocobozzz/PeerTube.git] / server / controllers / api / users / index.ts
CommitLineData
41fb13c3
C
1import express from 'express'
2import RateLimit from 'express-rate-limit'
edbc9325
C
3import { tokensRouter } from '@server/controllers/api/users/token'
4import { Hooks } from '@server/lib/plugins/hooks'
f43db2f4 5import { OAuthTokenModel } from '@server/models/oauth/oauth-token'
edbc9325 6import { MUser, MUserAccountDefault } from '@server/types/models'
7926c5f9 7import { UserCreate, UserCreateResult, UserRight, UserRole, UserUpdate } from '../../../../shared'
c0e8b12e 8import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes'
edbc9325
C
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'
d03cd8bb 12import { logger } from '../../../helpers/logger'
45f1bd72 13import { generateRandomString, getFormattedObjects } from '../../../helpers/utils'
edbc9325 14import { CONFIG } from '../../../initializers/config'
c1340a6a 15import { WEBSERVER } from '../../../initializers/constants'
edbc9325 16import { sequelizeTypescript } from '../../../initializers/database'
d03cd8bb 17import { Emailer } from '../../../lib/emailer'
edbc9325 18import { Notifier } from '../../../lib/notifier'
d03cd8bb 19import { Redis } from '../../../lib/redis'
d1ab89de 20import { createUserAccountAndChannelAndPlaylist, sendVerifyUserEmail } from '../../../lib/user'
65fcc311 21import {
f076daa7 22 asyncMiddleware,
90d4bb81 23 asyncRetryTransactionMiddleware,
f076daa7
C
24 authenticate,
25 ensureUserHasRight,
26 ensureUserRegistrationAllowed,
ff2c1fe8 27 ensureUserRegistrationAllowedForIP,
f076daa7
C
28 paginationValidator,
29 setDefaultPagination,
30 setDefaultSort,
74d63469 31 userAutocompleteValidator,
f076daa7
C
32 usersAddValidator,
33 usersGetValidator,
edbc9325 34 usersListValidator,
f076daa7
C
35 usersRegisterValidator,
36 usersRemoveValidator,
37 usersSortValidator,
d03cd8bb
C
38 usersUpdateValidator
39} from '../../../middlewares'
d9eaee39 40import {
e1c55031 41 ensureCanManageUser,
993cef4b
C
42 usersAskResetPasswordValidator,
43 usersAskSendVerifyEmailValidator,
44 usersBlockingValidator,
45 usersResetPasswordValidator,
e1c55031 46 usersVerifyEmailValidator
d9eaee39 47} from '../../../middlewares/validators'
7d9ba5c0 48import { UserModel } from '../../../models/user/user'
d03cd8bb 49import { meRouter } from './me'
edbc9325 50import { myAbusesRouter } from './my-abuses'
7ad9b984 51import { myBlocklistRouter } from './my-blocklist'
8b9a525a 52import { myVideosHistoryRouter } from './my-history'
cef534ed 53import { myNotificationsRouter } from './my-notifications'
cf405589 54import { mySubscriptionsRouter } from './my-subscriptions'
edbc9325 55import { myVideoPlaylistsRouter } from './my-video-playlists'
80e36cd9
AB
56
57const auditLogger = auditLoggerFactory('users')
65fcc311 58
c1340a6a
C
59const signupRateLimiter = RateLimit({
60 windowMs: CONFIG.RATES_LIMIT.SIGNUP.WINDOW_MS,
61 max: CONFIG.RATES_LIMIT.SIGNUP.MAX,
62 skipFailedRequests: true
490b595a 63})
c5911fd3 64
faa9d434 65const askSendEmailLimiter = RateLimit({
c1340a6a
C
66 windowMs: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.WINDOW_MS,
67 max: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.MAX
288fe385
C
68})
69
65fcc311 70const usersRouter = express.Router()
e1c55031 71usersRouter.use('/', tokensRouter)
cef534ed 72usersRouter.use('/', myNotificationsRouter)
cf405589 73usersRouter.use('/', mySubscriptionsRouter)
7ad9b984 74usersRouter.use('/', myBlocklistRouter)
8b9a525a 75usersRouter.use('/', myVideosHistoryRouter)
f0a39880 76usersRouter.use('/', myVideoPlaylistsRouter)
edbc9325 77usersRouter.use('/', myAbusesRouter)
06a05d5f 78usersRouter.use('/', meRouter)
9bd26629 79
74d63469
GR
80usersRouter.get('/autocomplete',
81 userAutocompleteValidator,
82 asyncMiddleware(autocompleteUsers)
83)
84
65fcc311 85usersRouter.get('/',
86d13ec2
C
86 authenticate,
87 ensureUserHasRight(UserRight.MANAGE_USERS),
65fcc311
C
88 paginationValidator,
89 usersSortValidator,
1174a847 90 setDefaultSort,
f05a1c30 91 setDefaultPagination,
ea7337cf 92 usersListValidator,
eb080476 93 asyncMiddleware(listUsers)
5c39adb7
C
94)
95
e6921918
C
96usersRouter.post('/:id/block',
97 authenticate,
98 ensureUserHasRight(UserRight.MANAGE_USERS),
99 asyncMiddleware(usersBlockingValidator),
a95a4cc8 100 ensureCanManageUser,
e6921918
C
101 asyncMiddleware(blockUser)
102)
103usersRouter.post('/:id/unblock',
104 authenticate,
105 ensureUserHasRight(UserRight.MANAGE_USERS),
106 asyncMiddleware(usersBlockingValidator),
a95a4cc8 107 ensureCanManageUser,
e6921918
C
108 asyncMiddleware(unblockUser)
109)
110
8094a898 111usersRouter.get('/:id',
94ff4c23
C
112 authenticate,
113 ensureUserHasRight(UserRight.MANAGE_USERS),
a2431b7d 114 asyncMiddleware(usersGetValidator),
8094a898
C
115 getUser
116)
117
65fcc311
C
118usersRouter.post('/',
119 authenticate,
954605a8 120 ensureUserHasRight(UserRight.MANAGE_USERS),
a2431b7d 121 asyncMiddleware(usersAddValidator),
90d4bb81 122 asyncRetryTransactionMiddleware(createUser)
9bd26629
C
123)
124
65fcc311 125usersRouter.post('/register',
c1340a6a 126 signupRateLimiter,
a2431b7d 127 asyncMiddleware(ensureUserRegistrationAllowed),
ff2c1fe8 128 ensureUserRegistrationAllowedForIP,
a2431b7d 129 asyncMiddleware(usersRegisterValidator),
90d4bb81 130 asyncRetryTransactionMiddleware(registerUser)
2c2e9092
C
131)
132
65fcc311
C
133usersRouter.put('/:id',
134 authenticate,
954605a8 135 ensureUserHasRight(UserRight.MANAGE_USERS),
a2431b7d 136 asyncMiddleware(usersUpdateValidator),
a95a4cc8 137 ensureCanManageUser,
eb080476 138 asyncMiddleware(updateUser)
9bd26629
C
139)
140
65fcc311
C
141usersRouter.delete('/:id',
142 authenticate,
954605a8 143 ensureUserHasRight(UserRight.MANAGE_USERS),
a2431b7d 144 asyncMiddleware(usersRemoveValidator),
a95a4cc8 145 ensureCanManageUser,
eb080476 146 asyncMiddleware(removeUser)
9bd26629 147)
6606150c 148
ecb4e35f
C
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
d9eaee39 159usersRouter.post('/ask-send-verify-email',
288fe385 160 askSendEmailLimiter,
d9eaee39 161 asyncMiddleware(usersAskSendVerifyEmailValidator),
d1ab89de 162 asyncMiddleware(reSendVerifyUserEmail)
d9eaee39
JM
163)
164
165usersRouter.post('/:id/verify-email',
166 asyncMiddleware(usersVerifyEmailValidator),
167 asyncMiddleware(verifyUserEmail)
168)
169
9457bf88
C
170// ---------------------------------------------------------------------------
171
65fcc311
C
172export {
173 usersRouter
174}
9457bf88
C
175
176// ---------------------------------------------------------------------------
177
90d4bb81 178async function createUser (req: express.Request, res: express.Response) {
4771e000 179 const body: UserCreate = req.body
3d215dc5 180
f05a1c30 181 const userToCreate = new UserModel({
4771e000
C
182 username: body.username,
183 password: body.password,
184 email: body.email,
0883b324 185 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
b65de1be 186 p2pEnabled: CONFIG.DEFAULTS.P2P.WEBAPP.ENABLED,
7efe153b 187 autoPlayVideo: true,
954605a8 188 role: body.role,
bee0abff 189 videoQuota: body.videoQuota,
1eddc9a7
C
190 videoQuotaDaily: body.videoQuotaDaily,
191 adminFlags: body.adminFlags || UserAdminFlag.NONE
1ca9f7c3 192 }) as MUser
9bd26629 193
45f1bd72
JL
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
3d215dc5 200 const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({
201 userToCreate,
69db1470 202 channelNames: body.channelName && { name: body.channelName, displayName: body.channelName }
3d215dc5 203 })
eb080476 204
993cef4b 205 auditLogger.create(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
38fa2065 206 logger.info('User %s with its channel and account created.', body.username)
f05a1c30 207
45f1bd72
JL
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
7226e90f 216 Hooks.runAction('action:api.user.created', { body, user, account, videoChannel, req, res })
6f3fe96f 217
1e904cde 218 return res.json({
90d4bb81
C
219 user: {
220 id: user.id,
221 account: {
57cfff78 222 id: account.id
90d4bb81 223 }
7926c5f9 224 } as UserCreateResult
8795d6f2 225 })
47e0652b
C
226}
227
90d4bb81 228async function registerUser (req: express.Request, res: express.Response) {
e590b4a5 229 const body: UserRegister = req.body
77a5501f 230
80e36cd9 231 const userToCreate = new UserModel({
77a5501f
C
232 username: body.username,
233 password: body.password,
234 email: body.email,
0883b324 235 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
b65de1be 236 p2pEnabled: CONFIG.DEFAULTS.P2P.WEBAPP.ENABLED,
7efe153b 237 autoPlayVideo: true,
954605a8 238 role: UserRole.USER,
bee0abff 239 videoQuota: CONFIG.USER.VIDEO_QUOTA,
d9eaee39
JM
240 videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY,
241 emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null
77a5501f
C
242 })
243
6f3fe96f 244 const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({
1f20622f
C
245 userToCreate: userToCreate,
246 userDisplayName: body.displayName || undefined,
247 channelNames: body.channel
248 })
47e0652b 249
80e36cd9 250 auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON()))
47e0652b 251 logger.info('User %s with its channel and account registered.', body.username)
90d4bb81 252
d9eaee39
JM
253 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) {
254 await sendVerifyUserEmail(user)
255 }
256
f7cc67b4
C
257 Notifier.Instance.notifyOnNewUserRegistration(user)
258
7226e90f 259 Hooks.runAction('action:api.user.registered', { body, user, account, videoChannel, req, res })
6f3fe96f 260
2d53be02 261 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
77a5501f
C
262}
263
dae86118
C
264async function unblockUser (req: express.Request, res: express.Response) {
265 const user = res.locals.user
e6921918
C
266
267 await changeUserBlock(res, user, false)
268
7226e90f 269 Hooks.runAction('action:api.user.unblocked', { user, req, res })
6f3fe96f 270
2d53be02 271 return res.status(HttpStatusCode.NO_CONTENT_204).end()
e6921918
C
272}
273
b426edd4 274async function blockUser (req: express.Request, res: express.Response) {
dae86118 275 const user = res.locals.user
eacb25c4 276 const reason = req.body.reason
e6921918 277
eacb25c4 278 await changeUserBlock(res, user, true, reason)
e6921918 279
7226e90f 280 Hooks.runAction('action:api.user.blocked', { user, req, res })
6f3fe96f 281
2d53be02 282 return res.status(HttpStatusCode.NO_CONTENT_204).end()
e6921918
C
283}
284
b426edd4 285function getUser (req: express.Request, res: express.Response) {
1eddc9a7 286 return res.json(res.locals.user.toFormattedJSON({ withAdminFlags: true }))
8094a898
C
287}
288
b426edd4 289async function autocompleteUsers (req: express.Request, res: express.Response) {
5cf84858 290 const resultList = await UserModel.autoComplete(req.query.search as string)
74d63469
GR
291
292 return res.json(resultList)
293}
294
b426edd4 295async function listUsers (req: express.Request, res: express.Response) {
8491293b
RK
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 })
eb080476 303
1eddc9a7 304 return res.json(getFormattedObjects(resultList.data, resultList.total, { withAdminFlags: true }))
9bd26629
C
305}
306
b426edd4 307async function removeUser (req: express.Request, res: express.Response) {
dae86118 308 const user = res.locals.user
eb080476 309
993cef4b 310 auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
80e36cd9 311
fae6e4da
C
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 })
2dbc170d 316
7226e90f 317 Hooks.runAction('action:api.user.deleted', { user, req, res })
6f3fe96f 318
76148b27 319 return res.status(HttpStatusCode.NO_CONTENT_204).end()
9bd26629
C
320}
321
b426edd4 322async function updateUser (req: express.Request, res: express.Response) {
8094a898 323 const body: UserUpdate = req.body
dae86118 324 const userToUpdate = res.locals.user
80e36cd9
AB
325 const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON())
326 const roleChanged = body.role !== undefined && body.role !== userToUpdate.role
8094a898 327
16c016e8
C
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 }
8094a898 342
80e36cd9 343 const user = await userToUpdate.save()
eb080476 344
f8b8c36b 345 // Destroy user token to refresh rights
f43db2f4 346 if (roleChanged || body.password !== undefined) await OAuthTokenModel.deleteUserToken(userToUpdate.id)
f8b8c36b 347
91411dba 348 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
80e36cd9 349
7226e90f 350 Hooks.runAction('action:api.user.updated', { user, req, res })
6f3fe96f 351
b426edd4 352 // Don't need to send this update to followers, these attributes are not federated
265ba139 353
76148b27 354 return res.status(HttpStatusCode.NO_CONTENT_204).end()
8094a898
C
355}
356
dae86118
C
357async function askResetUserPassword (req: express.Request, res: express.Response) {
358 const user = res.locals.user
ecb4e35f
C
359
360 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
6dd9de95 361 const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
963023ab 362 await Emailer.Instance.addPasswordResetEmailJob(user.username, user.email, url)
ecb4e35f 363
2d53be02 364 return res.status(HttpStatusCode.NO_CONTENT_204).end()
ecb4e35f
C
365}
366
dae86118
C
367async function resetUserPassword (req: express.Request, res: express.Response) {
368 const user = res.locals.user
ecb4e35f
C
369 user.password = req.body.password
370
371 await user.save()
e9c5f123 372 await Redis.Instance.removePasswordVerificationString(user.id)
ecb4e35f 373
2d53be02 374 return res.status(HttpStatusCode.NO_CONTENT_204).end()
ecb4e35f
C
375}
376
d1ab89de 377async function reSendVerifyUserEmail (req: express.Request, res: express.Response) {
dae86118 378 const user = res.locals.user
d9eaee39
JM
379
380 await sendVerifyUserEmail(user)
381
2d53be02 382 return res.status(HttpStatusCode.NO_CONTENT_204).end()
d9eaee39
JM
383}
384
dae86118
C
385async function verifyUserEmail (req: express.Request, res: express.Response) {
386 const user = res.locals.user
d9eaee39
JM
387 user.emailVerified = true
388
d1ab89de
C
389 if (req.body.isPendingEmail === true) {
390 user.email = user.pendingEmail
391 user.pendingEmail = null
392 }
393
d9eaee39
JM
394 await user.save()
395
2d53be02 396 return res.status(HttpStatusCode.NO_CONTENT_204).end()
d9eaee39
JM
397}
398
453e83ea 399async function changeUserBlock (res: express.Response, user: MUserAccountDefault, block: boolean, reason?: string) {
e6921918
C
400 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
401
402 user.blocked = block
eacb25c4 403 user.blockedReason = reason || null
e6921918
C
404
405 await sequelizeTypescript.transaction(async t => {
f43db2f4 406 await OAuthTokenModel.deleteUserToken(user.id, t)
e6921918
C
407
408 await user.save({ transaction: t })
409 })
410
eacb25c4
C
411 await Emailer.Instance.addUserBlockJob(user, block, reason)
412
91411dba 413 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
e6921918 414}