]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/users/index.ts
Limit associations fetch when loading token
[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'
5import { getFormattedObjects } from '../../../helpers/utils'
6import { CONFIG, RATES_LIMIT, sequelizeTypescript } from '../../../initializers'
7import { Emailer } from '../../../lib/emailer'
8import { Redis } from '../../../lib/redis'
9import { createUserAccountAndChannel } 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,
20 token,
74d63469 21 userAutocompleteValidator,
f076daa7
C
22 usersAddValidator,
23 usersGetValidator,
24 usersRegisterValidator,
25 usersRemoveValidator,
26 usersSortValidator,
d03cd8bb
C
27 usersUpdateValidator
28} from '../../../middlewares'
d9eaee39 29import {
993cef4b
C
30 usersAskResetPasswordValidator,
31 usersAskSendVerifyEmailValidator,
32 usersBlockingValidator,
33 usersResetPasswordValidator,
34 usersVerifyEmailValidator
d9eaee39 35} from '../../../middlewares/validators'
d03cd8bb
C
36import { UserModel } from '../../../models/account/user'
37import { OAuthTokenModel } from '../../../models/oauth/oauth-token'
993cef4b 38import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger'
d03cd8bb 39import { meRouter } from './me'
80e36cd9
AB
40
41const auditLogger = auditLoggerFactory('users')
65fcc311 42
490b595a
C
43const loginRateLimiter = new RateLimit({
44 windowMs: RATES_LIMIT.LOGIN.WINDOW_MS,
45 max: RATES_LIMIT.LOGIN.MAX,
46 delayMs: 0
47})
c5911fd3 48
288fe385
C
49const askSendEmailLimiter = new RateLimit({
50 windowMs: RATES_LIMIT.ASK_SEND_EMAIL.WINDOW_MS,
51 max: RATES_LIMIT.ASK_SEND_EMAIL.MAX,
52 delayMs: 0
53})
54
65fcc311 55const usersRouter = express.Router()
06a05d5f 56usersRouter.use('/', meRouter)
9bd26629 57
74d63469
GR
58usersRouter.get('/autocomplete',
59 userAutocompleteValidator,
60 asyncMiddleware(autocompleteUsers)
61)
62
65fcc311 63usersRouter.get('/',
86d13ec2
C
64 authenticate,
65 ensureUserHasRight(UserRight.MANAGE_USERS),
65fcc311
C
66 paginationValidator,
67 usersSortValidator,
1174a847 68 setDefaultSort,
f05a1c30 69 setDefaultPagination,
eb080476 70 asyncMiddleware(listUsers)
5c39adb7
C
71)
72
e6921918
C
73usersRouter.post('/:id/block',
74 authenticate,
75 ensureUserHasRight(UserRight.MANAGE_USERS),
76 asyncMiddleware(usersBlockingValidator),
77 asyncMiddleware(blockUser)
78)
79usersRouter.post('/:id/unblock',
80 authenticate,
81 ensureUserHasRight(UserRight.MANAGE_USERS),
82 asyncMiddleware(usersBlockingValidator),
83 asyncMiddleware(unblockUser)
84)
85
8094a898 86usersRouter.get('/:id',
94ff4c23
C
87 authenticate,
88 ensureUserHasRight(UserRight.MANAGE_USERS),
a2431b7d 89 asyncMiddleware(usersGetValidator),
8094a898
C
90 getUser
91)
92
65fcc311
C
93usersRouter.post('/',
94 authenticate,
954605a8 95 ensureUserHasRight(UserRight.MANAGE_USERS),
a2431b7d 96 asyncMiddleware(usersAddValidator),
90d4bb81 97 asyncRetryTransactionMiddleware(createUser)
9bd26629
C
98)
99
65fcc311 100usersRouter.post('/register',
a2431b7d 101 asyncMiddleware(ensureUserRegistrationAllowed),
ff2c1fe8 102 ensureUserRegistrationAllowedForIP,
a2431b7d 103 asyncMiddleware(usersRegisterValidator),
90d4bb81 104 asyncRetryTransactionMiddleware(registerUser)
2c2e9092
C
105)
106
65fcc311
C
107usersRouter.put('/:id',
108 authenticate,
954605a8 109 ensureUserHasRight(UserRight.MANAGE_USERS),
a2431b7d 110 asyncMiddleware(usersUpdateValidator),
eb080476 111 asyncMiddleware(updateUser)
9bd26629
C
112)
113
65fcc311
C
114usersRouter.delete('/:id',
115 authenticate,
954605a8 116 ensureUserHasRight(UserRight.MANAGE_USERS),
a2431b7d 117 asyncMiddleware(usersRemoveValidator),
eb080476 118 asyncMiddleware(removeUser)
9bd26629 119)
6606150c 120
ecb4e35f
C
121usersRouter.post('/ask-reset-password',
122 asyncMiddleware(usersAskResetPasswordValidator),
123 asyncMiddleware(askResetUserPassword)
124)
125
126usersRouter.post('/:id/reset-password',
127 asyncMiddleware(usersResetPasswordValidator),
128 asyncMiddleware(resetUserPassword)
129)
130
d9eaee39 131usersRouter.post('/ask-send-verify-email',
288fe385 132 askSendEmailLimiter,
d9eaee39
JM
133 asyncMiddleware(usersAskSendVerifyEmailValidator),
134 asyncMiddleware(askSendVerifyUserEmail)
135)
136
137usersRouter.post('/:id/verify-email',
138 asyncMiddleware(usersVerifyEmailValidator),
139 asyncMiddleware(verifyUserEmail)
140)
141
490b595a
C
142usersRouter.post('/token',
143 loginRateLimiter,
144 token,
145 success
146)
9bd26629 147// TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
9457bf88
C
148
149// ---------------------------------------------------------------------------
150
65fcc311
C
151export {
152 usersRouter
153}
9457bf88
C
154
155// ---------------------------------------------------------------------------
156
90d4bb81 157async function createUser (req: express.Request, res: express.Response) {
4771e000 158 const body: UserCreate = req.body
f05a1c30 159 const userToCreate = new UserModel({
4771e000
C
160 username: body.username,
161 password: body.password,
162 email: body.email,
0883b324 163 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
7efe153b 164 autoPlayVideo: true,
954605a8 165 role: body.role,
bee0abff
FA
166 videoQuota: body.videoQuota,
167 videoQuotaDaily: body.videoQuotaDaily
9bd26629
C
168 })
169
f05a1c30 170 const { user, account } = await createUserAccountAndChannel(userToCreate)
eb080476 171
993cef4b 172 auditLogger.create(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
38fa2065 173 logger.info('User %s with its channel and account created.', body.username)
f05a1c30 174
90d4bb81
C
175 return res.json({
176 user: {
177 id: user.id,
178 account: {
179 id: account.id,
180 uuid: account.Actor.uuid
181 }
182 }
183 }).end()
47e0652b
C
184}
185
90d4bb81 186async function registerUser (req: express.Request, res: express.Response) {
77a5501f
C
187 const body: UserCreate = req.body
188
80e36cd9 189 const userToCreate = new UserModel({
77a5501f
C
190 username: body.username,
191 password: body.password,
192 email: body.email,
0883b324 193 nsfwPolicy: CONFIG.INSTANCE.DEFAULT_NSFW_POLICY,
7efe153b 194 autoPlayVideo: true,
954605a8 195 role: UserRole.USER,
bee0abff 196 videoQuota: CONFIG.USER.VIDEO_QUOTA,
d9eaee39
JM
197 videoQuotaDaily: CONFIG.USER.VIDEO_QUOTA_DAILY,
198 emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null
77a5501f
C
199 })
200
80e36cd9 201 const { user } = await createUserAccountAndChannel(userToCreate)
47e0652b 202
80e36cd9 203 auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON()))
47e0652b 204 logger.info('User %s with its channel and account registered.', body.username)
90d4bb81 205
d9eaee39
JM
206 if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) {
207 await sendVerifyUserEmail(user)
208 }
209
90d4bb81 210 return res.type('json').status(204).end()
77a5501f
C
211}
212
e6921918
C
213async function unblockUser (req: express.Request, res: express.Response, next: express.NextFunction) {
214 const user: UserModel = res.locals.user
215
216 await changeUserBlock(res, user, false)
217
218 return res.status(204).end()
219}
220
221async function blockUser (req: express.Request, res: express.Response, next: express.NextFunction) {
222 const user: UserModel = res.locals.user
eacb25c4 223 const reason = req.body.reason
e6921918 224
eacb25c4 225 await changeUserBlock(res, user, true, reason)
e6921918
C
226
227 return res.status(204).end()
228}
229
8094a898 230function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
ce5496d6 231 return res.json((res.locals.user as UserModel).toFormattedJSON())
8094a898
C
232}
233
74d63469 234async function autocompleteUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
5cf84858 235 const resultList = await UserModel.autoComplete(req.query.search as string)
74d63469
GR
236
237 return res.json(resultList)
238}
239
eb080476 240async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
3fd3ab2d 241 const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort)
eb080476
C
242
243 return res.json(getFormattedObjects(resultList.data, resultList.total))
9bd26629
C
244}
245
eb080476 246async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
92b9d60c 247 const user: UserModel = res.locals.user
eb080476
C
248
249 await user.destroy()
250
993cef4b 251 auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
80e36cd9 252
eb080476 253 return res.sendStatus(204)
9bd26629
C
254}
255
eb080476 256async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) {
8094a898 257 const body: UserUpdate = req.body
80e36cd9
AB
258 const userToUpdate = res.locals.user as UserModel
259 const oldUserAuditView = new UserAuditView(userToUpdate.toFormattedJSON())
260 const roleChanged = body.role !== undefined && body.role !== userToUpdate.role
8094a898 261
80e36cd9
AB
262 if (body.email !== undefined) userToUpdate.email = body.email
263 if (body.videoQuota !== undefined) userToUpdate.videoQuota = body.videoQuota
bee0abff 264 if (body.videoQuotaDaily !== undefined) userToUpdate.videoQuotaDaily = body.videoQuotaDaily
80e36cd9 265 if (body.role !== undefined) userToUpdate.role = body.role
8094a898 266
80e36cd9 267 const user = await userToUpdate.save()
eb080476 268
f8b8c36b 269 // Destroy user token to refresh rights
91411dba 270 if (roleChanged) await OAuthTokenModel.deleteUserToken(userToUpdate.id)
f8b8c36b 271
91411dba 272 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
80e36cd9 273
265ba139
C
274 // Don't need to send this update to followers, these attributes are not propagated
275
eb080476 276 return res.sendStatus(204)
8094a898
C
277}
278
ecb4e35f
C
279async function askResetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
280 const user = res.locals.user as UserModel
281
282 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
283 const url = CONFIG.WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
284 await Emailer.Instance.addForgetPasswordEmailJob(user.email, url)
285
286 return res.status(204).end()
287}
288
289async function resetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) {
290 const user = res.locals.user as UserModel
291 user.password = req.body.password
292
293 await user.save()
294
295 return res.status(204).end()
296}
297
d9eaee39
JM
298async function sendVerifyUserEmail (user: UserModel) {
299 const verificationString = await Redis.Instance.setVerifyEmailVerificationString(user.id)
300 const url = CONFIG.WEBSERVER.URL + '/verify-account/email?userId=' + user.id + '&verificationString=' + verificationString
301 await Emailer.Instance.addVerifyEmailJob(user.email, url)
302 return
303}
304
305async function askSendVerifyUserEmail (req: express.Request, res: express.Response, next: express.NextFunction) {
306 const user = res.locals.user as UserModel
307
308 await sendVerifyUserEmail(user)
309
310 return res.status(204).end()
311}
312
313async function verifyUserEmail (req: express.Request, res: express.Response, next: express.NextFunction) {
314 const user = res.locals.user as UserModel
315 user.emailVerified = true
316
317 await user.save()
318
319 return res.status(204).end()
320}
321
69818c93 322function success (req: express.Request, res: express.Response, next: express.NextFunction) {
9457bf88
C
323 res.end()
324}
e6921918 325
eacb25c4 326async function changeUserBlock (res: express.Response, user: UserModel, block: boolean, reason?: string) {
e6921918
C
327 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
328
329 user.blocked = block
eacb25c4 330 user.blockedReason = reason || null
e6921918
C
331
332 await sequelizeTypescript.transaction(async t => {
333 await OAuthTokenModel.deleteUserToken(user.id, t)
334
335 await user.save({ transaction: t })
336 })
337
eacb25c4
C
338 await Emailer.Instance.addUserBlockJob(user, block, reason)
339
91411dba 340 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
e6921918 341}