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