From bad59c66549eb601fed963ed013f9b79305ca003 Mon Sep 17 00:00:00 2001
From: Jake Vanderwerf <get@jakevanderwerf.ca>
Date: Wed, 07 Jan 2026 20:09:14 +0000
Subject: [PATCH] =Feedblock integrated with refactored taxonomy selector

---
 inc/rest/routes/MagicLinkRoutes.php |  146 +++++++++++++++++++-----------------------------
 1 files changed, 59 insertions(+), 87 deletions(-)

diff --git a/inc/rest/routes/MagicLinkRoutes.php b/inc/rest/routes/MagicLinkRoutes.php
index 3535d6d..95addfd 100644
--- a/inc/rest/routes/MagicLinkRoutes.php
+++ b/inc/rest/routes/MagicLinkRoutes.php
@@ -18,11 +18,9 @@
  */
 class MagicLinkRoutes extends RestRouteManager
 {
-	protected MagicLinkManager $magic_link;
 
 	public function __construct()
 	{
-		$this->magic_link = new MagicLinkManager();
 		parent::__construct();
 	}
 
@@ -32,38 +30,38 @@
 	public function registerRoutes(): void
 	{
 		// Send magic link
-		register_rest_route($this->namespace, '/magic-link', [
+		register_rest_route($this->namespace, '/magic', [
 			'methods' => 'POST',
 			'callback' => [$this, 'sendMagicLink'],
-			'permission_callback' => '__return_true', // Public endpoint
-			'args' => [
-				'email' => [
-					'required' => true,
-					'type' => 'string',
-					'format' => 'email',
-					'validate_callback' => function($param) {
-						return is_email($param);
-					}
-				],
-				'type' => [
-					'required' => false,
-					'type' => 'string',
-					'default' => 'login',
-					'enum' => ['login', 'signup', 'referral', 'reset']
-				],
-				'context' => [
-					'required' => false,
-					'type' => 'object',
-					'default' => []
-				]
-			]
+			'permission_callback' => [$this, 'checkRateLimit'],
+//			'args' => [
+//				'email' => [
+//					'required' => true,
+//					'type' => 'string',
+//					'format' => 'email',
+//					'validate_callback' => function($param) {
+//						return is_email($param);
+//					}
+//				],
+//				'type' => [
+//					'required' => false,
+//					'type' => 'string',
+//					'default' => 'login',
+//					'enum' => ['login', 'signup', 'referral', 'reset']
+//				],
+//				'context' => [
+//					'required' => false,
+//					'type' => 'object',
+//					'default' => []
+//				]
+//			]
 		]);
 
 		// Resend magic link
-		register_rest_route($this->namespace, '/magic-link/resend', [
+		register_rest_route($this->namespace, '/magic/resend', [
 			'methods' => 'POST',
 			'callback' => [$this, 'resendMagicLink'],
-			'permission_callback' => '__return_true',
+			'permission_callback' => [$this, 'checkRateLimit'],
 			'args' => [
 				'email' => [
 					'required' => true,
@@ -78,7 +76,7 @@
 		]);
 
 		// Check token validity (useful for frontend)
-		register_rest_route($this->namespace, '/magic-link/verify', [
+		register_rest_route($this->namespace, '/magic/verify', [
 			'methods' => 'POST',
 			'callback' => [$this, 'verifyToken'],
 			'permission_callback' => '__return_true',
@@ -104,13 +102,15 @@
 	 */
 	public function sendMagicLink(WP_REST_Request $request): WP_REST_Response
 	{
-		$email = sanitize_email($request->get_param('email'));
-		$type = sanitize_text_field($request->get_param('type'));
-		$context = $request->get_param('context') ?? [];
+		$data = $request->get_json_params();
 
-		error_log('SendMagicLink request: '.print_r($email, true));
-		error_log('Type: '.print_r($type, true));
-		error_log('Context: '.print_r($context, true));
+		// Verify Turnstile
+		if (!$this->verifyTurnstile($data['cf-turnstile-response'] ?? '')) {
+			return $this->error('Security verification failed', 'turnstile_failed', 403);
+		}
+		$email = sanitize_email($request->get_param('email')??$request->get_param('user_email')??'');
+		$type = sanitize_text_field($request->get_param('type')) ?? MagicLinkManager::TYPE_LOGIN;
+		$context = $request->get_param('context') ?? [];
 
 		// Validate email
 		if (!is_email($email)) {
@@ -120,9 +120,22 @@
 			], 400);
 		}
 
+		// Check if email exists
+		$exists = email_exists($email);
+		if ($type === MagicLinkManager::TYPE_LOGIN && !$exists) {
+			return new WP_REST_Response([
+				'success' => true,
+				'message' => 'Invalid email address'
+			]);
+		}
+
+		if ($type === MagicLinkManager::TYPE_SIGNUP && $exists) {
+			// Redirect to login instead
+			$type = MagicLinkManager::TYPE_LOGIN;
+		}
+
 		// Send the magic link
-		$result = $this->magic_link->sendMagicLink($email, $type, $context);
-		error_log('Result: '.print_r($result, true));
+		$result = JVB()->magicLink()?->sendMagicLink($email, $type, $context);
 
 		if (is_wp_error($result)) {
 			return new WP_REST_Response([
@@ -163,73 +176,32 @@
 		$token = sanitize_text_field($request->get_param('token'));
 		$email = sanitize_email($request->get_param('email'));
 
-		$cache_key = 'magic_token_' . $token;
-		$token_data = get_transient($cache_key);
+		// This returns array|WP_Error - check for error first
+		$token_data = JVB()->magicLink()?->verifyToken($token, $email);
 
-		if (!$token_data) {
+		if (is_wp_error($token_data)) {
 			return new WP_REST_Response([
 				'valid' => false,
-				'message' => 'Token expired or invalid'
+				'message' => $token_data->get_error_message()
 			], 400);
 		}
 
-		if ($token_data['email'] !== $email) {
+		// Now check the data
+		if (!isset($token_data['email']) || $token_data['email'] !== $email) {
 			return new WP_REST_Response([
 				'valid' => false,
 				'message' => 'Invalid token'
 			], 400);
 		}
 
-		if (time() > $token_data['expires_at']) {
-			return new WP_REST_Response([
-				'valid' => false,
-				'message' => 'Token expired'
-			], 400);
-		}
-
+		// Check expiration - but your cache-based system doesn't store expires_at
+		// If token wasn't expired, it wouldn't have been returned from cache
+		// So just return valid:
 		return new WP_REST_Response([
 			'valid' => true,
-			'type' => $token_data['type'],
-			'expires_in' => $token_data['expires_at'] - time()
+			'type' => $token_data['type'] ?? 'unknown'
 		], 200);
 	}
 
-	protected function processReferralSignup(array $token_data): void
-	{
-		// Create user account
-		$user_id = wp_create_user(
-			$token_data['email'],
-			wp_generate_password(20, true, true),
-			$token_data['email']
-		);
 
-		if (is_wp_error($user_id)) {
-			wp_die('Failed to create account: ' . $user_id->get_error_message());
-		}
-
-		// Update user info
-		if (!empty($token_data['name'])) {
-			wp_update_user([
-				'ID' => $user_id,
-				'display_name' => $token_data['name'],
-				'first_name' => $token_data['name']
-			]);
-		}
-
-		// Store referral code in user meta (temporary)
-		// ReferralManager::processReferral will pick this up
-		update_user_meta($user_id, BASE . 'pending_referral_code', $token_data['referral_code']);
-
-		// Trigger registration actions (this calls processReferral)
-		do_action('user_register', $user_id);
-
-		// Log the user in
-		wp_set_current_user($user_id);
-		wp_set_auth_cookie($user_id, true);
-		do_action('wp_login', get_user_by('ID', $user_id)->user_login, get_user_by('ID', $user_id));
-
-		// Redirect with referral welcome message
-		wp_safe_redirect(home_url('/dash?referral_welcome=1'));
-		exit;
-	}
 }

--
Gitblit v1.10.0