CI / Tests (PHP 8.2) (pull_request) Successful in 44s
CI / Tests (PHP 8.1) (pull_request) Successful in 46s
CI / No Debug Code (pull_request) Successful in 2s
CI / Coding Standards (pull_request) Successful in 2m46s
CI / PHPStan (pull_request) Successful in 2m51s
CI / Tests (PHP 8.3) (pull_request) Successful in 2m38s
CI / Build Plugin Zip (pull_request) Skipped
A studio admin can generate a shareable group invite link (e.g. for a newsletter) from the Invites page, choosing a required expiry date. Anyone with the link may register while it is valid, in any registration mode: the form collects their own email, they must confirm it via the usual hashed token, and confirming approves the account immediately — group signups never enter the Pending Students queue. - us_invites grows kind (personal/group) and expires_at; an explicit expiry wins over the personal 14-day window. Group links stay pending (multi-use) until revoked or expired. - RegistrationPage: group signups create the account pending with the us_auto_approve marker and send the confirmation email; no auto-login. - EmailConfirmationHandler: auto-approve accounts are approved on confirmation, emailed the approved notice, and redirected to a new us_confirmed=ready notice with a sign-in link. Closes #77 Co-Authored-By: Claude Fable 5 <[email protected]>
280 lines
10 KiB
PHP
280 lines
10 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace Unsupervised\Schedular\Auth;
|
|
|
|
use Unsupervised\Schedular\Payment\StudioSettings;
|
|
use Unsupervised\Schedular\Policy\AcceptanceRepository;
|
|
use Unsupervised\Schedular\Policy\Policy;
|
|
use Unsupervised\Schedular\Policy\PolicyAcceptance;
|
|
use Unsupervised\Schedular\Policy\PolicyRepository;
|
|
use Unsupervised\Schedular\Policy\PolicyVersionRepository;
|
|
use Unsupervised\Schedular\Val;
|
|
|
|
class RegistrationPage {
|
|
|
|
/** Success signal: an invited student was created and logged in. */
|
|
private const RESULT_INVITE = 'invite';
|
|
|
|
/** Success signal: a self-signup was created and must confirm their email. */
|
|
private const RESULT_CONFIRM = 'confirm';
|
|
|
|
/**
|
|
* Success signal: a group-link signup was created and must confirm their
|
|
* email — confirming approves the account immediately (no admin review).
|
|
*/
|
|
private const RESULT_CONFIRM_GROUP = 'confirm_group';
|
|
|
|
public function __construct(
|
|
private InviteRepository $invites,
|
|
private PolicyRepository $policies,
|
|
private PolicyVersionRepository $versions,
|
|
private AcceptanceRepository $acceptances,
|
|
private StudioSettings $settings,
|
|
private RegistrationMailer $mailer,
|
|
) {}
|
|
|
|
/**
|
|
* Renders the student registration shortcode output.
|
|
*
|
|
* @param array<int|string, mixed> $atts Block attributes (`loginPageId`) or
|
|
* shortcode attributes (`login_page_id`).
|
|
*/
|
|
public function render( array $atts ): string {
|
|
if ( is_user_logged_in() ) {
|
|
return '<p>' . esc_html__( 'You already have an account and are logged in.', 'unsupervised-schedular' ) . '</p>';
|
|
}
|
|
|
|
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- token identifies the invite; the form submit is nonce-checked below.
|
|
$token = sanitize_text_field( Val::string( wp_unslash( $_REQUEST['us_invite'] ?? '' ) ) );
|
|
// Only the token's hash is stored, so hash the submitted token for lookup.
|
|
$invite = '' !== $token ? $this->invites->findByToken( Invite::hashToken( $token ) ) : null;
|
|
$open = $this->settings->openRegistrationEnabled();
|
|
|
|
// Only a redeemable invite fixes the form's email to the invited address.
|
|
// A stale token (expired / accepted / revoked) with open registration on
|
|
// must fall back to the normal editable email field, not show — and then
|
|
// fail to submit — the stale invite's address.
|
|
$inviteValid = null !== $invite && $invite->isAcceptable( current_time( 'mysql' ) );
|
|
|
|
$error = '';
|
|
$successType = '';
|
|
|
|
if ( isset( $_POST['us_register'] ) && check_admin_referer( 'us_student_register' ) ) {
|
|
$result = $this->handleSubmit( $invite, $open );
|
|
if ( in_array( $result, [ self::RESULT_INVITE, self::RESULT_CONFIRM, self::RESULT_CONFIRM_GROUP ], true ) ) {
|
|
$successType = $result;
|
|
} else {
|
|
$error = $result;
|
|
}
|
|
}
|
|
|
|
// Result of an email-confirmation link (set by EmailConfirmationHandler's redirect).
|
|
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only display flag, not a state change.
|
|
$confirmResult = sanitize_key( Val::string( wp_unslash( $_GET['us_confirmed'] ?? '' ) ) );
|
|
|
|
// Where the post-confirmation prompt sends students to sign in.
|
|
$loginUrl = $this->loginUrl( Val::int( $atts['loginPageId'] ?? $atts['login_page_id'] ?? 0 ) );
|
|
|
|
$policyForms = $this->signupPolicies();
|
|
$canRegister = $open || $inviteValid;
|
|
|
|
ob_start();
|
|
include USC_PLUGIN_DIR . 'templates/frontend/register-page.php';
|
|
return (string) ob_get_clean();
|
|
}
|
|
|
|
/**
|
|
* Redirect to the configured registration page when an invite token lands
|
|
* elsewhere (e.g. a link generated before the page was selected). Hooked on
|
|
* `template_redirect`.
|
|
*/
|
|
public function maybeRedirectToRegistrationPage(): void {
|
|
if ( is_admin() ) {
|
|
return;
|
|
}
|
|
|
|
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only token used only to build the redirect target.
|
|
$token = sanitize_text_field( Val::string( wp_unslash( $_GET['us_invite'] ?? '' ) ) );
|
|
if ( '' === $token ) {
|
|
return;
|
|
}
|
|
|
|
$pageId = Val::int( get_option( RegistrationController::OPTION_PAGE, 0 ) );
|
|
if ( $pageId <= 0 || is_page( $pageId ) ) {
|
|
return;
|
|
}
|
|
|
|
wp_safe_redirect( add_query_arg( 'us_invite', rawurlencode( $token ), (string) get_permalink( $pageId ) ) );
|
|
exit;
|
|
}
|
|
|
|
/**
|
|
* Process the submitted registration. Returns a success signal
|
|
* ({@see RESULT_INVITE} or {@see RESULT_CONFIRM}) or an error message string
|
|
* on failure.
|
|
*
|
|
* The invite branch is tried first, so an invited student always completes
|
|
* signup regardless of whether open registration is enabled.
|
|
*/
|
|
private function handleSubmit( ?Invite $invite, bool $open ): string {
|
|
$inviteValid = null !== $invite && $invite->isAcceptable( current_time( 'mysql' ) );
|
|
|
|
if ( ! $inviteValid && ! $open ) {
|
|
return esc_html__( 'This invitation is invalid, expired, or has already been used.', 'unsupervised-schedular' );
|
|
}
|
|
|
|
// The submit nonce is verified by the caller (render) before this runs.
|
|
// phpcs:disable WordPress.Security.NonceVerification.Missing
|
|
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- passwords must not be sanitized.
|
|
$password = Val::string( wp_unslash( $_POST['password'] ?? '' ) );
|
|
$displayName = sanitize_text_field( Val::string( wp_unslash( $_POST['display_name'] ?? '' ) ) );
|
|
|
|
if ( strlen( $password ) < 8 ) {
|
|
return esc_html__( 'Please choose a password of at least 8 characters.', 'unsupervised-schedular' );
|
|
}
|
|
|
|
// The email is fixed by a personal invite; group-link signups and
|
|
// self-signups supply their own.
|
|
if ( $inviteValid && ! $invite->isGroup() ) {
|
|
$email = $invite->email;
|
|
} else {
|
|
$email = sanitize_email( Val::string( wp_unslash( $_POST['email'] ?? '' ) ) );
|
|
if ( ! is_email( $email ) ) {
|
|
return esc_html__( 'Please enter a valid email address.', 'unsupervised-schedular' );
|
|
}
|
|
}
|
|
|
|
$policyForms = $this->signupPolicies();
|
|
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- each element is coerced to a positive int in the array_map callback; slashes cannot survive integer coercion.
|
|
$accepted = array_map( static fn( mixed $v ): int => absint( Val::int( $v ) ), (array) ( $_POST['accept'] ?? [] ) );
|
|
// phpcs:enable WordPress.Security.NonceVerification.Missing
|
|
|
|
foreach ( $policyForms as $form ) {
|
|
if ( ! in_array( (int) $form['version']->id, $accepted, true ) ) {
|
|
return esc_html__( 'You must accept all required policies to register.', 'unsupervised-schedular' );
|
|
}
|
|
}
|
|
|
|
if ( email_exists( $email ) ) {
|
|
return esc_html__( 'An account already exists for this email.', 'unsupervised-schedular' );
|
|
}
|
|
|
|
$userId = wp_insert_user(
|
|
[
|
|
'user_login' => $email,
|
|
'user_email' => $email,
|
|
'user_pass' => $password,
|
|
'display_name' => '' !== $displayName ? $displayName : $email,
|
|
'role' => $inviteValid ? $invite->role : RoleManager::STUDENT,
|
|
]
|
|
);
|
|
|
|
if ( is_wp_error( $userId ) ) {
|
|
return esc_html__( 'Could not create the account. Please contact the studio.', 'unsupervised-schedular' );
|
|
}
|
|
|
|
$this->recordAcceptances( $policyForms, (int) $userId );
|
|
|
|
if ( $inviteValid && ! $invite->isGroup() ) {
|
|
$this->invites->markAccepted( (int) $invite->id, (int) $userId );
|
|
|
|
wp_set_current_user( (int) $userId );
|
|
wp_set_auth_cookie( (int) $userId );
|
|
|
|
return self::RESULT_INVITE;
|
|
}
|
|
|
|
// Group-link signups and self-signups both stay pending until they
|
|
// confirm their email; the group link is multi-use so it is never marked
|
|
// accepted. A group signup auto-approves on confirmation — no admin
|
|
// review — while a self-signup then waits for studio approval.
|
|
$autoApprove = $inviteValid && $invite->isGroup();
|
|
|
|
$rawToken = RegistrationStatus::markPending( (int) $userId, $autoApprove );
|
|
$user = get_user_by( 'id', (int) $userId );
|
|
if ( $user instanceof \WP_User ) {
|
|
$this->mailer->sendConfirmation( $user, $this->confirmUrl( $rawToken ) );
|
|
}
|
|
|
|
return $autoApprove ? self::RESULT_CONFIRM_GROUP : self::RESULT_CONFIRM;
|
|
}
|
|
|
|
/**
|
|
* URL the post-confirmation sign-in link points to: the chosen login page
|
|
* when one is configured (and still exists), otherwise the WordPress login
|
|
* screen.
|
|
*/
|
|
private function loginUrl( int $loginPageId ): string {
|
|
if ( $loginPageId > 0 ) {
|
|
$url = get_permalink( $loginPageId );
|
|
|
|
if ( is_string( $url ) ) {
|
|
return $url;
|
|
}
|
|
}
|
|
|
|
return wp_login_url();
|
|
}
|
|
|
|
/**
|
|
* Build the email-confirmation URL for a raw token: the configured
|
|
* registration page (falling back to the home page) with `?us_confirm=`.
|
|
*/
|
|
private function confirmUrl( string $rawToken ): string {
|
|
$pageId = Val::int( get_option( RegistrationController::OPTION_PAGE, 0 ) );
|
|
$base = $pageId > 0 ? (string) get_permalink( $pageId ) : home_url( '/' );
|
|
|
|
return add_query_arg( 'us_confirm', rawurlencode( $rawToken ), $base );
|
|
}
|
|
|
|
/**
|
|
* Record account-time acceptances for each signup policy version.
|
|
*
|
|
* @param list<array{policy: Policy, version: \Unsupervised\Schedular\Policy\PolicyVersion}> $policyForms
|
|
*/
|
|
private function recordAcceptances( array $policyForms, int $userId ): void {
|
|
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- IP is stored verbatim for audit.
|
|
$ip = sanitize_text_field( Val::string( wp_unslash( $_SERVER['REMOTE_ADDR'] ?? '' ) ) );
|
|
|
|
foreach ( $policyForms as $form ) {
|
|
$this->acceptances->insert(
|
|
new PolicyAcceptance(
|
|
policyVersionId: (int) $form['version']->id,
|
|
studentId: $userId,
|
|
registrationType: PolicyAcceptance::REG_ACCOUNT,
|
|
registrationId: $userId,
|
|
ipAddress: '' !== $ip ? $ip : null,
|
|
)
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Signup-scoped policies that have a current published version.
|
|
*
|
|
* @return list<array{policy: Policy, version: \Unsupervised\Schedular\Policy\PolicyVersion}>
|
|
*/
|
|
private function signupPolicies(): array {
|
|
$out = [];
|
|
|
|
foreach ( $this->policies->findForScope( Policy::SCOPE_SIGNUP ) as $policy ) {
|
|
if ( null === $policy->currentVersionId ) {
|
|
continue;
|
|
}
|
|
|
|
$version = $this->versions->findById( $policy->currentVersionId );
|
|
if ( null === $version || ! $version->isPublished() ) {
|
|
continue;
|
|
}
|
|
|
|
$out[] = [
|
|
'policy' => $policy,
|
|
'version' => $version,
|
|
];
|
|
}
|
|
|
|
return $out;
|
|
}
|
|
}
|