]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/users/index.ts
Optimize custom markup angular tags
[github/Chocobozzz/PeerTube.git] / server / controllers / api / users / index.ts
CommitLineData
41fb13c3 1import express from 'express'
edbc9325
C
2import { tokensRouter } from '@server/controllers/api/users/token'
3import { Hooks } from '@server/lib/plugins/hooks'
f43db2f4 4import { OAuthTokenModel } from '@server/models/oauth/oauth-token'
d3d3deaa
C
5import { MUserAccountDefault } from '@server/types/models'
6import { pick } from '@shared/core-utils'
7import { HttpStatusCode, UserCreate, UserCreateResult, UserRegister, UserRight, UserUpdate } from '@shared/models'
edbc9325 8import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger'
d03cd8bb 9import { logger } from '../../../helpers/logger'
45f1bd72 10import { generateRandomString, getFormattedObjects } from '../../../helpers/utils'
edbc9325 11import { CONFIG } from '../../../initializers/config'
c1340a6a 12import { WEBSERVER } from '../../../initializers/constants'
edbc9325 13import { sequelizeTypescript } from '../../../initializers/database'
d03cd8bb 14import { Emailer } from '../../../lib/emailer'
edbc9325 15import { Notifier } from '../../../lib/notifier'
d03cd8bb 16import { Redis } from '../../../lib/redis'
d3d3deaa 17import { buildUser, createUserAccountAndChannelAndPlaylist, sendVerifyUserEmail } from '../../../lib/user'
65fcc311 18import {
e5a781ec 19 adminUsersSortValidator,
f076daa7 20 asyncMiddleware,
90d4bb81 21 asyncRetryTransactionMiddleware,
f076daa7 22 authenticate,
e5a781ec 23 buildRateLimiter,
f076daa7
C
24 ensureUserHasRight,
25 ensureUserRegistrationAllowed,
ff2c1fe8 26 ensureUserRegistrationAllowedForIP,
f076daa7
C
27 paginationValidator,
28 setDefaultPagination,
29 setDefaultSort,
74d63469 30 userAutocompleteValidator,
f076daa7
C
31 usersAddValidator,
32 usersGetValidator,
edbc9325 33 usersListValidator,
f076daa7
C
34 usersRegisterValidator,
35 usersRemoveValidator,
d03cd8bb
C
36 usersUpdateValidator
37} from '../../../middlewares'
d9eaee39 38import {
d4d9bbc6 39 ensureCanModerateUser,
993cef4b
C
40 usersAskResetPasswordValidator,
41 usersAskSendVerifyEmailValidator,
42 usersBlockingValidator,
43 usersResetPasswordValidator,
e1c55031 44 usersVerifyEmailValidator
d9eaee39 45} from '../../../middlewares/validators'
7d9ba5c0 46import { UserModel } from '../../../models/user/user'
d03cd8bb 47import { meRouter } from './me'
edbc9325 48import { myAbusesRouter } from './my-abuses'
7ad9b984 49import { myBlocklistRouter } from './my-blocklist'
8b9a525a 50import { myVideosHistoryRouter } from './my-history'
cef534ed 51import { myNotificationsRouter } from './my-notifications'
cf405589 52import { mySubscriptionsRouter } from './my-subscriptions'
edbc9325 53import { myVideoPlaylistsRouter } from './my-video-playlists'
56f47830 54import { twoFactorRouter } from './two-factor'
80e36cd9
AB
55
56const auditLogger = auditLoggerFactory('users')
65fcc311 57
e5a781ec 58const signupRateLimiter = buildRateLimiter({
c1340a6a
C
59 windowMs: CONFIG.RATES_LIMIT.SIGNUP.WINDOW_MS,
60 max: CONFIG.RATES_LIMIT.SIGNUP.MAX,
61 skipFailedRequests: true
490b595a 62})
c5911fd3 63
e5a781ec 64const askSendEmailLimiter = buildRateLimiter({
c1340a6a
C
65 windowMs: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.WINDOW_MS,
66 max: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.MAX
288fe385
C
67})
68
65fcc311 69const usersRouter = express.Router()
56f47830 70usersRouter.use('/', twoFactorRouter)
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 88 paginationValidator,
87a0cac6 89 adminUsersSortValidator,
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),
d4d9bbc6 100 ensureCanModerateUser,
e6921918
C
101 asyncMiddleware(blockUser)
102)
103usersRouter.post('/:id/unblock',
104 authenticate,
105 ensureUserHasRight(UserRight.MANAGE_USERS),
106 asyncMiddleware(usersBlockingValidator),
d4d9bbc6 107 ensureCanModerateUser,
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),
d4d9bbc6 137 ensureCanModerateUser,
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),
d4d9bbc6 145 ensureCanModerateUser,
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
d3d3deaa
C
181 const userToCreate = buildUser({
182 ...pick(body, [ 'username', 'password', 'email', 'role', 'videoQuota', 'videoQuotaDaily', 'adminFlags' ]),
183
184 emailVerified: null
185 })
9bd26629 186
45f1bd72
JL
187 // NB: due to the validator usersAddValidator, password==='' can only be true if we can send the mail.
188 const createPassword = userToCreate.password === ''
189 if (createPassword) {
190 userToCreate.password = await generateRandomString(20)
191 }
192
3d215dc5 193 const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({
194 userToCreate,
69db1470 195 channelNames: body.channelName && { name: body.channelName, displayName: body.channelName }
3d215dc5 196 })
eb080476 197
993cef4b 198 auditLogger.create(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
38fa2065 199 logger.info('User %s with its channel and account created.', body.username)
f05a1c30 200
45f1bd72
JL
201 if (createPassword) {
202 // this will send an email for newly created users, so then can set their first password.
203 logger.info('Sending to user %s a create password email', body.username)
204 const verificationString = await Redis.Instance.setCreatePasswordVerificationString(user.id)
205 const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
d17c7b4e 206 Emailer.Instance.addPasswordCreateEmailJob(userToCreate.username, user.email, url)
45f1bd72
JL
207 }
208
7226e90f 209 Hooks.runAction('action:api.user.created', { body, user, account, videoChannel, req, res })
6f3fe96f 210
1e904cde 211 return res.json({
90d4bb81
C
212 user: {
213 id: user.id,
214 account: {
57cfff78 215 id: account.id
90d4bb81 216 }
7926c5f9 217 } as UserCreateResult
8795d6f2 218 })
47e0652b
C
219}
220
90d4bb81 221async function registerUser (req: express.Request, res: express.Response) {
e590b4a5 222 const body: UserRegister = req.body
77a5501f 223
d3d3deaa
C
224 const userToCreate = buildUser({
225 ...pick(body, [ 'username', 'password', 'email' ]),
226
d9eaee39 227 emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null
77a5501f
C
228 })
229
6f3fe96f 230 const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({
ba2684ce 231 userToCreate,
1f20622f
C
232 userDisplayName: body.displayName || undefined,
233 channelNames: body.channel
234 })
47e0652b 235
80e36cd9 236 auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON()))
47e0652b 237 logger.info('User %s with its channel and account registered.', body.username)
90d4bb81 238
d9eaee39
JM
239 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) {
240 await sendVerifyUserEmail(user)
241 }
242
f7cc67b4
C
243 Notifier.Instance.notifyOnNewUserRegistration(user)
244
7226e90f 245 Hooks.runAction('action:api.user.registered', { body, user, account, videoChannel, req, res })
6f3fe96f 246
2d53be02 247 return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
77a5501f
C
248}
249
dae86118
C
250async function unblockUser (req: express.Request, res: express.Response) {
251 const user = res.locals.user
e6921918
C
252
253 await changeUserBlock(res, user, false)
254
7226e90f 255 Hooks.runAction('action:api.user.unblocked', { user, req, res })
6f3fe96f 256
2d53be02 257 return res.status(HttpStatusCode.NO_CONTENT_204).end()
e6921918
C
258}
259
b426edd4 260async function blockUser (req: express.Request, res: express.Response) {
dae86118 261 const user = res.locals.user
eacb25c4 262 const reason = req.body.reason
e6921918 263
eacb25c4 264 await changeUserBlock(res, user, true, reason)
e6921918 265
7226e90f 266 Hooks.runAction('action:api.user.blocked', { user, req, res })
6f3fe96f 267
2d53be02 268 return res.status(HttpStatusCode.NO_CONTENT_204).end()
e6921918
C
269}
270
b426edd4 271function getUser (req: express.Request, res: express.Response) {
1eddc9a7 272 return res.json(res.locals.user.toFormattedJSON({ withAdminFlags: true }))
8094a898
C
273}
274
b426edd4 275async function autocompleteUsers (req: express.Request, res: express.Response) {
5cf84858 276 const resultList = await UserModel.autoComplete(req.query.search as string)
74d63469
GR
277
278 return res.json(resultList)
279}
280
b426edd4 281async function listUsers (req: express.Request, res: express.Response) {
87a0cac6 282 const resultList = await UserModel.listForAdminApi({
8491293b
RK
283 start: req.query.start,
284 count: req.query.count,
285 sort: req.query.sort,
286 search: req.query.search,
287 blocked: req.query.blocked
288 })
eb080476 289
1eddc9a7 290 return res.json(getFormattedObjects(resultList.data, resultList.total, { withAdminFlags: true }))
9bd26629
C
291}
292
b426edd4 293async function removeUser (req: express.Request, res: express.Response) {
dae86118 294 const user = res.locals.user
eb080476 295
993cef4b 296 auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
80e36cd9 297
fae6e4da
C
298 await sequelizeTypescript.transaction(async t => {
299 // Use a transaction to avoid inconsistencies with hooks (account/channel deletion & federation)
300 await user.destroy({ transaction: t })
301 })
2dbc170d 302
7226e90f 303 Hooks.runAction('action:api.user.deleted', { user, req, res })
6f3fe96f 304
76148b27 305 return res.status(HttpStatusCode.NO_CONTENT_204).end()
9bd26629
C
306}
307
b426edd4 308async function updateUser (req: express.Request, res: express.Response) {
8094a898 309 const body: UserUpdate = req.body
dae86118 310 const userToUpdate = res.locals.user
80e36cd9
AB
311 const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON())
312 const roleChanged = body.role !== undefined && body.role !== userToUpdate.role
8094a898 313
16c016e8
C
314 const keysToUpdate: (keyof UserUpdate)[] = [
315 'password',
316 'email',
317 'emailVerified',
318 'videoQuota',
319 'videoQuotaDaily',
320 'role',
321 'adminFlags',
322 'pluginAuth'
323 ]
324
325 for (const key of keysToUpdate) {
326 if (body[key] !== undefined) userToUpdate.set(key, body[key])
327 }
8094a898 328
80e36cd9 329 const user = await userToUpdate.save()
eb080476 330
f8b8c36b 331 // Destroy user token to refresh rights
f43db2f4 332 if (roleChanged || body.password !== undefined) await OAuthTokenModel.deleteUserToken(userToUpdate.id)
f8b8c36b 333
91411dba 334 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
80e36cd9 335
7226e90f 336 Hooks.runAction('action:api.user.updated', { user, req, res })
6f3fe96f 337
b426edd4 338 // Don't need to send this update to followers, these attributes are not federated
265ba139 339
76148b27 340 return res.status(HttpStatusCode.NO_CONTENT_204).end()
8094a898
C
341}
342
dae86118
C
343async function askResetUserPassword (req: express.Request, res: express.Response) {
344 const user = res.locals.user
ecb4e35f
C
345
346 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
6dd9de95 347 const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
c5f3ff39 348 Emailer.Instance.addPasswordResetEmailJob(user.username, user.email, url)
ecb4e35f 349
2d53be02 350 return res.status(HttpStatusCode.NO_CONTENT_204).end()
ecb4e35f
C
351}
352
dae86118
C
353async function resetUserPassword (req: express.Request, res: express.Response) {
354 const user = res.locals.user
ecb4e35f
C
355 user.password = req.body.password
356
357 await user.save()
e9c5f123 358 await Redis.Instance.removePasswordVerificationString(user.id)
ecb4e35f 359
2d53be02 360 return res.status(HttpStatusCode.NO_CONTENT_204).end()
ecb4e35f
C
361}
362
d1ab89de 363async function reSendVerifyUserEmail (req: express.Request, res: express.Response) {
dae86118 364 const user = res.locals.user
d9eaee39
JM
365
366 await sendVerifyUserEmail(user)
367
2d53be02 368 return res.status(HttpStatusCode.NO_CONTENT_204).end()
d9eaee39
JM
369}
370
dae86118
C
371async function verifyUserEmail (req: express.Request, res: express.Response) {
372 const user = res.locals.user
d9eaee39
JM
373 user.emailVerified = true
374
d1ab89de
C
375 if (req.body.isPendingEmail === true) {
376 user.email = user.pendingEmail
377 user.pendingEmail = null
378 }
379
d9eaee39
JM
380 await user.save()
381
2d53be02 382 return res.status(HttpStatusCode.NO_CONTENT_204).end()
d9eaee39
JM
383}
384
453e83ea 385async function changeUserBlock (res: express.Response, user: MUserAccountDefault, block: boolean, reason?: string) {
e6921918
C
386 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
387
388 user.blocked = block
eacb25c4 389 user.blockedReason = reason || null
e6921918
C
390
391 await sequelizeTypescript.transaction(async t => {
f43db2f4 392 await OAuthTokenModel.deleteUserToken(user.id, t)
e6921918
C
393
394 await user.save({ transaction: t })
395 })
396
eacb25c4
C
397 await Emailer.Instance.addUserBlockJob(user, block, reason)
398
91411dba 399 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
e6921918 400}