feat: add customer login page in SPA

- Created Login/index.tsx with styled form
- Added /auth/customer-login API endpoint (no admin perms required)
- Registered route in Routes.php
- Added /login route in customer-spa App.tsx
- Account page now redirects to SPA login instead of wp-login.php
- Login supports redirect param for post-login navigation
This commit is contained in:
Dwindi Ramadhana
2025-12-31 22:43:13 +07:00
parent 3d7eb5bf48
commit 56042d4b8e
5 changed files with 242 additions and 13 deletions

View File

@@ -15,6 +15,7 @@ import Checkout from './pages/Checkout';
import ThankYou from './pages/ThankYou';
import Account from './pages/Account';
import Wishlist from './pages/Wishlist';
import Login from './pages/Login';
// Create QueryClient instance
const queryClient = new QueryClient({
@@ -30,7 +31,7 @@ const queryClient = new QueryClient({
// Get theme config from window (injected by PHP)
const getThemeConfig = () => {
const config = (window as any).woonoowCustomer?.theme;
// Default config if not provided
return config || {
mode: 'full',
@@ -65,28 +66,31 @@ const getInitialRoute = () => {
function AppRoutes() {
const initialRoute = getInitialRoute();
console.log('[WooNooW Customer] Using initial route:', initialRoute);
return (
<BaseLayout>
<Routes>
{/* Root route redirects to initial route based on SPA mode */}
<Route path="/" element={<Navigate to={initialRoute} replace />} />
{/* Shop Routes */}
<Route path="/shop" element={<Shop />} />
<Route path="/product/:slug" element={<Product />} />
{/* Cart & Checkout */}
<Route path="/cart" element={<Cart />} />
<Route path="/checkout" element={<Checkout />} />
<Route path="/order-received/:orderId" element={<ThankYou />} />
{/* Wishlist - Public route accessible to guests */}
<Route path="/wishlist" element={<Wishlist />} />
{/* Login */}
<Route path="/login" element={<Login />} />
{/* My Account */}
<Route path="/my-account/*" element={<Account />} />
{/* Fallback to initial route */}
<Route path="*" element={<Navigate to={initialRoute} replace />} />
</Routes>
@@ -98,14 +102,14 @@ function App() {
const themeConfig = getThemeConfig();
const appearanceSettings = getAppearanceSettings();
const toastPosition = (appearanceSettings?.general?.toast_position || 'top-right') as any;
return (
<QueryClientProvider client={queryClient}>
<ThemeProvider config={themeConfig}>
<HashRouter>
<AppRoutes />
</HashRouter>
{/* Toast notifications - position from settings */}
<Toaster position={toastPosition} richColors />
</ThemeProvider>

View File

@@ -1,5 +1,5 @@
import React from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { Routes, Route, Navigate, useLocation } from 'react-router-dom';
import Container from '@/components/Layout/Container';
import { AccountLayout } from './components/AccountLayout';
import Dashboard from './Dashboard';
@@ -12,11 +12,12 @@ import AccountDetails from './AccountDetails';
export default function Account() {
const user = (window as any).woonoowCustomer?.user;
const location = useLocation();
// Redirect to login if not authenticated
if (!user?.isLoggedIn) {
window.location.href = '/wp-login.php?redirect_to=' + encodeURIComponent(window.location.href);
return null;
const currentPath = location.pathname;
return <Navigate to={`/login?redirect=${encodeURIComponent(currentPath)}`} replace />;
}
return (

View File

@@ -0,0 +1,165 @@
import React, { useState } from 'react';
import { useNavigate, useSearchParams, Link } 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 { LogIn, Eye, EyeOff, ArrowLeft } from 'lucide-react';
export default function Login() {
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const redirectTo = searchParams.get('redirect') || '/my-account';
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [showPassword, setShowPassword] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
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/customer-login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': nonce,
},
credentials: 'include',
body: JSON.stringify({ username, password }),
});
const data = await response.json();
if (data.success) {
// Update window config with new nonce and user data
if ((window as any).woonoowCustomer) {
(window as any).woonoowCustomer.nonce = data.nonce;
(window as any).woonoowCustomer.user = {
isLoggedIn: true,
id: data.user.id,
name: data.user.name,
email: data.user.email,
firstName: data.user.first_name,
lastName: data.user.last_name,
avatar: data.user.avatar,
};
}
toast.success('Login successful!');
// Full page reload to refresh nonce and user state
window.location.href = window.location.origin + '/store/#' + redirectTo;
} else {
setError(data.message || 'Login failed');
}
} catch (err: any) {
setError(err.message || 'An error occurred. Please try again.');
} finally {
setIsLoading(false);
}
};
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="/shop"
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" />
Continue shopping
</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">
<LogIn className="w-8 h-8 text-primary" />
</div>
<h1 className="text-2xl font-bold text-gray-900">Welcome Back</h1>
<p className="text-gray-600 mt-2">Sign in to your account</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="username">Email or Username</Label>
<Input
id="username"
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Enter your email or username"
required
autoComplete="username"
disabled={isLoading}
/>
</div>
<div className="space-y-2">
<Label htmlFor="password">Password</Label>
<div className="relative">
<Input
id="password"
type={showPassword ? 'text' : 'password'}
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter your password"
required
autoComplete="current-password"
disabled={isLoading}
className="pr-10"
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
tabIndex={-1}
>
{showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
</button>
</div>
</div>
<Button
type="submit"
className="w-full"
disabled={isLoading}
>
{isLoading ? 'Signing in...' : 'Sign In'}
</Button>
</form>
{/* Footer links */}
<div className="mt-6 text-center text-sm text-gray-600">
<a
href="/wp-login.php?action=lostpassword"
className="hover:text-primary"
>
Forgot your password?
</a>
</div>
</div>
</div>
</div>
</Container>
);
}