feat: 前端认证
This commit is contained in:
17
web/src/api/auth.ts
Normal file
17
web/src/api/auth.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import apiClient from './index';
|
||||
|
||||
export interface LoginRequest {
|
||||
auth_key: string;
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
success: boolean;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export const login = async (authKey: string): Promise<LoginResponse> => {
|
||||
const response = await apiClient.post<LoginResponse>('/auth/login', {
|
||||
auth_key: authKey
|
||||
});
|
||||
return response.data;
|
||||
};
|
@@ -1,4 +1,6 @@
|
||||
import axios from "axios";
|
||||
import { useAuthStore } from "@/stores/authStore";
|
||||
import router from "@/router";
|
||||
|
||||
const apiClient = axios.create({
|
||||
baseURL: "/api",
|
||||
@@ -7,8 +9,42 @@ const apiClient = axios.create({
|
||||
},
|
||||
});
|
||||
|
||||
// 可以添加请求和响应拦截器
|
||||
// apiClient.interceptors.request.use(...)
|
||||
// apiClient.interceptors.response.use(...)
|
||||
// 请求拦截器:自动添加认证头
|
||||
apiClient.interceptors.request.use(
|
||||
(config) => {
|
||||
const authStore = useAuthStore();
|
||||
const authKey = authStore.getAuthKey();
|
||||
|
||||
if (authKey) {
|
||||
config.headers.Authorization = `Bearer ${authKey}`;
|
||||
}
|
||||
|
||||
return config;
|
||||
},
|
||||
(error) => {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
// 响应拦截器:处理401认证失败
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => {
|
||||
return response;
|
||||
},
|
||||
(error) => {
|
||||
if (error.response?.status === 401) {
|
||||
// 认证失败,清除登录状态并跳转到登录页
|
||||
const authStore = useAuthStore();
|
||||
authStore.logout();
|
||||
|
||||
// 跳转到登录页(如果不在登录页的话)
|
||||
if (router.currentRoute.value.path !== '/login') {
|
||||
router.push('/login');
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
export default apiClient;
|
||||
|
Reference in New Issue
Block a user