fix: use customer-spa for password reset page

Changed reset link URL from admin SPA to customer-spa:
- Old: /wp-admin/admin.php?page=woonoow#/reset-password?key=...
- New: /my-account#/reset-password?key=...

This fixes the login redirect issue - the customer-spa is publicly
accessible so users can reset their password without logging in first.

Added:
- customer-spa/src/pages/ResetPassword/index.tsx
- Route /reset-password in customer-spa App.tsx

EmailManager.php now:
- Uses wc_get_page_id('myaccount') to get my-account page URL
- Falls back to home_url if my-account page not found
This commit is contained in:
Dwindi Ramadhana
2026-01-03 17:09:00 +07:00
parent 316fcbf2f0
commit a98217897c
3 changed files with 313 additions and 4 deletions

View File

@@ -17,6 +17,7 @@ import Account from './pages/Account';
import Wishlist from './pages/Wishlist'; import Wishlist from './pages/Wishlist';
import Login from './pages/Login'; import Login from './pages/Login';
import ForgotPassword from './pages/ForgotPassword'; import ForgotPassword from './pages/ForgotPassword';
import ResetPassword from './pages/ResetPassword';
// Create QueryClient instance // Create QueryClient instance
const queryClient = new QueryClient({ const queryClient = new QueryClient({
@@ -89,6 +90,7 @@ function AppRoutes() {
{/* Login & Auth */} {/* Login & Auth */}
<Route path="/login" element={<Login />} /> <Route path="/login" element={<Login />} />
<Route path="/forgot-password" element={<ForgotPassword />} /> <Route path="/forgot-password" element={<ForgotPassword />} />
<Route path="/reset-password" element={<ResetPassword />} />
{/* My Account */} {/* My Account */}
<Route path="/my-account/*" element={<Account />} /> <Route path="/my-account/*" element={<Account />} />

View File

@@ -0,0 +1,300 @@
import React, { useState, useEffect } from 'react';
import { Link, useSearchParams, useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import Container from '@/components/Layout/Container';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { KeyRound, ArrowLeft, Eye, EyeOff, CheckCircle, AlertCircle, Loader2 } from 'lucide-react';
export default function ResetPassword() {
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const key = searchParams.get('key') || '';
const login = searchParams.get('login') || '';
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [showPassword, setShowPassword] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [isValidating, setIsValidating] = useState(true);
const [isValid, setIsValid] = useState(false);
const [error, setError] = useState('');
const [isSuccess, setIsSuccess] = useState(false);
// Validate the reset key on mount
useEffect(() => {
const validateKey = async () => {
if (!key || !login) {
setError('Invalid password reset link. Please request a new one.');
setIsValidating(false);
return;
}
try {
const apiRoot = (window as any).woonoowCustomer?.apiRoot || '/wp-json/woonoow/v1';
const nonce = (window as any).woonoowCustomer?.nonce || '';
const response = await fetch(`${apiRoot}/auth/validate-reset-key`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': nonce,
},
credentials: 'include',
body: JSON.stringify({ key, login }),
});
const data = await response.json();
if (response.ok && data.valid) {
setIsValid(true);
} else {
setError(data.message || 'This password reset link has expired or is invalid.');
}
} catch (err) {
setError('Unable to validate reset link. Please try again later.');
} finally {
setIsValidating(false);
}
};
validateKey();
}, [key, login]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
if (password !== confirmPassword) {
setError('Passwords do not match');
return;
}
if (password.length < 8) {
setError('Password must be at least 8 characters long');
return;
}
setIsLoading(true);
try {
const apiRoot = (window as any).woonoowCustomer?.apiRoot || '/wp-json/woonoow/v1';
const nonce = (window as any).woonoowCustomer?.nonce || '';
const response = await fetch(`${apiRoot}/auth/reset-password`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': nonce,
},
credentials: 'include',
body: JSON.stringify({ key, login, password }),
});
const data = await response.json();
if (response.ok && data.success) {
setIsSuccess(true);
toast.success('Password reset successfully!');
} else {
setError(data.message || 'Failed to reset password. Please try again.');
}
} catch (err: any) {
setError(err.message || 'An error occurred. Please try again later.');
} finally {
setIsLoading(false);
}
};
// Password strength indicator
const getPasswordStrength = (pwd: string) => {
if (pwd.length === 0) return { label: '', color: '', width: '0%' };
if (pwd.length < 8) return { label: 'Too short', color: 'bg-red-500', width: '25%' };
let strength = 0;
if (pwd.length >= 8) strength++;
if (pwd.length >= 12) strength++;
if (/[a-z]/.test(pwd) && /[A-Z]/.test(pwd)) strength++;
if (/\d/.test(pwd)) strength++;
if (/[!@#$%^&*(),.?":{}|<>]/.test(pwd)) strength++;
if (strength <= 2) return { label: 'Weak', color: 'bg-orange-500', width: '50%' };
if (strength <= 3) return { label: 'Medium', color: 'bg-yellow-500', width: '75%' };
return { label: 'Strong', color: 'bg-green-500', width: '100%' };
};
const passwordStrength = getPasswordStrength(password);
// Loading state
if (isValidating) {
return (
<Container>
<div className="min-h-[60vh] flex items-center justify-center py-12">
<div className="w-full max-w-md">
<div className="bg-white rounded-2xl shadow-xl p-8 border text-center">
<Loader2 className="w-8 h-8 animate-spin text-primary mx-auto mb-4" />
<p className="text-gray-600">Validating reset link...</p>
</div>
</div>
</div>
</Container>
);
}
// Success state
if (isSuccess) {
return (
<Container>
<div className="min-h-[60vh] flex items-center justify-center py-12">
<div className="w-full max-w-md">
<div className="bg-white rounded-2xl shadow-xl p-8 border text-center">
<div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
<CheckCircle className="w-8 h-8 text-green-600" />
</div>
<h1 className="text-2xl font-bold text-gray-900 mb-2">Password Reset!</h1>
<p className="text-gray-600 mb-6">
Your password has been successfully updated. You can now log in with your new password.
</p>
<Link to="/login">
<Button className="w-full">Sign In</Button>
</Link>
</div>
</div>
</div>
</Container>
);
}
// Error state (invalid key)
if (!isValid && error) {
return (
<Container>
<div className="min-h-[60vh] flex items-center justify-center py-12">
<div className="w-full max-w-md">
<div className="bg-white rounded-2xl shadow-xl p-8 border text-center">
<div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
<AlertCircle className="w-8 h-8 text-red-600" />
</div>
<h1 className="text-2xl font-bold text-gray-900 mb-2">Invalid Reset Link</h1>
<p className="text-gray-600 mb-6">{error}</p>
<Link to="/forgot-password">
<Button className="w-full">Request New Link</Button>
</Link>
</div>
</div>
</div>
</Container>
);
}
// Reset form
return (
<Container>
<div className="min-h-[60vh] flex items-center justify-center py-12">
<div className="w-full max-w-md">
{/* Back link */}
<Link
to="/login"
className="inline-flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 mb-6 no-underline"
>
<ArrowLeft className="w-4 h-4" />
Back to login
</Link>
<div className="bg-white rounded-2xl shadow-xl p-8 border">
{/* Header */}
<div className="text-center mb-8">
<div className="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center mx-auto mb-4">
<KeyRound className="w-8 h-8 text-primary" />
</div>
<h1 className="text-2xl font-bold text-gray-900">Reset Your Password</h1>
<p className="text-gray-600 mt-2">
Enter your new password below.
</p>
</div>
{/* Error message */}
{error && (
<div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg mb-6">
{error}
</div>
)}
{/* Form */}
<form onSubmit={handleSubmit} className="space-y-6">
<div className="space-y-2">
<Label htmlFor="password">New Password</Label>
<div className="relative">
<Input
id="password"
type={showPassword ? 'text' : 'password'}
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter new password"
required
disabled={isLoading}
className="pr-10"
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
>
{showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
</button>
</div>
{password && (
<div className="space-y-1">
<div className="h-1 bg-gray-200 rounded-full overflow-hidden">
<div
className={`h-full transition-all ${passwordStrength.color}`}
style={{ width: passwordStrength.width }}
/>
</div>
<p className="text-xs text-gray-500">
Strength: <span className="font-medium">{passwordStrength.label}</span>
</p>
</div>
)}
</div>
<div className="space-y-2">
<Label htmlFor="confirmPassword">Confirm Password</Label>
<Input
id="confirmPassword"
type={showPassword ? 'text' : 'password'}
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
placeholder="Confirm new password"
required
disabled={isLoading}
/>
{confirmPassword && password !== confirmPassword && (
<p className="text-xs text-red-500">Passwords do not match</p>
)}
</div>
<Button
type="submit"
className="w-full"
disabled={isLoading || password !== confirmPassword}
>
{isLoading ? 'Resetting...' : 'Reset Password'}
</Button>
</form>
{/* Footer */}
<div className="mt-6 text-center text-sm text-gray-600">
Remember your password?{' '}
<Link to="/login" className="text-primary hover:underline">
Sign in
</Link>
</div>
</div>
</div>
</div>
</Container>
);
}

View File

@@ -327,12 +327,19 @@ class EmailManager {
return $message; // Use WordPress default return $message; // Use WordPress default
} }
// Build reset URL - use SPA route // Build reset URL - use customer-facing SPA route on my-account page
$admin_url = admin_url('admin.php?page=woonoow'); // The my-account page loads the customer-spa which has the reset-password route
$myaccount_page_id = function_exists('wc_get_page_id') ? wc_get_page_id('myaccount') : 0;
if ($myaccount_page_id > 0) {
$myaccount_url = get_permalink($myaccount_page_id);
} else {
// Fallback to home URL if my-account page doesn't exist
$myaccount_url = home_url('/');
}
// Build SPA reset password URL with hash router format // Build SPA reset password URL with hash router format
// Format: /wp-admin/admin.php?page=woonoow#/reset-password?key=KEY&login=LOGIN // Format: /my-account/#/reset-password?key=KEY&login=LOGIN
$reset_link = $admin_url . '#/reset-password?key=' . $key . '&login=' . rawurlencode($user_login); $reset_link = rtrim($myaccount_url, '/') . '#/reset-password?key=' . $key . '&login=' . rawurlencode($user_login);
// Create a pseudo WC_Customer for template rendering // Create a pseudo WC_Customer for template rendering
$customer = null; $customer = null;