Добавлен компонент AuthGuard для защиты страниц от неавторизованных пользователей. Обновлен middleware для редиректа на страницу авторизации при отсутствии токена. Обернуты страницы дашборда, аккаунта, статистики и финансов в AuthGuard для проверки авторизации.
This commit is contained in:
parent
6ab1a42be7
commit
af0c52dbb6
@ -5,6 +5,11 @@ export function middleware(request: NextRequest) {
|
||||
// Получаем access_token из куков (SSR)
|
||||
const token = request.cookies.get('access_token');
|
||||
|
||||
// Если не на /auth и нет токена, редиректим на /auth
|
||||
if (pathname !== '/auth' && !token) {
|
||||
return NextResponse.redirect(new URL('/auth', request.url));
|
||||
}
|
||||
// Если на /auth и токен есть, редиректим на главную
|
||||
if (pathname === '/auth' && token) {
|
||||
return NextResponse.redirect(new URL('/', request.url));
|
||||
}
|
||||
@ -12,5 +17,5 @@ export function middleware(request: NextRequest) {
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: ['/auth'],
|
||||
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
|
||||
};
|
||||
@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
import { useEffect, useState } from "react";
|
||||
import styles from "../../styles/dashboard.module.css";
|
||||
import AuthGuard from "../../components/AuthGuard";
|
||||
|
||||
interface AccountData {
|
||||
id: number;
|
||||
@ -11,40 +12,42 @@ interface AccountData {
|
||||
}
|
||||
|
||||
export default function AccountPage() {
|
||||
const [account, setAccount] = useState<AccountData | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
// const [account, setAccount] = useState<AccountData | null>(null);
|
||||
// const [loading, setLoading] = useState(true);
|
||||
// const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetch("/api/account")
|
||||
.then((res) => {
|
||||
if (!res.ok) throw new Error("Ошибка загрузки данных аккаунта");
|
||||
return res.json();
|
||||
})
|
||||
.then((data) => {
|
||||
setAccount(data);
|
||||
setLoading(false);
|
||||
})
|
||||
.catch((err) => {
|
||||
setError(err.message);
|
||||
setLoading(false);
|
||||
});
|
||||
}, []);
|
||||
// useEffect(() => {
|
||||
// fetch("/api/account")
|
||||
// .then((res) => {
|
||||
// if (!res.ok) throw new Error("Ошибка загрузки данных аккаунта");
|
||||
// return res.json();
|
||||
// })
|
||||
// .then((data) => {
|
||||
// setAccount(data);
|
||||
// setLoading(false);
|
||||
// })
|
||||
// .catch((err) => {
|
||||
// setError(err.message);
|
||||
// setLoading(false);
|
||||
// });
|
||||
// }, []);
|
||||
|
||||
if (loading) return <div className={styles.dashboard}>Загрузка...</div>;
|
||||
if (error) return <div className={styles.dashboard}>Ошибка: {error}</div>;
|
||||
if (!account) return <div className={styles.dashboard}>Нет данных</div>;
|
||||
// if (loading) return <div className={styles.dashboard}>Загрузка...</div>;
|
||||
// if (error) return <div className={styles.dashboard}>Ошибка: {error}</div>;
|
||||
// if (!account) return <div className={styles.dashboard}>Нет данных</div>;
|
||||
|
||||
return (
|
||||
<div className={styles.dashboard}>
|
||||
<h1 className={styles.title}>Аккаунт</h1>
|
||||
<div className={styles.card} style={{ maxWidth: 400, margin: "0 auto" }}>
|
||||
<div><b>ID:</b> {account.id}</div>
|
||||
<div><b>Логин:</b> {account.login}</div>
|
||||
<div><b>Имя:</b> {account.name || "-"}</div>
|
||||
<div><b>Email:</b> {account.email || "-"}</div>
|
||||
<div><b>Баланс:</b> {account.balance.toLocaleString("ru-RU", { style: "currency", currency: "RUB" })}</div>
|
||||
<AuthGuard>
|
||||
<div className={styles.dashboard}>
|
||||
<h1 className={styles.title}>Аккаунт</h1>
|
||||
<div className={styles.card} style={{ maxWidth: 400, margin: "0 auto" }}>
|
||||
{/* <div><b>ID:</b> {account.id}</div>
|
||||
<div><b>Логин:</b> {account.login}</div>
|
||||
<div><b>Имя:</b> {account.name || "-"}</div>
|
||||
<div><b>Email:</b> {account.email || "-"}</div>
|
||||
<div><b>Баланс:</b> {account.balance.toLocaleString("ru-RU", { style: "currency", currency: "RUB" })}</div> */}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</AuthGuard>
|
||||
);
|
||||
}
|
||||
@ -14,6 +14,11 @@ export default function AuthPage() {
|
||||
const [error, setError] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
// Удаляем токен при заходе на страницу авторизации
|
||||
Cookies.remove('access_token', { path: '/' });
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (hasToken()) {
|
||||
window.location.href = "/";
|
||||
|
||||
@ -7,6 +7,7 @@ import BillingMetricCards from "../../components/BillingMetricCards";
|
||||
import PayoutsTransactionsTable from "../../components/PayoutsTransactionsTable";
|
||||
import BillingStatChart from "../../components/BillingStatChart";
|
||||
import DateFilters from "../../components/DateFilters";
|
||||
import AuthGuard from "../../components/AuthGuard";
|
||||
|
||||
export default function BillingPage() {
|
||||
const [payoutForm, setPayoutForm] = useState({
|
||||
@ -36,29 +37,31 @@ export default function BillingPage() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.billingPage}>
|
||||
<h1 className={styles.title}>Финансы</h1>
|
||||
<BillingMetricCards />
|
||||
<div className={styles.grid2}>
|
||||
<BillingStatChart />
|
||||
<BillingPieChart />
|
||||
<AuthGuard>
|
||||
<div className={styles.billingPage}>
|
||||
<h1 className={styles.title}>Финансы</h1>
|
||||
<BillingMetricCards />
|
||||
<div className={styles.grid2}>
|
||||
<BillingStatChart />
|
||||
<BillingPieChart />
|
||||
</div>
|
||||
<DateFilters
|
||||
dateStart={filters.dateStart}
|
||||
dateEnd={filters.dateEnd}
|
||||
onChange={(field, value) => {
|
||||
if (field === "dateStart") {
|
||||
if (filters.dateEnd && value > filters.dateEnd) return;
|
||||
}
|
||||
if (field === "dateEnd") {
|
||||
if (filters.dateStart && value < filters.dateStart) return;
|
||||
}
|
||||
setFilters(f => ({ ...f, [field]: value }));
|
||||
}}
|
||||
onApply={handleApply}
|
||||
onClear={handleClear}
|
||||
/>
|
||||
<PayoutsTransactionsTable filters={filters} reloadKey={reloadKey} />
|
||||
</div>
|
||||
<DateFilters
|
||||
dateStart={filters.dateStart}
|
||||
dateEnd={filters.dateEnd}
|
||||
onChange={(field, value) => {
|
||||
if (field === "dateStart") {
|
||||
if (filters.dateEnd && value > filters.dateEnd) return;
|
||||
}
|
||||
if (field === "dateEnd") {
|
||||
if (filters.dateStart && value < filters.dateStart) return;
|
||||
}
|
||||
setFilters(f => ({ ...f, [field]: value }));
|
||||
}}
|
||||
onApply={handleApply}
|
||||
onClear={handleClear}
|
||||
/>
|
||||
<PayoutsTransactionsTable filters={filters} reloadKey={reloadKey} />
|
||||
</div>
|
||||
</AuthGuard>
|
||||
);
|
||||
}
|
||||
@ -1,8 +1,8 @@
|
||||
import mockData from "../data/mockData";
|
||||
'use client'
|
||||
import MetricCards from "../components/MetricCards";
|
||||
import Table from "../components/Table";
|
||||
import StatCharts from "../components/StatCharts";
|
||||
import styles from "../styles/dashboard.module.css";
|
||||
import AuthGuard from "../components/AuthGuard";
|
||||
|
||||
function formatCurrency(amount: number) {
|
||||
return amount.toLocaleString("ru-RU", {
|
||||
@ -14,31 +14,33 @@ function formatCurrency(amount: number) {
|
||||
|
||||
export default function DashboardPage() {
|
||||
return (
|
||||
<div className={styles.dashboard}>
|
||||
<h1 className={styles.title}>Дашборд</h1>
|
||||
<MetricCards />
|
||||
<StatCharts />
|
||||
{/* <div className={styles.tableBlock}>
|
||||
<h3 className={styles.tableTitle}>Последние продажи</h3>
|
||||
<Table
|
||||
headers={["ID реферала", "Агент", "Сумма продажи", "Комиссия", "Дата", "Статус"]}
|
||||
data={mockData.dashboard.recentSales}
|
||||
renderRow={(sale: any, index: number) => (
|
||||
<tr key={index}>
|
||||
<td>{sale.id}</td>
|
||||
<td>{sale.agent}</td>
|
||||
<td>{formatCurrency(sale.amount)}</td>
|
||||
<td>{formatCurrency(sale.commission)}</td>
|
||||
<td>{sale.date}</td>
|
||||
<td>
|
||||
<span className={sale.status === "Выплачено" ? styles.statusPaid : styles.statusPending}>
|
||||
{sale.status}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
/>
|
||||
</div> */}
|
||||
</div>
|
||||
<AuthGuard>
|
||||
<div className={styles.dashboard}>
|
||||
<h1 className={styles.title}>Дашборд</h1>
|
||||
<MetricCards />
|
||||
<StatCharts />
|
||||
{/* <div className={styles.tableBlock}>
|
||||
<h3 className={styles.tableTitle}>Последние продажи</h3>
|
||||
<Table
|
||||
headers={["ID реферала", "Агент", "Сумма продажи", "Комиссия", "Дата", "Статус"]}
|
||||
data={mockData.dashboard.recentSales}
|
||||
renderRow={(sale: any, index: number) => (
|
||||
<tr key={index}>
|
||||
<td>{sale.id}</td>
|
||||
<td>{sale.agent}</td>
|
||||
<td>{formatCurrency(sale.amount)}</td>
|
||||
<td>{formatCurrency(sale.commission)}</td>
|
||||
<td>{sale.date}</td>
|
||||
<td>
|
||||
<span className={sale.status === "Выплачено" ? styles.statusPaid : styles.statusPending}>
|
||||
{sale.status}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
/>
|
||||
</div> */}
|
||||
</div>
|
||||
</AuthGuard>
|
||||
);
|
||||
}
|
||||
|
||||
@ -7,6 +7,7 @@ import SalesTable from "../../components/SalesTable";
|
||||
import styles from "../../styles/stat.module.css";
|
||||
import DateInput from "../../components/DateInput";
|
||||
import DateFilters from "../../components/DateFilters";
|
||||
import AuthGuard from "../../components/AuthGuard";
|
||||
|
||||
const tabs = [
|
||||
{ id: "agents", label: "Агенты" },
|
||||
@ -32,53 +33,53 @@ export default function StatPage() {
|
||||
setReloadKey(k => k + 1);
|
||||
}
|
||||
|
||||
|
||||
|
||||
return (
|
||||
<div className={styles.statPage}>
|
||||
<div className={styles.headerRow}>
|
||||
<h1 className={styles.title}>Статистика и аналитика</h1>
|
||||
{/* <button className={styles.exportBtn}>Экспорт</button> */}
|
||||
</div>
|
||||
<div className={styles.tabs}>
|
||||
{tabs.map((tab) => (
|
||||
<button
|
||||
key={tab.id}
|
||||
className={activeTab === tab.id ? styles.activeTab : styles.tab}
|
||||
onClick={() => setActiveTab(tab.id)}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<DateFilters
|
||||
dateStart={filters.dateStart}
|
||||
dateEnd={filters.dateEnd}
|
||||
onChange={(field, value) => {
|
||||
if (field === "dateStart") {
|
||||
if (filters.dateEnd && value > filters.dateEnd) return;
|
||||
}
|
||||
if (field === "dateEnd") {
|
||||
if (filters.dateStart && value < filters.dateStart) return;
|
||||
}
|
||||
setFilters(f => ({ ...f, [field]: value }));
|
||||
}}
|
||||
onApply={handleApply}
|
||||
onClear={handleClear}
|
||||
/>
|
||||
<AuthGuard>
|
||||
<div className={styles.statPage}>
|
||||
<div className={styles.headerRow}>
|
||||
<h1 className={styles.title}>Статистика и аналитика</h1>
|
||||
{/* <button className={styles.exportBtn}>Экспорт</button> */}
|
||||
</div>
|
||||
<div className={styles.tabs}>
|
||||
{tabs.map((tab) => (
|
||||
<button
|
||||
key={tab.id}
|
||||
className={activeTab === tab.id ? styles.activeTab : styles.tab}
|
||||
onClick={() => setActiveTab(tab.id)}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<DateFilters
|
||||
dateStart={filters.dateStart}
|
||||
dateEnd={filters.dateEnd}
|
||||
onChange={(field, value) => {
|
||||
if (field === "dateStart") {
|
||||
if (filters.dateEnd && value > filters.dateEnd) return;
|
||||
}
|
||||
if (field === "dateEnd") {
|
||||
if (filters.dateStart && value < filters.dateStart) return;
|
||||
}
|
||||
setFilters(f => ({ ...f, [field]: value }));
|
||||
}}
|
||||
onApply={handleApply}
|
||||
onClear={handleClear}
|
||||
/>
|
||||
|
||||
<div className={styles.tabContent}>
|
||||
{activeTab === "agents" && (
|
||||
<AgentsTable filters={filters} reloadKey={reloadKey} />
|
||||
)}
|
||||
{activeTab === "referrals" && (
|
||||
<ReferralsTable filters={filters} reloadKey={reloadKey} />
|
||||
)}
|
||||
{activeTab === "sales" && (
|
||||
<SalesTable filters={filters} reloadKey={reloadKey} />
|
||||
)}
|
||||
<div className={styles.tabContent}>
|
||||
{activeTab === "agents" && (
|
||||
<AgentsTable filters={filters} reloadKey={reloadKey} />
|
||||
)}
|
||||
{activeTab === "referrals" && (
|
||||
<ReferralsTable filters={filters} reloadKey={reloadKey} />
|
||||
)}
|
||||
{activeTab === "sales" && (
|
||||
<SalesTable filters={filters} reloadKey={reloadKey} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</AuthGuard>
|
||||
);
|
||||
}
|
||||
23
src/components/AuthGuard.tsx
Normal file
23
src/components/AuthGuard.tsx
Normal file
@ -0,0 +1,23 @@
|
||||
"use client";
|
||||
import { useEffect, useState, ReactNode } from "react";
|
||||
import Cookies from "js-cookie";
|
||||
|
||||
interface AuthGuardProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export default function AuthGuard({ children }: AuthGuardProps) {
|
||||
const [checked, setChecked] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const token = Cookies.get('access_token');
|
||||
if (!token) {
|
||||
window.location.href = "/auth";
|
||||
} else {
|
||||
setChecked(true);
|
||||
}
|
||||
}, []);
|
||||
|
||||
if (!checked) return null;
|
||||
return <>{children}</>;
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user