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