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