feat: add admin auth middleware
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
import axios from 'axios';
|
||||
|
||||
// Create axios instance with default config
|
||||
@@ -12,11 +13,10 @@ const httpClient = axios.create({
|
||||
// Request interceptor
|
||||
httpClient.interceptors.request.use(
|
||||
config => {
|
||||
// You can add auth token here if needed
|
||||
// const token = localStorage.getItem('token');
|
||||
// if (token) {
|
||||
// config.headers.Authorization = `Bearer ${token}`;
|
||||
// }
|
||||
const authStore = useAuthStore();
|
||||
if (authStore.isAuthenticated && authStore.token) {
|
||||
config.headers.Authorization = `Bearer ${authStore.token}`;
|
||||
}
|
||||
return config;
|
||||
},
|
||||
error => {
|
||||
|
||||
@@ -25,6 +25,10 @@ const validateForm = () => {
|
||||
errorMessage.value = '请输入密码';
|
||||
return false;
|
||||
}
|
||||
if (password.value.length < 8) {
|
||||
errorMessage.value = '密码至少需要8个字符';
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -35,7 +39,8 @@ const handleLogin = async () => {
|
||||
errorMessage.value = '';
|
||||
|
||||
try {
|
||||
const token = await authService.login(username.value, password.value);
|
||||
const resp = await authService.login(username.value, password.value);
|
||||
const { token } = resp.data;
|
||||
authStore.setToken(token);
|
||||
router.push('/');
|
||||
} catch (error) {
|
||||
|
||||
@@ -2,21 +2,21 @@ import { defineStore } from 'pinia';
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
const token = ref(localStorage.getItem('token'));
|
||||
const token = ref(localStorage.getItem('__token'));
|
||||
const user = ref(null);
|
||||
|
||||
const isAuthenticated = computed(() => !!token.value);
|
||||
|
||||
function setToken(newToken) {
|
||||
token.value = newToken;
|
||||
localStorage.setItem('token', newToken);
|
||||
localStorage.setItem('__token', newToken);
|
||||
}
|
||||
|
||||
|
||||
function logout() {
|
||||
token.value = null;
|
||||
user.value = null;
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('__token');
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
Reference in New Issue
Block a user