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