feat: add JWT authentication and AGENTS.md

This commit is contained in:
祀梦
2026-05-17 11:21:41 +08:00
parent 40eb2dadb0
commit 3c03866021
19 changed files with 554 additions and 1632 deletions

View File

@@ -6,6 +6,7 @@ import { useCategoryStore } from '@/stores/useCategoryStore'
import { useTagStore } from '@/stores/useTagStore'
import { useUIStore } from '@/stores/useUIStore'
import { useUserSettingsStore } from '@/stores/useUserSettingsStore'
import { useAuthStore } from '@/stores/useAuthStore'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import AppHeader from '@/components/AppHeader.vue'
import TaskDialog from '@/components/TaskDialog.vue'
@@ -18,6 +19,7 @@ const categoryStore = useCategoryStore()
const tagStore = useTagStore()
const uiStore = useUIStore()
const userSettingsStore = useUserSettingsStore()
const authStore = useAuthStore()
// 路由变化时同步 currentView
watch(() => route.meta.view, (view) => {
@@ -33,6 +35,8 @@ watch(() => userSettingsStore.siteName, (name) => {
})
onMounted(async () => {
if (!authStore.isLoggedIn) return
await userSettingsStore.fetchAndSync()
// 根据用户设置初始化默认排序
@@ -63,41 +67,46 @@ onMounted(async () => {
<template>
<el-config-provider :locale="zhCn">
<div class="app-container">
<div class="decoration-star" style="top: 20%; right: 8%; animation-delay: 0.5s;"></div>
<div class="decoration-star" style="top: 60%; left: 3%; animation-delay: 1s;"></div>
<div class="decoration-star" style="top: 80%; right: 5%; animation-delay: 1.5s;"></div>
<template v-if="route.name !== 'login'">
<div class="decoration-star" style="top: 20%; right: 8%; animation-delay: 0.5s;"></div>
<div class="decoration-star" style="top: 60%; left: 3%; animation-delay: 1s;"></div>
<div class="decoration-star" style="top: 80%; right: 5%; animation-delay: 1.5s;"></div>
<AppHeader />
<AppHeader />
<div class="app-main">
<main
class="main-content"
:class="{
'full-width': uiStore.currentView !== 'list'
}"
>
<router-view v-slot="{ Component }">
<Transition name="view-fade" mode="out-in">
<component :is="Component" />
</Transition>
</router-view>
</main>
</div>
<div class="app-main">
<main
class="main-content"
:class="{
'full-width': uiStore.currentView !== 'list'
}"
>
<router-view v-slot="{ Component }">
<Transition name="view-fade" mode="out-in">
<component :is="Component" />
</Transition>
</router-view>
</main>
</div>
<div v-if="uiStore.currentView !== 'settings' && uiStore.currentView !== 'profile' && uiStore.currentView !== 'habits' && uiStore.currentView !== 'anniversaries' && uiStore.currentView !== 'assets'" class="fab-container">
<el-button
type="primary"
circle
size="large"
class="add-btn btn-glow"
@click="uiStore.openTaskDialog()"
>
<el-icon :size="24"><Plus /></el-icon>
</el-button>
</div>
<div v-if="uiStore.currentView !== 'settings' && uiStore.currentView !== 'profile' && uiStore.currentView !== 'habits' && uiStore.currentView !== 'anniversaries' && uiStore.currentView !== 'assets'" class="fab-container">
<el-button
type="primary"
circle
size="large"
class="add-btn btn-glow"
@click="uiStore.openTaskDialog()"
>
<el-icon :size="24"><Plus /></el-icon>
</el-button>
</div>
<TaskDialog />
<CategoryDialog />
<TaskDialog />
<CategoryDialog />
</template>
<router-view v-else v-slot="{ Component }">
<component :is="Component" />
</router-view>
</div>
</el-config-provider>
</template>

19
WebUI/src/api/auth.ts Normal file
View File

@@ -0,0 +1,19 @@
import { post } from './request'
export interface LoginResponse {
access_token: string
token_type: string
}
export interface ChangePasswordData {
old_password: string
new_password: string
}
export function login(password: string): Promise<LoginResponse> {
return post<LoginResponse>('/auth/login', { password })
}
export function changePassword(data: ChangePasswordData): Promise<{ message: string }> {
return post<{ message: string }>('/auth/change-password', data)
}

View File

@@ -1,6 +1,8 @@
import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
const TOKEN_KEY = 'elysia_auth_token'
const instance: AxiosInstance = axios.create({
baseURL: '/api',
timeout: 10000,
@@ -9,6 +11,14 @@ const instance: AxiosInstance = axios.create({
}
})
instance.interceptors.request.use((config) => {
const token = localStorage.getItem(TOKEN_KEY)
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
})
instance.interceptors.response.use(
(response: AxiosResponse) => {
return response
@@ -28,7 +38,9 @@ instance.interceptors.response.use(
break
case 401:
message = '登录状态已失效~'
break
localStorage.removeItem(TOKEN_KEY)
window.location.href = '/login'
return Promise.reject(error)
case 403:
message = '没有权限访问呢~'
break

View File

@@ -3,9 +3,11 @@ import { computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUIStore } from '@/stores/useUIStore'
import { useUserSettingsStore } from '@/stores/useUserSettingsStore'
import { useAuthStore } from '@/stores/useAuthStore'
const uiStore = useUIStore()
const userSettingsStore = useUserSettingsStore()
const authStore = useAuthStore()
const router = useRouter()
const route = useRoute()
@@ -21,6 +23,11 @@ function setView(view: string) {
}
function handleCommand(command: string) {
if (command === 'logout') {
authStore.logout()
router.push('/login')
return
}
router.push(`/${command}`)
}
@@ -125,6 +132,10 @@ const currentRouteName = computed(() => route.name as string)
<el-icon><Setting /></el-icon>
<span>偏好设置</span>
</el-dropdown-item>
<el-dropdown-item command="logout" divided>
<el-icon><SwitchButton /></el-icon>
<span>退出登录</span>
</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>

View File

@@ -3,6 +3,12 @@ import type { RouteRecordRaw } from 'vue-router'
import { useUserSettingsStore } from '@/stores/useUserSettingsStore'
const routes: RouteRecordRaw[] = [
{
path: '/login',
name: 'login',
component: () => import('@/views/LoginView.vue'),
meta: { title: '登录', noAuth: true }
},
{
path: '/',
redirect: '/tasks'
@@ -68,11 +74,20 @@ const router = createRouter({
}
})
router.beforeEach((to) => {
const TOKEN_KEY = 'elysia_auth_token'
router.beforeEach((to, from) => {
const page = (to.meta.title as string) || ''
const userStore = useUserSettingsStore()
const siteName = userStore.siteName || '爱莉希雅待办'
document.title = page ? `${page} - ${siteName}` : siteName
if (to.meta.noAuth) return
const token = localStorage.getItem(TOKEN_KEY)
if (!token) {
return { path: '/login', query: { redirect: to.fullPath } }
}
})
export default router

View File

@@ -0,0 +1,49 @@
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as apiLogin } from '@/api/auth'
const TOKEN_KEY = 'elysia_auth_token'
function getStoredToken(): string {
return localStorage.getItem(TOKEN_KEY) || ''
}
function setStoredToken(token: string) {
localStorage.setItem(TOKEN_KEY, token)
}
function clearStoredToken() {
localStorage.removeItem(TOKEN_KEY)
}
export const useAuthStore = defineStore('auth', () => {
const token = ref<string>(getStoredToken())
const loading = ref(false)
const error = ref('')
const isLoggedIn = computed(() => !!token.value)
async function login(password: string): Promise<boolean> {
loading.value = true
error.value = ''
try {
const res = await apiLogin(password)
token.value = res.access_token
setStoredToken(res.access_token)
return true
} catch (e: any) {
error.value = e?.response?.data?.detail || '登录失败'
return false
} finally {
loading.value = false
}
}
function logout() {
token.value = ''
error.value = ''
clearStoredToken()
}
return { token, loading, error, isLoggedIn, login, logout }
})

View File

@@ -0,0 +1,157 @@
<script setup lang="ts">
import { ref, shallowRef } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Lock } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/useAuthStore'
import { useUserSettingsStore } from '@/stores/useUserSettingsStore'
const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()
const userSettingsStore = useUserSettingsStore()
const password = ref('')
const loading = ref(false)
const error = ref('')
const redirect = (route.query.redirect as string) || '/'
async function handleLogin() {
if (!password.value) return
loading.value = true
error.value = ''
try {
const ok = await authStore.login(password.value)
if (ok) {
await userSettingsStore.fetchAndSync()
router.replace(redirect)
} else {
error.value = authStore.error || '密码错误'
}
} finally {
loading.value = false
}
}
</script>
<template>
<div class="login-wrapper">
<div class="decoration-star" style="top: 10%; right: 15%; animation-delay: 0s;"></div>
<div class="decoration-star" style="top: 70%; left: 10%; animation-delay: 1s;"></div>
<div class="decoration-star" style="top: 30%; left: 20%; animation-delay: 2s;"></div>
<div class="login-card">
<div class="login-header">
<div class="logo-icon"></div>
<h1 class="site-name">{{ userSettingsStore.siteName }}</h1>
<p class="subtitle">需要密码才能进入哦~</p>
</div>
<el-form @submit.prevent="handleLogin" class="login-form">
<el-input
v-model="password"
type="password"
placeholder="请输入密码"
size="large"
show-password
:prefix-icon="Lock"
@keyup.enter="handleLogin"
/>
<p v-if="error" class="error-msg">{{ error }}</p>
<el-button
type="primary"
size="large"
:loading="loading"
class="login-btn"
@click="handleLogin"
>
进入
</el-button>
</el-form>
</div>
</div>
</template>
<style scoped lang="scss">
.login-wrapper {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, #fce4ec 0%, #f8bbd0 30%, #f48fb1 60%, #fce4ec 100%);
position: relative;
overflow: hidden;
}
.login-card {
background: rgba(255, 255, 255, 0.85);
backdrop-filter: blur(16px);
border-radius: 24px;
padding: 48px 40px;
width: 400px;
max-width: 90vw;
box-shadow: 0 8px 32px rgba(255, 183, 197, 0.3);
z-index: 1;
}
.login-header {
text-align: center;
margin-bottom: 32px;
.logo-icon {
font-size: 48px;
color: var(--primary);
animation: twinkle 2s ease-in-out infinite;
margin-bottom: 12px;
}
.site-name {
font-size: 24px;
font-weight: 700;
background: linear-gradient(135deg, var(--primary) 0%, var(--accent) 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
margin: 0 0 8px;
}
.subtitle {
font-size: 14px;
color: var(--text-secondary);
margin: 0;
}
}
.login-form {
display: flex;
flex-direction: column;
gap: 16px;
}
.error-msg {
color: #f56c6c;
font-size: 13px;
margin: 0;
text-align: center;
}
.login-btn {
width: 100%;
height: 44px;
font-size: 16px;
font-weight: 600;
background: linear-gradient(135deg, var(--primary) 0%, var(--accent) 100%);
border: none;
border-radius: 12px;
&:hover {
transform: translateY(-1px);
box-shadow: 0 4px 16px rgba(255, 183, 197, 0.5);
}
}
@keyframes twinkle {
0%, 100% { opacity: 1; transform: scale(1); }
50% { opacity: 0.7; transform: scale(1.05); }
}
</style>