feat: 完善登录等接口鉴权

This commit is contained in:
R524809
2026-01-06 10:49:19 +08:00
parent 84ddca26b5
commit 76c22429ad
16 changed files with 572 additions and 93 deletions
+17 -8
View File
@@ -1,6 +1,10 @@
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { envConfig } from '../config/env';
// Token 存储键名(与 auth service 保持一致)
const TOKEN_KEY = 'access_token';
// 创建 axios 实例
const apiClient: AxiosInstance = axios.create({
baseURL: envConfig.apiBaseUrl,
@@ -13,11 +17,11 @@ const apiClient: AxiosInstance = axios.create({
// 请求拦截器
apiClient.interceptors.request.use(
(config) => {
// 可以在这里添加 token 等认证信息
// const token = localStorage.getItem('token')
// if (token) {
// config.headers.Authorization = `Bearer ${token}`
// }
// 自动添加 token 到请求头
const token = localStorage.getItem(TOKEN_KEY);
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
if (envConfig.debug) {
console.log('请求:', config.method?.toUpperCase(), config.url);
@@ -50,8 +54,13 @@ apiClient.interceptors.response.use(
if (error.response) {
switch (error.response.status) {
case 401:
// 未授权,可以跳转到登录页
// window.location.href = '/login'
// 未授权,清除 token 并跳转到登录页
localStorage.removeItem(TOKEN_KEY);
localStorage.removeItem('user_info');
// 避免在登录页重复跳转
if (window.location.pathname !== '/login') {
window.location.href = '/login';
}
break;
case 403:
console.error('没有权限访问该资源');
+104
View File
@@ -0,0 +1,104 @@
import { api } from './api';
import type { UserInfo, LoginRequest, LoginResponse } from '@/types/user';
import type { ApiResponse } from '@/types/common';
/**
* Token 存储键名
*/
const TOKEN_KEY = 'access_token';
const USER_KEY = 'user_info';
/**
* 认证服务
*/
class AuthService {
/**
* 登录
*/
async login(credentials: LoginRequest): Promise<LoginResponse> {
const response = await api.post<ApiResponse<LoginResponse>>('/auth/login', credentials);
if (response.code === 0 && response.data) {
this.setToken(response.data.accessToken);
this.setUser(response.data.user);
return response.data;
}
throw new Error(response.message || '登录失败');
}
/**
* 登出
*/
logout(): void {
this.removeToken();
this.removeUser();
}
/**
* 获取当前 token
*/
getToken(): string | null {
return localStorage.getItem(TOKEN_KEY);
}
/**
* 设置 token
*/
setToken(token: string): void {
localStorage.setItem(TOKEN_KEY, token);
}
/**
* 移除 token
*/
removeToken(): void {
localStorage.removeItem(TOKEN_KEY);
}
/**
* 获取当前用户信息
*/
getUser(): UserInfo | null {
const userStr = localStorage.getItem(USER_KEY);
if (!userStr) return null;
try {
return JSON.parse(userStr);
} catch {
return null;
}
}
/**
* 设置用户信息
*/
setUser(user: UserInfo): void {
localStorage.setItem(USER_KEY, JSON.stringify(user));
}
/**
* 移除用户信息
*/
removeUser(): void {
localStorage.removeItem(USER_KEY);
}
/**
* 检查是否已登录
*/
isAuthenticated(): boolean {
return !!this.getToken();
}
/**
* 检查是否为管理员
*/
isAdmin(): boolean {
const user = this.getUser();
return user?.role === 'admin' || user?.role === 'super_admin';
}
}
// 导出单例
export const authService = new AuthService();