]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/users/index.ts
Refactor auth flow
[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, UserRight, UserRole, UserUpdate } from '../../../../shared'
8 import { HttpStatusCode } from '../../../../shared/core-utils/miscs/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/account/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 }
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.sendStatus(HttpStatusCode.NO_CONTENT_204)
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 if (body.password !== undefined) userToUpdate.password = body.password
327 if (body.email !== undefined) userToUpdate.email = body.email
328 if (body.emailVerified !== undefined) userToUpdate.emailVerified = body.emailVerified
329 if (body.videoQuota !== undefined) userToUpdate.videoQuota = body.videoQuota
330 if (body.videoQuotaDaily !== undefined) userToUpdate.videoQuotaDaily = body.videoQuotaDaily
331 if (body.role !== undefined) userToUpdate.role = body.role
332 if (body.adminFlags !== undefined) userToUpdate.adminFlags = body.adminFlags
333 if (body.pluginAuth !== undefined) userToUpdate.pluginAuth = body.pluginAuth
334
335 const user = await userToUpdate.save()
336
337 // Destroy user token to refresh rights
338 if (roleChanged || body.password !== undefined) await OAuthTokenModel.deleteUserToken(userToUpdate.id)
339
340 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
341
342 Hooks.runAction('action:api.user.updated', { user })
343
344 // Don't need to send this update to followers, these attributes are not federated
345
346 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
347 }
348
349 async function askResetUserPassword (req: express.Request, res: express.Response) {
350 const user = res.locals.user
351
352 const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id)
353 const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
354 await Emailer.Instance.addPasswordResetEmailJob(user.username, user.email, url)
355
356 return res.status(HttpStatusCode.NO_CONTENT_204).end()
357 }
358
359 async function resetUserPassword (req: express.Request, res: express.Response) {
360 const user = res.locals.user
361 user.password = req.body.password
362
363 await user.save()
364 await Redis.Instance.removePasswordVerificationString(user.id)
365
366 return res.status(HttpStatusCode.NO_CONTENT_204).end()
367 }
368
369 async function reSendVerifyUserEmail (req: express.Request, res: express.Response) {
370 const user = res.locals.user
371
372 await sendVerifyUserEmail(user)
373
374 return res.status(HttpStatusCode.NO_CONTENT_204).end()
375 }
376
377 async function verifyUserEmail (req: express.Request, res: express.Response) {
378 const user = res.locals.user
379 user.emailVerified = true
380
381 if (req.body.isPendingEmail === true) {
382 user.email = user.pendingEmail
383 user.pendingEmail = null
384 }
385
386 await user.save()
387
388 return res.status(HttpStatusCode.NO_CONTENT_204).end()
389 }
390
391 async function changeUserBlock (res: express.Response, user: MUserAccountDefault, block: boolean, reason?: string) {
392 const oldUserAuditView = new UserAuditView(user.toFormattedJSON())
393
394 user.blocked = block
395 user.blockedReason = reason || null
396
397 await sequelizeTypescript.transaction(async t => {
398 await OAuthTokenModel.deleteUserToken(user.id, t)
399
400 await user.save({ transaction: t })
401 })
402
403 await Emailer.Instance.addUserBlockJob(user, block, reason)
404
405 auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView)
406 }