From 4089ba01e0881c89a72332e13bc3a80b6bddec2a Mon Sep 17 00:00:00 2001
From: Jake Vanderwerf <get@jakevanderwerf.ca>
Date: Mon, 29 Jun 2026 22:15:55 +0000
Subject: [PATCH] =DashboardManager overhaul. A bit easier to modify the output of pages. Still have to get the account pages to work as expected, as well as verify the integrations and others are working - but registrar/content pages work as expected. Also fixed up the table generation in CRUD.js and CRUDSkeleton.php

---
 inc/managers/MagicLinkManager.php |  138 +++++++++++++++++++++++++++++++--------------
 1 files changed, 95 insertions(+), 43 deletions(-)

diff --git a/inc/managers/MagicLinkManager.php b/inc/managers/MagicLinkManager.php
index c8d0a88..8d642f5 100644
--- a/inc/managers/MagicLinkManager.php
+++ b/inc/managers/MagicLinkManager.php
@@ -1,6 +1,10 @@
 <?php
 namespace JVBase\managers;
 
+use JetBrains\PhpStorm\NoReturn;
+use JVBase\base\Site;
+use JVBase\meta\Form;
+use JVBase\ui\Tabs;
 use WP_User;
 use WP_Error;
 
@@ -54,32 +58,25 @@
 		// Validate email
 		$email = sanitize_email($email);
 		if (!is_email($email)) {
+			error_log('Invalid email for Magic Link: '.$email);
 			return new WP_Error('invalid_email', 'Invalid email address');
 		}
 
 		// Check rate limiting
 		$rate_check = $this->checkRateLimit($email);
 		if (is_wp_error($rate_check)) {
+			error_log('Rate limit reached for Magic Link: '.$email);
 			return $rate_check;
 		}
 
 		// Handle different link types
-		switch ($type) {
-			case self::TYPE_LOGIN:
-				return $this->sendLoginLink($email, $context);
-
-			case self::TYPE_SIGNUP:
-				return $this->sendSignupLink($email, $context);
-
-			case self::TYPE_REFERRAL:
-				return $this->sendReferralLink($email, $context);
-
-			case self::TYPE_RESET:
-				return $this->sendResetLink($email, $context);
-
-			default:
-				return new WP_Error('invalid_type', 'Invalid magic link type');
-		}
+		return match ($type) {
+			self::TYPE_LOGIN => $this->sendLoginLink($email, $context),
+			self::TYPE_SIGNUP => $this->sendSignupLink($email, $context),
+			self::TYPE_REFERRAL => $this->sendReferralLink($email, $context),
+			self::TYPE_RESET => $this->sendResetLink($email, $context),
+			default => new WP_Error('invalid_type', 'Invalid magic link type'),
+		};
 	}
 
 	/**
@@ -176,7 +173,8 @@
 	{
 		$user = get_user_by('email', $email);
 		if (!$user) {
-			return new WP_Error('user_not_found', 'No account found with this email');
+			error_log('Attempted signin with no account, redirecting to signup link '.$email);
+			return $this->sendSignupLink($email, $context);
 		}
 
 		$token = $this->generateToken($email, self::TYPE_LOGIN, [
@@ -213,7 +211,7 @@
 
 		$token_data = [
 			'name' => $context['name'] ?? '',
-			'role' => $context['role'] ?? 'subscriber',
+			'role' => $context['role'] ?? Site::getDefaultRole(),
 			'meta' => $context['meta'] ?? []
 		];
 
@@ -301,7 +299,7 @@
 	 */
 	public function handleMagicLinkClick(): void
 	{
-		if (!isset($_GET['action']) || !isset($_GET['magic_token']) || !isset($_GET['email'])) {
+		if (!isset($_GET['magic_token']) || !isset($_GET['action']) || !isset($_GET['email'])) {
 			return;
 		}
 
@@ -316,7 +314,7 @@
 		$token_data = $this->verifyToken($token, $email);
 
 		if (is_wp_error($token_data)) {
-			$this->handleInvalidToken($token_data);
+			$this->cleanURL();
 			return;
 		}
 
@@ -339,6 +337,19 @@
 		}
 	}
 
+	#[NoReturn] protected function cleanURL():void
+	{
+		global $wp;
+		$redirect = isset($_GET['redirect_to']) ? esc_url_raw($_GET['redirect_to']) : get_home_url(null, '/'.$wp->request);
+		if (isset($_GET['magic_token'])) {
+			error_log('============= Redirecting and removing magic token stuffs =============');
+			wp_safe_redirect(remove_query_arg(['magic_token', 'action', 'email'], esc_url($redirect)));
+			exit;
+		}
+		wp_safe_redirect(esc_url($redirect));
+		exit;
+	}
+
 	/**
 	 * Process login via magic link
 	 */
@@ -355,21 +366,17 @@
 		wp_set_auth_cookie($user->ID, true);
 
 		do_action('wp_login', $user->user_login, $user);
-
-		$redirect = isset($_GET['redirect_to']) ? esc_url_raw($_GET['redirect_to']) : home_url('/dash');
-
-		wp_safe_redirect($redirect);
-		exit;
+		$this->cleanURL();
 	}
 
 	/**
 	 * Process signup via magic link
 	 */
-	protected function processSignup(array $token_data): void
+	#[NoReturn] protected function processSignup(array $token_data): void
 	{
 		if (!array_key_exists('email', $token_data) || !array_key_exists('name', $token_data)) {
-			JVB()->error()->log('[MagicLinkManager]Could not process Signup');
-			return;
+			JVB()->error()->log('MagicLinkManager', 'Could not process Signup');
+			$this->cleanURL();
 		}
 		$user_id = wp_create_user(
 			$token_data['email'],
@@ -378,7 +385,7 @@
 		);
 
 		if (is_wp_error($user_id)) {
-			wp_die('Failed to create account: ' . $user_id->get_error_message());
+			$this->cleanURL();
 		}
 
 		$user = get_user_by('ID', $user_id);
@@ -401,11 +408,9 @@
 		wp_set_current_user($user_id);
 		wp_set_auth_cookie($user_id, true);
 
-		do_action('user_register', $user_id);
 		do_action('wp_login', $user->user_login, $user);
 
-		wp_safe_redirect(home_url('/dash?welcome=1'));
-		exit;
+		$this->cleanURL();
 	}
 
 	/**
@@ -423,8 +428,9 @@
 
 		$email = sanitize_email($token_data['email']);
 		if (email_exists($email)) {
-			wp_die('Looks like you already have an account!');
+			$this->processSignup($token_data);
 		}
+
 		$role = JVB()->referrals()->getRole();
 		$pass = wp_generate_password(20, true, true);
 		$name = sanitize_text_field($token_data['name']);
@@ -447,6 +453,7 @@
 				$user_id->get_error_message(),
 				$token_data
 			);
+			$this->cleanURL();
 		}
 	}
 
@@ -458,26 +465,22 @@
 		$user = get_user_by('ID', $token_data['user_id']);
 
 		if (!$user) {
-			wp_die('Invalid user');
+			JVB()->error()->log(
+				'MagicLinkManager',
+				'Invalid user, could not reset password',
+			);
+			$this->cleanURL();
 		}
 
 		// Log user in and redirect to password change page
 		wp_set_current_user($user->ID);
 		wp_set_auth_cookie($user->ID, true);
-
+		//TODO: hmmm
 		wp_safe_redirect(admin_url('profile.php?password_reset=1'));
 		exit;
 	}
 
 	/**
-	 * Handle invalid token
-	 */
-	protected function handleInvalidToken(WP_Error $error): void
-	{
-		wp_die($error->get_error_message());
-	}
-
-	/**
 	 * Handle failed login - offer magic link option
 	 */
 	public function handleFailedLogin(string $username): void
@@ -557,4 +560,53 @@
 
 		return $content;
 	}
+
+	public function renderForm():string
+	{
+		ob_start();
+		JVB()->connect('cloudflare')->renderTurnstile();
+		$turnstile = ob_get_clean();
+		global $wp;
+
+		 $magicLink = sprintf(
+			'<form id="magic-link-form" data-save="auth/magic">
+				%s%s
+				<input type="hidden" name="redirect_to" value="%s">
+				%s
+				<button type="submit">%sLogin with Magic Link</button>
+				<p class="hint"><a href="" data-tab="login">Prefer to use a password?</a></p>
+			</form>
+			<div class="success-content" hidden>
+				<h3>Check Your Email!</h3>
+				<p>We\'ve sent you a magic link to log in - no password required! Click the link in your email to log in.</p>
+				<p class="hint">Can\'t find it? Check your spam folder.</p>
+			</div>',
+			jvbFormStatus(),
+			Form::render('user_email', null, [
+				'required'	=> true,
+				'type'		=> 'email',
+				'label'		=> 'Your Email',
+				'autocomplete'=>'email'
+			]),
+			get_home_url(null,'/'.$wp->request),
+			$turnstile,
+			jvbIcon('magic-wand'),
+//			wp_login_url()
+		);
+
+		 $login = LoginManager::getInstance()->renderLoginForm('login', get_home_url(null,'/'.$wp->request));
+
+		 $tabs = new Tabs();
+		 $tabs->addTab('magic')
+			 ->title('With Magic Link')
+			 ->icon('magic-wand')
+			 ->content($magicLink);
+
+		 $tabs->addTab('login')
+			 ->title('With Password')
+			 ->icon('password')
+			 ->content($login);
+
+		 return $tabs->render();
+	}
 }

--
Gitblit v1.10.0