feat: add admin login
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import { http } from '@/utils/http';
|
||||
import httpClient from './httpClient';
|
||||
|
||||
export const authService = {
|
||||
login(username, password) {
|
||||
return http.post('/admin/auth/login', { username, password });
|
||||
return httpClient.post('/admin/auth', { username, password });
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script setup>
|
||||
import { authService } from '@/api/authService';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
import Button from 'primevue/button';
|
||||
import Card from 'primevue/card';
|
||||
@@ -10,17 +11,32 @@ import { useRouter } from 'vue-router';
|
||||
const router = useRouter();
|
||||
const authStore = useAuthStore();
|
||||
|
||||
const username = ref('');
|
||||
const password = ref('');
|
||||
const username = ref('admin');
|
||||
const password = ref('xixi@0202');
|
||||
const loading = ref(false);
|
||||
const errorMessage = ref('');
|
||||
|
||||
const validateForm = () => {
|
||||
if (!username.value.trim()) {
|
||||
errorMessage.value = '请输入用户名';
|
||||
return false;
|
||||
}
|
||||
if (!password.value) {
|
||||
errorMessage.value = '请输入密码';
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const handleLogin = async () => {
|
||||
if (!validateForm()) return;
|
||||
|
||||
loading.value = true;
|
||||
errorMessage.value = '';
|
||||
|
||||
try {
|
||||
await authStore.login(username.value, password.value);
|
||||
const token = await authService.login(username.value, password.value);
|
||||
authStore.setToken(token);
|
||||
router.push('/');
|
||||
} catch (error) {
|
||||
errorMessage.value = error.message || '登录失败';
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { authService } from '@/api/authService';
|
||||
import { defineStore } from 'pinia';
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
@@ -8,13 +7,12 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
|
||||
const isAuthenticated = computed(() => !!token.value);
|
||||
|
||||
async function login(username, password) {
|
||||
const { data } = await authService.login(username, password);
|
||||
token.value = data.token;
|
||||
user.value = data.user;
|
||||
localStorage.setItem('token', data.token);
|
||||
function setToken(newToken) {
|
||||
token.value = newToken;
|
||||
localStorage.setItem('token', newToken);
|
||||
}
|
||||
|
||||
|
||||
function logout() {
|
||||
token.value = null;
|
||||
user.value = null;
|
||||
@@ -25,7 +23,7 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
token,
|
||||
user,
|
||||
isAuthenticated,
|
||||
login,
|
||||
logout
|
||||
logout,
|
||||
setToken
|
||||
};
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user