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