From e364e31e25bd1d4b8d801c845a96d6be708f0a18 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 19 Jan 2023 09:27:16 +0100 Subject: Implement signup approval in server --- server/controllers/api/config.ts | 1 + server/controllers/api/users/email-verification.ts | 72 +++++++ server/controllers/api/users/index.ts | 99 +-------- server/controllers/api/users/registrations.ts | 236 +++++++++++++++++++++ 4 files changed, 316 insertions(+), 92 deletions(-) create mode 100644 server/controllers/api/users/email-verification.ts create mode 100644 server/controllers/api/users/registrations.ts (limited to 'server/controllers') diff --git a/server/controllers/api/config.ts b/server/controllers/api/config.ts index f0fb43071..86434f382 100644 --- a/server/controllers/api/config.ts +++ b/server/controllers/api/config.ts @@ -193,6 +193,7 @@ function customConfig (): CustomConfig { signup: { enabled: CONFIG.SIGNUP.ENABLED, limit: CONFIG.SIGNUP.LIMIT, + requiresApproval: CONFIG.SIGNUP.REQUIRES_APPROVAL, requiresEmailVerification: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION, minimumAge: CONFIG.SIGNUP.MINIMUM_AGE }, diff --git a/server/controllers/api/users/email-verification.ts b/server/controllers/api/users/email-verification.ts new file mode 100644 index 000000000..230aaa9af --- /dev/null +++ b/server/controllers/api/users/email-verification.ts @@ -0,0 +1,72 @@ +import express from 'express' +import { HttpStatusCode } from '@shared/models' +import { CONFIG } from '../../../initializers/config' +import { sendVerifyRegistrationEmail, sendVerifyUserEmail } from '../../../lib/user' +import { asyncMiddleware, buildRateLimiter } from '../../../middlewares' +import { + registrationVerifyEmailValidator, + usersAskSendVerifyEmailValidator, + usersVerifyEmailValidator +} from '../../../middlewares/validators' + +const askSendEmailLimiter = buildRateLimiter({ + windowMs: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.WINDOW_MS, + max: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.MAX +}) + +const emailVerificationRouter = express.Router() + +emailVerificationRouter.post([ '/ask-send-verify-email', '/registrations/ask-send-verify-email' ], + askSendEmailLimiter, + asyncMiddleware(usersAskSendVerifyEmailValidator), + asyncMiddleware(reSendVerifyUserEmail) +) + +emailVerificationRouter.post('/:id/verify-email', + asyncMiddleware(usersVerifyEmailValidator), + asyncMiddleware(verifyUserEmail) +) + +emailVerificationRouter.post('/registrations/:registrationId/verify-email', + asyncMiddleware(registrationVerifyEmailValidator), + asyncMiddleware(verifyRegistrationEmail) +) + +// --------------------------------------------------------------------------- + +export { + emailVerificationRouter +} + +async function reSendVerifyUserEmail (req: express.Request, res: express.Response) { + const user = res.locals.user + const registration = res.locals.userRegistration + + if (user) await sendVerifyUserEmail(user) + else if (registration) await sendVerifyRegistrationEmail(registration) + + return res.status(HttpStatusCode.NO_CONTENT_204).end() +} + +async function verifyUserEmail (req: express.Request, res: express.Response) { + const user = res.locals.user + user.emailVerified = true + + if (req.body.isPendingEmail === true) { + user.email = user.pendingEmail + user.pendingEmail = null + } + + await user.save() + + return res.status(HttpStatusCode.NO_CONTENT_204).end() +} + +async function verifyRegistrationEmail (req: express.Request, res: express.Response) { + const registration = res.locals.userRegistration + registration.emailVerified = true + + await registration.save() + + return res.status(HttpStatusCode.NO_CONTENT_204).end() +} diff --git a/server/controllers/api/users/index.ts b/server/controllers/api/users/index.ts index a8677a1d3..5a5a12e82 100644 --- a/server/controllers/api/users/index.ts +++ b/server/controllers/api/users/index.ts @@ -4,26 +4,21 @@ import { Hooks } from '@server/lib/plugins/hooks' import { OAuthTokenModel } from '@server/models/oauth/oauth-token' import { MUserAccountDefault } from '@server/types/models' import { pick } from '@shared/core-utils' -import { HttpStatusCode, UserCreate, UserCreateResult, UserRegister, UserRight, UserUpdate } from '@shared/models' +import { HttpStatusCode, UserCreate, UserCreateResult, UserRight, UserUpdate } from '@shared/models' import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger' import { logger } from '../../../helpers/logger' import { generateRandomString, getFormattedObjects } from '../../../helpers/utils' -import { CONFIG } from '../../../initializers/config' import { WEBSERVER } from '../../../initializers/constants' import { sequelizeTypescript } from '../../../initializers/database' import { Emailer } from '../../../lib/emailer' -import { Notifier } from '../../../lib/notifier' import { Redis } from '../../../lib/redis' -import { buildUser, createUserAccountAndChannelAndPlaylist, sendVerifyUserEmail } from '../../../lib/user' +import { buildUser, createUserAccountAndChannelAndPlaylist } from '../../../lib/user' import { adminUsersSortValidator, asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, - buildRateLimiter, ensureUserHasRight, - ensureUserRegistrationAllowed, - ensureUserRegistrationAllowedForIP, paginationValidator, setDefaultPagination, setDefaultSort, @@ -31,19 +26,17 @@ import { usersAddValidator, usersGetValidator, usersListValidator, - usersRegisterValidator, usersRemoveValidator, usersUpdateValidator } from '../../../middlewares' import { ensureCanModerateUser, usersAskResetPasswordValidator, - usersAskSendVerifyEmailValidator, usersBlockingValidator, - usersResetPasswordValidator, - usersVerifyEmailValidator + usersResetPasswordValidator } from '../../../middlewares/validators' import { UserModel } from '../../../models/user/user' +import { emailVerificationRouter } from './email-verification' import { meRouter } from './me' import { myAbusesRouter } from './my-abuses' import { myBlocklistRouter } from './my-blocklist' @@ -51,22 +44,14 @@ import { myVideosHistoryRouter } from './my-history' import { myNotificationsRouter } from './my-notifications' import { mySubscriptionsRouter } from './my-subscriptions' import { myVideoPlaylistsRouter } from './my-video-playlists' +import { registrationsRouter } from './registrations' import { twoFactorRouter } from './two-factor' const auditLogger = auditLoggerFactory('users') -const signupRateLimiter = buildRateLimiter({ - windowMs: CONFIG.RATES_LIMIT.SIGNUP.WINDOW_MS, - max: CONFIG.RATES_LIMIT.SIGNUP.MAX, - skipFailedRequests: true -}) - -const askSendEmailLimiter = buildRateLimiter({ - windowMs: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.WINDOW_MS, - max: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.MAX -}) - const usersRouter = express.Router() +usersRouter.use('/', emailVerificationRouter) +usersRouter.use('/', registrationsRouter) usersRouter.use('/', twoFactorRouter) usersRouter.use('/', tokensRouter) usersRouter.use('/', myNotificationsRouter) @@ -122,14 +107,6 @@ usersRouter.post('/', asyncRetryTransactionMiddleware(createUser) ) -usersRouter.post('/register', - signupRateLimiter, - asyncMiddleware(ensureUserRegistrationAllowed), - ensureUserRegistrationAllowedForIP, - asyncMiddleware(usersRegisterValidator), - asyncRetryTransactionMiddleware(registerUser) -) - usersRouter.put('/:id', authenticate, ensureUserHasRight(UserRight.MANAGE_USERS), @@ -156,17 +133,6 @@ usersRouter.post('/:id/reset-password', asyncMiddleware(resetUserPassword) ) -usersRouter.post('/ask-send-verify-email', - askSendEmailLimiter, - asyncMiddleware(usersAskSendVerifyEmailValidator), - asyncMiddleware(reSendVerifyUserEmail) -) - -usersRouter.post('/:id/verify-email', - asyncMiddleware(usersVerifyEmailValidator), - asyncMiddleware(verifyUserEmail) -) - // --------------------------------------------------------------------------- export { @@ -218,35 +184,6 @@ async function createUser (req: express.Request, res: express.Response) { }) } -async function registerUser (req: express.Request, res: express.Response) { - const body: UserRegister = req.body - - const userToCreate = buildUser({ - ...pick(body, [ 'username', 'password', 'email' ]), - - emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null - }) - - const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({ - userToCreate, - userDisplayName: body.displayName || undefined, - channelNames: body.channel - }) - - auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON())) - logger.info('User %s with its channel and account registered.', body.username) - - if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) { - await sendVerifyUserEmail(user) - } - - Notifier.Instance.notifyOnNewUserRegistration(user) - - Hooks.runAction('action:api.user.registered', { body, user, account, videoChannel, req, res }) - - return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end() -} - async function unblockUser (req: express.Request, res: express.Response) { const user = res.locals.user @@ -360,28 +297,6 @@ async function resetUserPassword (req: express.Request, res: express.Response) { return res.status(HttpStatusCode.NO_CONTENT_204).end() } -async function reSendVerifyUserEmail (req: express.Request, res: express.Response) { - const user = res.locals.user - - await sendVerifyUserEmail(user) - - return res.status(HttpStatusCode.NO_CONTENT_204).end() -} - -async function verifyUserEmail (req: express.Request, res: express.Response) { - const user = res.locals.user - user.emailVerified = true - - if (req.body.isPendingEmail === true) { - user.email = user.pendingEmail - user.pendingEmail = null - } - - await user.save() - - return res.status(HttpStatusCode.NO_CONTENT_204).end() -} - async function changeUserBlock (res: express.Response, user: MUserAccountDefault, block: boolean, reason?: string) { const oldUserAuditView = new UserAuditView(user.toFormattedJSON()) diff --git a/server/controllers/api/users/registrations.ts b/server/controllers/api/users/registrations.ts new file mode 100644 index 000000000..3d4e0aa18 --- /dev/null +++ b/server/controllers/api/users/registrations.ts @@ -0,0 +1,236 @@ +import express from 'express' +import { Emailer } from '@server/lib/emailer' +import { Hooks } from '@server/lib/plugins/hooks' +import { UserRegistrationModel } from '@server/models/user/user-registration' +import { pick } from '@shared/core-utils' +import { HttpStatusCode, UserRegister, UserRegistrationRequest, UserRegistrationState, UserRight } from '@shared/models' +import { auditLoggerFactory, UserAuditView } from '../../../helpers/audit-logger' +import { logger } from '../../../helpers/logger' +import { CONFIG } from '../../../initializers/config' +import { Notifier } from '../../../lib/notifier' +import { buildUser, createUserAccountAndChannelAndPlaylist, sendVerifyRegistrationEmail, sendVerifyUserEmail } from '../../../lib/user' +import { + acceptOrRejectRegistrationValidator, + asyncMiddleware, + asyncRetryTransactionMiddleware, + authenticate, + buildRateLimiter, + ensureUserHasRight, + ensureUserRegistrationAllowedFactory, + ensureUserRegistrationAllowedForIP, + getRegistrationValidator, + listRegistrationsValidator, + paginationValidator, + setDefaultPagination, + setDefaultSort, + userRegistrationsSortValidator, + usersDirectRegistrationValidator, + usersRequestRegistrationValidator +} from '../../../middlewares' + +const auditLogger = auditLoggerFactory('users') + +const registrationRateLimiter = buildRateLimiter({ + windowMs: CONFIG.RATES_LIMIT.SIGNUP.WINDOW_MS, + max: CONFIG.RATES_LIMIT.SIGNUP.MAX, + skipFailedRequests: true +}) + +const registrationsRouter = express.Router() + +registrationsRouter.post('/registrations/request', + registrationRateLimiter, + asyncMiddleware(ensureUserRegistrationAllowedFactory('request-registration')), + ensureUserRegistrationAllowedForIP, + asyncMiddleware(usersRequestRegistrationValidator), + asyncRetryTransactionMiddleware(requestRegistration) +) + +registrationsRouter.post('/registrations/:registrationId/accept', + authenticate, + ensureUserHasRight(UserRight.MANAGE_REGISTRATIONS), + asyncMiddleware(acceptOrRejectRegistrationValidator), + asyncRetryTransactionMiddleware(acceptRegistration) +) +registrationsRouter.post('/registrations/:registrationId/reject', + authenticate, + ensureUserHasRight(UserRight.MANAGE_REGISTRATIONS), + asyncMiddleware(acceptOrRejectRegistrationValidator), + asyncRetryTransactionMiddleware(rejectRegistration) +) + +registrationsRouter.delete('/registrations/:registrationId', + authenticate, + ensureUserHasRight(UserRight.MANAGE_REGISTRATIONS), + asyncMiddleware(getRegistrationValidator), + asyncRetryTransactionMiddleware(deleteRegistration) +) + +registrationsRouter.get('/registrations', + authenticate, + ensureUserHasRight(UserRight.MANAGE_REGISTRATIONS), + paginationValidator, + userRegistrationsSortValidator, + setDefaultSort, + setDefaultPagination, + listRegistrationsValidator, + asyncMiddleware(listRegistrations) +) + +registrationsRouter.post('/register', + registrationRateLimiter, + asyncMiddleware(ensureUserRegistrationAllowedFactory('direct-registration')), + ensureUserRegistrationAllowedForIP, + asyncMiddleware(usersDirectRegistrationValidator), + asyncRetryTransactionMiddleware(registerUser) +) + +// --------------------------------------------------------------------------- + +export { + registrationsRouter +} + +// --------------------------------------------------------------------------- + +async function requestRegistration (req: express.Request, res: express.Response) { + const body: UserRegistrationRequest = req.body + + const registration = new UserRegistrationModel({ + ...pick(body, [ 'username', 'password', 'email', 'registrationReason' ]), + + accountDisplayName: body.displayName, + channelDisplayName: body.channel?.displayName, + channelHandle: body.channel?.name, + + state: UserRegistrationState.PENDING, + + emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null + }) + + await registration.save() + + if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) { + await sendVerifyRegistrationEmail(registration) + } + + Notifier.Instance.notifyOnNewRegistrationRequest(registration) + + Hooks.runAction('action:api.user.requested-registration', { body, registration, req, res }) + + return res.json(registration.toFormattedJSON()) +} + +// --------------------------------------------------------------------------- + +async function acceptRegistration (req: express.Request, res: express.Response) { + const registration = res.locals.userRegistration + + const userToCreate = buildUser({ + username: registration.username, + password: registration.password, + email: registration.email, + emailVerified: registration.emailVerified + }) + // We already encrypted password in registration model + userToCreate.skipPasswordEncryption = true + + // TODO: handle conflicts if someone else created a channel handle/user handle/user email between registration and approval + + const { user } = await createUserAccountAndChannelAndPlaylist({ + userToCreate, + userDisplayName: registration.accountDisplayName, + channelNames: registration.channelHandle && registration.channelDisplayName + ? { + name: registration.channelHandle, + displayName: registration.channelDisplayName + } + : undefined + }) + + registration.userId = user.id + registration.state = UserRegistrationState.ACCEPTED + registration.moderationResponse = req.body.moderationResponse + + await registration.save() + + logger.info('Registration of %s accepted', registration.username) + + Emailer.Instance.addUserRegistrationRequestProcessedJob(registration) + + return res.sendStatus(HttpStatusCode.NO_CONTENT_204) +} + +async function rejectRegistration (req: express.Request, res: express.Response) { + const registration = res.locals.userRegistration + + registration.state = UserRegistrationState.REJECTED + registration.moderationResponse = req.body.moderationResponse + + await registration.save() + + Emailer.Instance.addUserRegistrationRequestProcessedJob(registration) + + logger.info('Registration of %s rejected', registration.username) + + return res.sendStatus(HttpStatusCode.NO_CONTENT_204) +} + +// --------------------------------------------------------------------------- + +async function deleteRegistration (req: express.Request, res: express.Response) { + const registration = res.locals.userRegistration + + await registration.destroy() + + logger.info('Registration of %s deleted', registration.username) + + return res.sendStatus(HttpStatusCode.NO_CONTENT_204) +} + +// --------------------------------------------------------------------------- + +async function listRegistrations (req: express.Request, res: express.Response) { + const resultList = await UserRegistrationModel.listForApi({ + start: req.query.start, + count: req.query.count, + sort: req.query.sort, + search: req.query.search + }) + + return res.json({ + total: resultList.total, + data: resultList.data.map(d => d.toFormattedJSON()) + }) +} + +// --------------------------------------------------------------------------- + +async function registerUser (req: express.Request, res: express.Response) { + const body: UserRegister = req.body + + const userToCreate = buildUser({ + ...pick(body, [ 'username', 'password', 'email' ]), + + emailVerified: CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION ? false : null + }) + + const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({ + userToCreate, + userDisplayName: body.displayName || undefined, + channelNames: body.channel + }) + + auditLogger.create(body.username, new UserAuditView(user.toFormattedJSON())) + logger.info('User %s with its channel and account registered.', body.username) + + if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION) { + await sendVerifyUserEmail(user) + } + + Notifier.Instance.notifyOnNewDirectRegistration(user) + + Hooks.runAction('action:api.user.registered', { body, user, account, videoChannel, req, res }) + + return res.sendStatus(HttpStatusCode.NO_CONTENT_204) +} -- cgit v1.2.3