超管后台 - 登录拦截
This commit is contained in:
@@ -1,19 +1,28 @@
|
||||
<?php
|
||||
use think\facade\Route;
|
||||
|
||||
// 超级管理员认证相关路由
|
||||
// 超级管理员认证相关路由(不需要鉴权)
|
||||
Route::post('auth/login', 'app\\superadmin\\controller\\Auth@login');
|
||||
|
||||
// 菜单管理相关路由
|
||||
Route::group('menu', function () {
|
||||
Route::get('tree', 'app\\superadmin\\controller\\Menu@getMenuTree');
|
||||
Route::get('list', 'app\\superadmin\\controller\\Menu@getMenuList');
|
||||
});
|
||||
|
||||
// 管理员相关路由
|
||||
Route::group('administrator', function () {
|
||||
// 获取管理员列表
|
||||
Route::get('list', 'app\\superadmin\\controller\\Administrator@getList');
|
||||
// 获取管理员详情
|
||||
Route::get('detail/:id', 'app\\superadmin\\controller\\Administrator@getDetail');
|
||||
});
|
||||
// 需要登录认证的路由组
|
||||
Route::group('', function () {
|
||||
// 菜单管理相关路由
|
||||
Route::group('menu', function () {
|
||||
Route::get('tree', 'app\\superadmin\\controller\\Menu@getMenuTree');
|
||||
Route::get('list', 'app\\superadmin\\controller\\Menu@getMenuList');
|
||||
Route::post('save', 'app\\superadmin\\controller\\Menu@saveMenu');
|
||||
Route::delete('delete/:id', 'app\\superadmin\\controller\\Menu@deleteMenu');
|
||||
Route::post('status', 'app\\superadmin\\controller\\Menu@updateStatus');
|
||||
});
|
||||
|
||||
// 管理员相关路由
|
||||
Route::group('administrator', function () {
|
||||
// 获取管理员列表
|
||||
Route::get('list', 'app\\superadmin\\controller\\Administrator@getList');
|
||||
// 获取管理员详情
|
||||
Route::get('detail/:id', 'app\\superadmin\\controller\\Administrator@getDetail');
|
||||
});
|
||||
|
||||
// 系统信息相关路由
|
||||
Route::get('system/info', 'app\\superadmin\\controller\\System@getInfo');
|
||||
})->middleware(['app\\superadmin\\middleware\\AdminAuth']);
|
||||
@@ -57,7 +57,7 @@ class Auth extends Controller
|
||||
*/
|
||||
private function createToken($admin)
|
||||
{
|
||||
$data = $admin->id . '|' . $admin->account . '|' . time();
|
||||
$data = $admin->id . '|' . $admin->account;
|
||||
return md5($data . 'cunkebao_admin_secret');
|
||||
}
|
||||
}
|
||||
74
Server/application/superadmin/middleware/AdminAuth.php
Normal file
74
Server/application/superadmin/middleware/AdminAuth.php
Normal file
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
namespace app\superadmin\middleware;
|
||||
|
||||
/**
|
||||
* 超级管理员后台登录认证中间件
|
||||
*/
|
||||
class AdminAuth
|
||||
{
|
||||
/**
|
||||
* 处理请求
|
||||
* @param \think\Request $request
|
||||
* @param \Closure $next
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle($request, \Closure $next)
|
||||
{
|
||||
// 获取Cookie中的管理员信息
|
||||
$adminId = cookie('admin_id');
|
||||
$adminToken = cookie('admin_token');
|
||||
|
||||
// 如果没有登录信息,返回401未授权
|
||||
if (empty($adminId) || empty($adminToken)) {
|
||||
return json([
|
||||
'code' => 401,
|
||||
'msg' => '请先登录',
|
||||
'data' => null
|
||||
]);
|
||||
}
|
||||
|
||||
// 获取管理员信息
|
||||
$admin = \app\superadmin\model\Administrator::where([
|
||||
['id', '=', $adminId],
|
||||
['status', '=', 1],
|
||||
['deleteTime', '=', 0]
|
||||
])->find();
|
||||
|
||||
// 如果管理员不存在,返回401未授权
|
||||
if (!$admin) {
|
||||
return json([
|
||||
'code' => 401,
|
||||
'msg' => '管理员账号不存在或已被禁用',
|
||||
'data' => null
|
||||
]);
|
||||
}
|
||||
|
||||
// 验证Token是否有效
|
||||
$expectedToken = $this->createToken($admin);
|
||||
|
||||
if ($adminToken !== $expectedToken) {
|
||||
return json([
|
||||
'code' => 401,
|
||||
'msg' => '登录已过期,请重新登录',
|
||||
'data' => null
|
||||
]);
|
||||
}
|
||||
|
||||
// 将管理员信息绑定到请求对象,方便后续控制器使用
|
||||
$request->adminInfo = $admin;
|
||||
|
||||
// 继续执行后续操作
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建登录令牌
|
||||
* @param \app\superadmin\model\Administrator $admin
|
||||
* @return string
|
||||
*/
|
||||
private function createToken($admin)
|
||||
{
|
||||
$data = $admin->id . '|' . $admin->account;
|
||||
return md5($data . 'cunkebao_admin_secret');
|
||||
}
|
||||
}
|
||||
@@ -12,16 +12,16 @@
|
||||
// [ 应用入口文件 ]
|
||||
namespace think;
|
||||
|
||||
//处理跨域预检请求
|
||||
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
|
||||
//允许的源域名
|
||||
header("Access-Control-Allow-Origin: *");
|
||||
//允许的请求头信息
|
||||
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
|
||||
//允许的请求类型
|
||||
header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
|
||||
exit;
|
||||
}
|
||||
////处理跨域预检请求
|
||||
//if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
|
||||
// //允许的源域名
|
||||
// header("Access-Control-Allow-Origin: *");
|
||||
// //允许的请求头信息
|
||||
// header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
|
||||
// //允许的请求类型
|
||||
// header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
|
||||
// exit;
|
||||
//}
|
||||
|
||||
define('ROOT_PATH', dirname(__DIR__));
|
||||
define('DS', DIRECTORY_SEPARATOR);
|
||||
|
||||
@@ -12,11 +12,11 @@
|
||||
use think\facade\Route;
|
||||
|
||||
// 允许跨域
|
||||
header('Access-Control-Allow-Origin: *');
|
||||
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, PATCH');
|
||||
header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With, X-Token, X-Api-Token');
|
||||
header('Access-Control-Max-Age: 1728000');
|
||||
header('Access-Control-Allow-Credentials: true');
|
||||
// header('Access-Control-Allow-Origin: *');
|
||||
// header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, PATCH');
|
||||
// header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With, X-Token, X-Api-Token');
|
||||
// header('Access-Control-Max-Age: 1728000');
|
||||
// header('Access-Control-Allow-Credentials: true');
|
||||
|
||||
// 加载Store模块路由配置
|
||||
include __DIR__ . '/../application/api/config/route.php';
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
"use client"
|
||||
|
||||
import type React from "react"
|
||||
import { useState } from "react"
|
||||
import { useState, useEffect } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Menu, X, LogOut } from "lucide-react"
|
||||
import { Menu, X } from "lucide-react"
|
||||
import { Sidebar } from "@/components/layout/sidebar"
|
||||
import { Header } from "@/components/layout/header"
|
||||
import { getAdminInfo } from "@/lib/utils"
|
||||
|
||||
export default function DashboardLayout({
|
||||
children,
|
||||
@@ -13,6 +15,20 @@ export default function DashboardLayout({
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const [sidebarOpen, setSidebarOpen] = useState(true)
|
||||
const router = useRouter()
|
||||
|
||||
// 认证检查
|
||||
useEffect(() => {
|
||||
const checkAuth = () => {
|
||||
const adminInfo = getAdminInfo()
|
||||
if (!adminInfo) {
|
||||
// 未登录时跳转到登录页
|
||||
router.push('/login')
|
||||
}
|
||||
}
|
||||
|
||||
checkAuth()
|
||||
}, [router])
|
||||
|
||||
return (
|
||||
<div className="flex h-screen overflow-hidden">
|
||||
|
||||
@@ -8,52 +8,58 @@ import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { md5 } from "@/lib/utils"
|
||||
import { md5, saveAdminInfo } from "@/lib/utils"
|
||||
import { login } from "@/lib/admin-api"
|
||||
import { useToast } from "@/components/ui/use-toast"
|
||||
|
||||
export default function LoginPage() {
|
||||
const [account, setAccount] = useState("")
|
||||
const [password, setPassword] = useState("")
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [error, setError] = useState("")
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
|
||||
const handleLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setIsLoading(true)
|
||||
setError("")
|
||||
|
||||
try {
|
||||
// 对密码进行MD5加密
|
||||
const encryptedPassword = md5(password)
|
||||
|
||||
// 调用登录接口
|
||||
const response = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/auth/login`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
account,
|
||||
password: encryptedPassword
|
||||
}),
|
||||
credentials: "include"
|
||||
})
|
||||
const result = await login(account, encryptedPassword)
|
||||
|
||||
const result = await response.json()
|
||||
|
||||
if (result.code === 200) {
|
||||
// 保存用户信息到本地存储
|
||||
localStorage.setItem("admin_info", JSON.stringify(result.data))
|
||||
localStorage.setItem("admin_token", result.data.token)
|
||||
if (result.code === 200 && result.data) {
|
||||
// 保存管理员信息
|
||||
saveAdminInfo(result.data)
|
||||
|
||||
// 显示成功提示
|
||||
toast({
|
||||
title: "登录成功",
|
||||
description: `欢迎回来,${result.data.name}`,
|
||||
variant: "success",
|
||||
})
|
||||
|
||||
// 跳转到仪表盘
|
||||
router.push("/dashboard")
|
||||
} else {
|
||||
setError(result.msg || "登录失败")
|
||||
// 显示错误提示
|
||||
toast({
|
||||
title: "登录失败",
|
||||
description: result.msg || "账号或密码错误",
|
||||
variant: "destructive",
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("登录失败:", err)
|
||||
setError("网络错误,请稍后再试")
|
||||
|
||||
// 显示错误提示
|
||||
toast({
|
||||
title: "登录失败",
|
||||
description: "网络错误,请稍后再试",
|
||||
variant: "destructive",
|
||||
})
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
@@ -65,7 +71,6 @@ export default function LoginPage() {
|
||||
<CardHeader className="space-y-1">
|
||||
<CardTitle className="text-2xl text-center">超级管理员后台</CardTitle>
|
||||
<CardDescription className="text-center">请输入您的账号和密码登录系统</CardDescription>
|
||||
{error && <p className="text-sm text-red-500 text-center">{error}</p>}
|
||||
</CardHeader>
|
||||
<form onSubmit={handleLogin}>
|
||||
<CardContent className="space-y-4">
|
||||
|
||||
@@ -35,7 +35,7 @@ const ScrollBar = React.forwardRef<
|
||||
orientation === "vertical" &&
|
||||
"h-full w-2.5 border-l border-l-transparent p-[1px]",
|
||||
orientation === "horizontal" &&
|
||||
"h-2.5 flex-col border-t border-t-transparent p-[1px]",
|
||||
"h-2.5 border-t border-t-transparent p-[1px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getConfig } from './config';
|
||||
import { apiRequest, ApiResponse } from './api-utils';
|
||||
|
||||
// 管理员接口数据类型定义
|
||||
export interface Administrator {
|
||||
@@ -33,11 +33,25 @@ export interface PaginatedResponse<T> {
|
||||
limit: number;
|
||||
}
|
||||
|
||||
// API响应数据结构
|
||||
export interface ApiResponse<T> {
|
||||
code: number;
|
||||
msg: string;
|
||||
data: T | null;
|
||||
/**
|
||||
* 管理员登录
|
||||
* @param account 账号
|
||||
* @param password 密码
|
||||
* @returns 登录结果
|
||||
*/
|
||||
export async function login(
|
||||
account: string,
|
||||
password: string
|
||||
): Promise<ApiResponse<{
|
||||
id: number;
|
||||
name: string;
|
||||
account: string;
|
||||
token: string;
|
||||
}>> {
|
||||
return apiRequest('/auth/login', 'POST', {
|
||||
account,
|
||||
password
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -52,8 +66,6 @@ export async function getAdministrators(
|
||||
limit: number = 10,
|
||||
keyword: string = ''
|
||||
): Promise<ApiResponse<PaginatedResponse<Administrator>>> {
|
||||
const { apiBaseUrl } = getConfig();
|
||||
|
||||
// 构建查询参数
|
||||
const params = new URLSearchParams();
|
||||
params.append('page', page.toString());
|
||||
@@ -62,28 +74,7 @@ export async function getAdministrators(
|
||||
params.append('keyword', keyword);
|
||||
}
|
||||
|
||||
try {
|
||||
// 发送请求
|
||||
const response = await fetch(`${apiBaseUrl}/administrator/list?${params.toString()}`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`请求失败,状态码: ${response.status}`);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error('获取管理员列表失败:', error);
|
||||
return {
|
||||
code: 500,
|
||||
msg: '获取管理员列表失败',
|
||||
data: null
|
||||
};
|
||||
}
|
||||
return apiRequest(`/administrator/list?${params.toString()}`);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -92,28 +83,5 @@ export async function getAdministrators(
|
||||
* @returns 管理员详情
|
||||
*/
|
||||
export async function getAdministratorDetail(id: number | string): Promise<ApiResponse<AdministratorDetail>> {
|
||||
const { apiBaseUrl } = getConfig();
|
||||
|
||||
try {
|
||||
// 发送请求
|
||||
const response = await fetch(`${apiBaseUrl}/administrator/detail/${id}`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`请求失败,状态码: ${response.status}`);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error('获取管理员详情失败:', error);
|
||||
return {
|
||||
code: 500,
|
||||
msg: '获取管理员详情失败',
|
||||
data: null
|
||||
};
|
||||
}
|
||||
return apiRequest(`/administrator/detail/${id}`);
|
||||
}
|
||||
83
SuperAdmin/lib/api-utils.ts
Normal file
83
SuperAdmin/lib/api-utils.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import { getConfig } from './config';
|
||||
import { getAdminInfo, clearAdminInfo } from './utils';
|
||||
|
||||
/**
|
||||
* API响应数据结构
|
||||
*/
|
||||
export interface ApiResponse<T = any> {
|
||||
code: number;
|
||||
msg: string;
|
||||
data: T | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通用API请求函数
|
||||
* @param endpoint API端点
|
||||
* @param method HTTP方法
|
||||
* @param data 请求数据
|
||||
* @returns API响应
|
||||
*/
|
||||
export async function apiRequest<T = any>(
|
||||
endpoint: string,
|
||||
method: 'GET' | 'POST' | 'PUT' | 'DELETE' = 'GET',
|
||||
data?: any
|
||||
): Promise<ApiResponse<T>> {
|
||||
const { apiBaseUrl } = getConfig();
|
||||
const url = `${apiBaseUrl}${endpoint}`;
|
||||
|
||||
// 获取认证信息
|
||||
const adminInfo = getAdminInfo();
|
||||
|
||||
// 请求头
|
||||
const headers: HeadersInit = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
|
||||
// 如果有认证信息,添加Cookie头
|
||||
if (adminInfo?.token) {
|
||||
// 添加认证令牌,作为Cookie发送
|
||||
document.cookie = `admin_id=${adminInfo.id}; path=/`;
|
||||
document.cookie = `admin_token=${adminInfo.token}; path=/`;
|
||||
}
|
||||
|
||||
// 请求配置
|
||||
const config: RequestInit = {
|
||||
method,
|
||||
headers,
|
||||
credentials: 'include', // 包含跨域请求的Cookie
|
||||
};
|
||||
|
||||
// 如果有请求数据,转换为JSON
|
||||
if (data && method !== 'GET') {
|
||||
config.body = JSON.stringify(data);
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(url, config);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`请求失败: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const result = await response.json() as ApiResponse<T>;
|
||||
|
||||
// 如果返回未授权错误,清除登录信息
|
||||
if (result.code === 401) {
|
||||
clearAdminInfo();
|
||||
// 如果在浏览器环境,跳转到登录页
|
||||
if (typeof window !== 'undefined') {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error('API请求错误:', error);
|
||||
|
||||
return {
|
||||
code: 500,
|
||||
msg: error instanceof Error ? error.message : '未知错误',
|
||||
data: null
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { apiRequest, ApiResponse } from './api-utils';
|
||||
|
||||
/**
|
||||
* 菜单项接口
|
||||
*/
|
||||
@@ -13,78 +15,60 @@ export interface MenuItem {
|
||||
}
|
||||
|
||||
/**
|
||||
* 从服务器获取菜单数据
|
||||
* 获取菜单树
|
||||
* @param onlyEnabled 是否只获取启用的菜单
|
||||
* @returns Promise<MenuItem[]>
|
||||
* @returns 菜单树
|
||||
*/
|
||||
export async function getMenus(onlyEnabled: boolean = true): Promise<MenuItem[]> {
|
||||
try {
|
||||
// API基础路径从环境变量获取
|
||||
const apiBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8000';
|
||||
// 构建查询参数
|
||||
const params = new URLSearchParams();
|
||||
params.append('only_enabled', onlyEnabled ? '1' : '0');
|
||||
|
||||
// 构建API URL
|
||||
const url = `${apiBaseUrl}/menu/tree?only_enabled=${onlyEnabled ? 1 : 0}`;
|
||||
const response = await apiRequest<MenuItem[]>(`/menu/tree?${params.toString()}`);
|
||||
|
||||
// 获取存储的token
|
||||
const token = typeof window !== 'undefined' ? localStorage.getItem('admin_token') : null;
|
||||
|
||||
// 发起请求
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': token ? `Bearer ${token}` : ''
|
||||
},
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
// 处理响应
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.code === 200) {
|
||||
return result.data;
|
||||
} else {
|
||||
console.error('获取菜单失败:', result.msg);
|
||||
return [];
|
||||
}
|
||||
return response.data || [];
|
||||
} catch (error) {
|
||||
console.error('获取菜单出错:', error);
|
||||
console.error('获取菜单树失败:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存菜单
|
||||
* 获取菜单列表
|
||||
* @param page 页码
|
||||
* @param limit 每页数量
|
||||
* @returns 菜单列表
|
||||
*/
|
||||
export async function getMenuList(
|
||||
page: number = 1,
|
||||
limit: number = 20
|
||||
): Promise<ApiResponse<{
|
||||
list: MenuItem[];
|
||||
total: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
}>> {
|
||||
// 构建查询参数
|
||||
const params = new URLSearchParams();
|
||||
params.append('page', page.toString());
|
||||
params.append('limit', limit.toString());
|
||||
|
||||
return apiRequest(`/menu/list?${params.toString()}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存菜单(新增或更新)
|
||||
* @param menuData 菜单数据
|
||||
* @returns Promise<boolean>
|
||||
* @returns 保存结果
|
||||
*/
|
||||
export async function saveMenu(menuData: Partial<MenuItem>): Promise<boolean> {
|
||||
try {
|
||||
const apiBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8000';
|
||||
const url = `${apiBaseUrl}/menu/save`;
|
||||
const token = typeof window !== 'undefined' ? localStorage.getItem('admin_token') : null;
|
||||
const response = await apiRequest('/menu/save', 'POST', menuData);
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': token ? `Bearer ${token}` : ''
|
||||
},
|
||||
body: JSON.stringify(menuData)
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
return result.code === 200;
|
||||
return response.code === 200;
|
||||
} catch (error) {
|
||||
console.error('保存菜单出错:', error);
|
||||
console.error('保存菜单失败:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -92,30 +76,15 @@ export async function saveMenu(menuData: Partial<MenuItem>): Promise<boolean> {
|
||||
/**
|
||||
* 删除菜单
|
||||
* @param id 菜单ID
|
||||
* @returns Promise<boolean>
|
||||
* @returns 删除结果
|
||||
*/
|
||||
export async function deleteMenu(id: number): Promise<boolean> {
|
||||
try {
|
||||
const apiBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8000';
|
||||
const url = `${apiBaseUrl}/menu/delete/${id}`;
|
||||
const token = typeof window !== 'undefined' ? localStorage.getItem('admin_token') : null;
|
||||
const response = await apiRequest(`/menu/delete/${id}`, 'DELETE');
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': token ? `Bearer ${token}` : ''
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
return result.code === 200;
|
||||
return response.code === 200;
|
||||
} catch (error) {
|
||||
console.error('删除菜单出错:', error);
|
||||
console.error('删除菜单失败:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -123,32 +92,19 @@ export async function deleteMenu(id: number): Promise<boolean> {
|
||||
/**
|
||||
* 更新菜单状态
|
||||
* @param id 菜单ID
|
||||
* @param status 状态 (0-禁用, 1-启用)
|
||||
* @returns Promise<boolean>
|
||||
* @param status 状态:1启用,0禁用
|
||||
* @returns 更新结果
|
||||
*/
|
||||
export async function updateMenuStatus(id: number, status: 0 | 1): Promise<boolean> {
|
||||
try {
|
||||
const apiBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8000';
|
||||
const url = `${apiBaseUrl}/menu/status`;
|
||||
const token = typeof window !== 'undefined' ? localStorage.getItem('admin_token') : null;
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': token ? `Bearer ${token}` : ''
|
||||
},
|
||||
body: JSON.stringify({ id, status })
|
||||
const response = await apiRequest('/menu/status', 'POST', {
|
||||
id,
|
||||
status
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
return result.code === 200;
|
||||
return response.code === 200;
|
||||
} catch (error) {
|
||||
console.error('更新菜单状态出错:', error);
|
||||
console.error('更新菜单状态失败:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -12,3 +12,64 @@ export function cn(...inputs: ClassValue[]) {
|
||||
export function md5(text: string): string {
|
||||
return crypto.createHash("md5").update(text).digest("hex")
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员信息
|
||||
*/
|
||||
export interface AdminInfo {
|
||||
id: number;
|
||||
name: string;
|
||||
account: string;
|
||||
token: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存管理员信息到本地存储
|
||||
* @param adminInfo 管理员信息
|
||||
*/
|
||||
export function saveAdminInfo(adminInfo: AdminInfo): void {
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.setItem('admin_id', adminInfo.id.toString());
|
||||
localStorage.setItem('admin_name', adminInfo.name);
|
||||
localStorage.setItem('admin_account', adminInfo.account);
|
||||
localStorage.setItem('admin_token', adminInfo.token);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取管理员信息
|
||||
* @returns 管理员信息
|
||||
*/
|
||||
export function getAdminInfo(): AdminInfo | null {
|
||||
if (typeof window === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const id = localStorage.getItem('admin_id');
|
||||
const name = localStorage.getItem('admin_name');
|
||||
const account = localStorage.getItem('admin_account');
|
||||
const token = localStorage.getItem('admin_token');
|
||||
|
||||
if (!id || !name || !account || !token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id: parseInt(id, 10),
|
||||
name,
|
||||
account,
|
||||
token
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除管理员信息
|
||||
*/
|
||||
export function clearAdminInfo(): void {
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.removeItem('admin_id');
|
||||
localStorage.removeItem('admin_name');
|
||||
localStorage.removeItem('admin_account');
|
||||
localStorage.removeItem('admin_token');
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user