feat: Implement standalone admin at /admin with custom login page and auth system

This commit is contained in:
dwindown
2025-11-04 21:28:00 +07:00
parent 549ef12802
commit e161163362
6 changed files with 486 additions and 4 deletions

View File

@@ -1,5 +1,5 @@
import React, { useEffect, useState } from 'react';
import { HashRouter, Routes, Route, NavLink, useLocation, useParams } from 'react-router-dom';
import { HashRouter, Routes, Route, NavLink, useLocation, useParams, Navigate } from 'react-router-dom';
import Dashboard from '@/routes/Dashboard';
import DashboardRevenue from '@/routes/Dashboard/Revenue';
import DashboardOrders from '@/routes/Dashboard/Orders';
@@ -19,6 +19,7 @@ import ProductAttributes from '@/routes/Products/Attributes';
import CouponsIndex from '@/routes/Coupons';
import CouponNew from '@/routes/Coupons/New';
import CustomersIndex from '@/routes/Customers';
import { Login } from '@/routes/Login';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { LayoutDashboard, ReceiptText, Package, Tag, Users, Settings as SettingsIcon, Maximize2, Minimize2, Loader2 } from 'lucide-react';
import { Toaster } from 'sonner';
@@ -394,13 +395,63 @@ function Shell() {
);
}
function AuthWrapper() {
const [isAuthenticated, setIsAuthenticated] = useState(
window.WNW_CONFIG?.isAuthenticated ?? true
);
const [isChecking, setIsChecking] = useState(window.WNW_CONFIG?.standaloneMode ?? false);
const location = useLocation();
useEffect(() => {
if (window.WNW_CONFIG?.standaloneMode) {
fetch(window.WNW_CONFIG.restUrl + '/auth/check', {
credentials: 'include',
})
.then(res => res.json())
.then(data => {
setIsAuthenticated(data.authenticated);
if (data.authenticated && data.user) {
window.WNW_CONFIG.currentUser = data.user;
}
})
.catch(() => setIsAuthenticated(false))
.finally(() => setIsChecking(false));
}
}, []);
if (isChecking) {
return (
<div className="flex items-center justify-center min-h-screen">
<Loader2 className="w-12 h-12 animate-spin text-primary" />
</div>
);
}
if (window.WNW_CONFIG?.standaloneMode && !isAuthenticated && location.pathname !== '/login') {
return <Navigate to="/login" replace />;
}
if (location.pathname === '/login' && isAuthenticated) {
return <Navigate to="/dashboard" replace />;
}
return (
<DashboardProvider>
<Shell />
</DashboardProvider>
);
}
export default function App() {
return (
<QueryClientProvider client={qc}>
<HashRouter>
<DashboardProvider>
<Shell />
</DashboardProvider>
<Routes>
{window.WNW_CONFIG?.standaloneMode && (
<Route path="/login" element={<Login />} />
)}
<Route path="/*" element={<AuthWrapper />} />
</Routes>
<Toaster
richColors
theme="light"

View File

@@ -0,0 +1,59 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive:
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
}
)
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
))
Alert.displayName = "Alert"
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
{...props}
/>
))
AlertTitle.displayName = "AlertTitle"
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm [&_p]:leading-relaxed", className)}
{...props}
/>
))
AlertDescription.displayName = "AlertDescription"
export { Alert, AlertTitle, AlertDescription }

View File

@@ -0,0 +1,153 @@
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Loader2, ArrowLeft } from 'lucide-react';
import { __ } from '@/lib/i18n';
export function Login() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState('');
const navigate = useNavigate();
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
setIsLoading(true);
setError('');
try {
const response = await fetch(window.WNW_CONFIG.restUrl + '/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify({ username, password }),
});
const data = await response.json();
if (response.ok && data.success) {
// Update global config
window.WNW_CONFIG.isAuthenticated = true;
window.WNW_CONFIG.currentUser = data.user;
window.WNW_CONFIG.nonce = data.nonce;
// Redirect to dashboard
navigate('/dashboard');
// Reload to ensure all auth state is fresh
window.location.reload();
} else {
setError(data.message || __('Invalid username or password'));
}
} catch (err) {
console.error('Login error:', err);
setError(__('Login failed. Please try again.'));
} finally {
setIsLoading(false);
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-gray-900 dark:to-gray-800 p-4">
<div className="w-full max-w-md">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl p-8">
{/* Logo */}
<div className="text-center mb-8">
<h1 className="text-3xl font-bold text-gray-900 dark:text-white">
WooNooW
</h1>
<p className="text-gray-600 dark:text-gray-400 mt-2">
{__('Sign in to your admin dashboard')}
</p>
</div>
{/* Error Alert */}
{error && (
<Alert variant="destructive" className="mb-6">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* Login Form */}
<form onSubmit={handleLogin} className="space-y-6">
<div>
<Label htmlFor="username">{__('Username or Email')}</Label>
<Input
id="username"
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder={__('Enter your username')}
required
disabled={isLoading}
className="mt-1"
autoComplete="username"
/>
</div>
<div>
<Label htmlFor="password">{__('Password')}</Label>
<Input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder={__('Enter your password')}
required
disabled={isLoading}
className="mt-1"
autoComplete="current-password"
/>
</div>
<Button
type="submit"
className="w-full"
disabled={isLoading}
>
{isLoading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{__('Signing in...')}
</>
) : (
__('Sign In')
)}
</Button>
</form>
{/* Footer Links */}
<div className="mt-6 space-y-3">
<a
href={window.WNW_CONFIG.wpAdminUrl}
className="flex items-center justify-center gap-2 text-sm text-blue-600 hover:text-blue-700 dark:text-blue-400 transition-colors"
>
<ArrowLeft className="w-4 h-4" />
{__('Back to WordPress Admin')}
</a>
<div className="text-center">
<a
href={window.WNW_CONFIG.siteUrl + '/wp-login.php?action=lostpassword'}
className="text-sm text-gray-600 hover:text-gray-700 dark:text-gray-400 transition-colors"
>
{__('Forgot password?')}
</a>
</div>
</div>
</div>
{/* Site Info */}
<div className="text-center mt-6 text-sm text-gray-600 dark:text-gray-400">
{window.WNW_CONFIG.siteName}
</div>
</div>
</div>
);
}

84
admin/index.php Normal file
View File

@@ -0,0 +1,84 @@
<?php
/**
* WooNooW Standalone Admin Entry Point
*
* Minimal WordPress bootstrap - no theme, no plugins bloat.
* This file provides a clean, fast admin interface without wp_head/wp_footer.
*
* @package WooNooW
*/
// Load WordPress core only (no theme, no plugins)
define( 'WP_USE_THEMES', false );
define( 'WOONOOW_STANDALONE_ADMIN', true );
// Load WordPress
require_once( __DIR__ . '/../../../../wp-load.php' );
// Check if user is logged in and has permissions
$is_authenticated = is_user_logged_in() && current_user_can( 'manage_woocommerce' );
// Get nonce for REST API
$nonce = wp_create_nonce( 'wp_rest' );
$rest_url = rest_url( 'woonoow/v1' );
$wp_admin_url = admin_url( 'admin.php?page=woonoow' );
// Get current user data if authenticated
$current_user = null;
if ( $is_authenticated ) {
$user = wp_get_current_user();
$current_user = [
'id' => $user->ID,
'name' => $user->display_name,
'email' => $user->user_email,
'avatar' => get_avatar_url( $user->ID ),
];
}
// Get asset URLs
$plugin_url = plugins_url( '', dirname( __FILE__ ) );
$asset_url = $plugin_url . '/admin-spa/dist';
$css_url = $asset_url . '/app.css';
$js_url = $asset_url . '/app.js';
// Add cache busting
$version = defined( 'WP_DEBUG' ) && WP_DEBUG ? time() : '1.0.0';
$css_url .= '?ver=' . $version;
$js_url .= '?ver=' . $version;
?>
<!DOCTYPE html>
<html lang="<?php echo esc_attr( get_locale() ); ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, nofollow">
<title>WooNooW Admin</title>
<!-- WooNooW Assets Only - NO wp_head() -->
<link rel="stylesheet" href="<?php echo esc_url( $css_url ); ?>">
</head>
<body class="woonoow-standalone">
<div id="woonoow-admin-root"></div>
<script>
// Minimal config - no WordPress bloat
window.WNW_CONFIG = {
restUrl: <?php echo wp_json_encode( $rest_url ); ?>,
nonce: <?php echo wp_json_encode( $nonce ); ?>,
standaloneMode: true,
wpAdminUrl: <?php echo wp_json_encode( $wp_admin_url ); ?>,
isAuthenticated: <?php echo $is_authenticated ? 'true' : 'false'; ?>,
currentUser: <?php echo wp_json_encode( $current_user ); ?>,
locale: <?php echo wp_json_encode( get_locale() ); ?>,
siteUrl: <?php echo wp_json_encode( home_url() ); ?>,
siteName: <?php echo wp_json_encode( get_bloginfo( 'name' ) ); ?>
};
</script>
<script type="module" src="<?php echo esc_url( $js_url ); ?>"></script>
<?php
// NO wp_footer() - we don't want theme/plugin scripts
?>
</body>
</html>

View File

@@ -0,0 +1,114 @@
<?php
namespace WooNooW\Api;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;
/**
* Authentication Controller for Standalone Admin
*
* Handles login, logout, and auth status checks for the standalone admin interface.
*
* @package WooNooW\Api
*/
class AuthController {
/**
* Login endpoint for standalone admin
*
* @param WP_REST_Request $request Request object
* @return WP_REST_Response Response object
*/
public static function login( WP_REST_Request $request ): WP_REST_Response {
$username = sanitize_text_field( $request->get_param( 'username' ) );
$password = $request->get_param( 'password' );
if ( empty( $username ) || empty( $password ) ) {
return new WP_REST_Response( [
'success' => false,
'message' => __( 'Username and password are required', 'woonoow' ),
], 400 );
}
// Authenticate user
$user = wp_authenticate( $username, $password );
if ( is_wp_error( $user ) ) {
return new WP_REST_Response( [
'success' => false,
'message' => __( 'Invalid username or password', 'woonoow' ),
], 401 );
}
// Check if user has WooCommerce permissions
if ( ! user_can( $user, 'manage_woocommerce' ) ) {
return new WP_REST_Response( [
'success' => false,
'message' => __( 'You do not have permission to access this area', 'woonoow' ),
], 403 );
}
// Set auth cookie
wp_set_auth_cookie( $user->ID, true );
// Return user data and new nonce
return new WP_REST_Response( [
'success' => true,
'user' => [
'id' => $user->ID,
'name' => $user->display_name,
'email' => $user->user_email,
'avatar' => get_avatar_url( $user->ID ),
],
'nonce' => wp_create_nonce( 'wp_rest' ),
], 200 );
}
/**
* Logout endpoint
*
* @return WP_REST_Response Response object
*/
public static function logout(): WP_REST_Response {
wp_logout();
return new WP_REST_Response( [
'success' => true,
'message' => __( 'Logged out successfully', 'woonoow' ),
], 200 );
}
/**
* Check auth status
*
* @return WP_REST_Response Response object
*/
public static function check(): WP_REST_Response {
if ( ! is_user_logged_in() ) {
return new WP_REST_Response( [
'authenticated' => false,
], 200 );
}
$user = wp_get_current_user();
// Check WooCommerce permission
if ( ! current_user_can( 'manage_woocommerce' ) ) {
return new WP_REST_Response( [
'authenticated' => false,
'message' => __( 'Insufficient permissions', 'woonoow' ),
], 200 );
}
return new WP_REST_Response( [
'authenticated' => true,
'user' => [
'id' => $user->ID,
'name' => $user->display_name,
'email' => $user->user_email,
'avatar' => get_avatar_url( $user->ID ),
],
], 200 );
}
}

View File

@@ -6,6 +6,7 @@ use WP_REST_Response;
use WooNooW\Api\CheckoutController;
use WooNooW\Api\OrdersController;
use WooNooW\Api\AnalyticsController;
use WooNooW\Api\AuthController;
class Routes {
public static function init() {
@@ -14,6 +15,26 @@ class Routes {
add_action('rest_api_init', function () {
$namespace = 'woonoow/v1';
// Auth endpoints (public - no permission check)
register_rest_route( $namespace, '/auth/login', [
'methods' => 'POST',
'callback' => [ AuthController::class, 'login' ],
'permission_callback' => '__return_true',
] );
register_rest_route( $namespace, '/auth/logout', [
'methods' => 'POST',
'callback' => [ AuthController::class, 'logout' ],
'permission_callback' => '__return_true',
] );
register_rest_route( $namespace, '/auth/check', [
'methods' => 'GET',
'callback' => [ AuthController::class, 'check' ],
'permission_callback' => '__return_true',
] );
// Defer to controllers to register their endpoints
CheckoutController::register();
OrdersController::register();