feat: 接入两端用户名登录和独立学习空间 (#2)
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
import { watch } from 'vue'
|
||||
import { RouterView, useRouter } from 'vue-router'
|
||||
import { useSessionStore } from './stores/session'
|
||||
const session = useSessionStore()
|
||||
const router = useRouter()
|
||||
watch(() => session.user, user => {
|
||||
if (!user && router.currentRoute.value.meta.private) void router.replace('/login')
|
||||
})
|
||||
</script>
|
||||
|
||||
<template><RouterView /></template>
|
||||
@@ -0,0 +1,114 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { useSessionStore, TOKEN_KEY } from '../stores/session'
|
||||
|
||||
// All accounts and tokens in these tests are deliberately fictitious.
|
||||
const user = { id: 7, username: 'fictional-reader', role: 'learner' }
|
||||
const ok = (data: unknown) => new Response(JSON.stringify({ code: 200, data }), { status: 200 })
|
||||
const denied = () => new Response(JSON.stringify({ code: 401, msg: '账号或密码错误' }), { status: 401 })
|
||||
const loginResult = () => ok({ token: 'fictional-token', expiresAt: '2030-01-01', user })
|
||||
|
||||
describe('learner session boundaries', () => {
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear()
|
||||
setActivePinia(createPinia())
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('accepts a username without email format and stores only the opaque token', async () => {
|
||||
const fetch = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(loginResult())
|
||||
const store = useSessionStore()
|
||||
await store.login('fictional-reader', 'fictional-password')
|
||||
expect(JSON.parse(fetch.mock.calls[0]![1]!.body as string)).toEqual({ username: 'fictional-reader', password: 'fictional-password' })
|
||||
expect(store.user).toEqual(user)
|
||||
expect(sessionStorage.getItem(TOKEN_KEY)).toBe('fictional-token')
|
||||
expect(sessionStorage.length).toBe(1)
|
||||
})
|
||||
|
||||
it('failed account switch clears the previous private identity and space', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(loginResult()).mockResolvedValueOnce(ok({ ownerId: 7, language: 'en' })).mockResolvedValueOnce(denied())
|
||||
const store = useSessionStore()
|
||||
await store.login('fictional-reader', 'fictional-password')
|
||||
await store.loadSpace()
|
||||
await expect(store.login('fictional-other', 'incorrect')).rejects.toThrow('账号或密码错误')
|
||||
expect(store.user).toBeNull()
|
||||
expect(store.space).toBeNull()
|
||||
expect(sessionStorage.getItem(TOKEN_KEY)).toBeNull()
|
||||
})
|
||||
|
||||
it('validates a persisted session before exposing identity and clears it on 401', async () => {
|
||||
sessionStorage.setItem(TOKEN_KEY, 'fictional-expired-token')
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(denied())
|
||||
const store = useSessionStore()
|
||||
expect(store.user).toBeNull()
|
||||
await store.restore()
|
||||
expect(store.user).toBeNull()
|
||||
expect(sessionStorage.getItem(TOKEN_KEY)).toBeNull()
|
||||
})
|
||||
|
||||
it('clears identity and space when a private request gets 401', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(loginResult()).mockResolvedValueOnce(denied())
|
||||
const store = useSessionStore()
|
||||
await store.login('fictional-reader', 'fictional-password')
|
||||
await expect(store.loadSpace()).rejects.toThrow()
|
||||
expect(store.user).toBeNull()
|
||||
expect(store.space).toBeNull()
|
||||
expect(sessionStorage.getItem(TOKEN_KEY)).toBeNull()
|
||||
})
|
||||
|
||||
it('clears locally immediately even if server logout fails', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(loginResult()).mockRejectedValueOnce(new Error('offline'))
|
||||
const store = useSessionStore()
|
||||
await store.login('fictional-reader', 'fictional-password')
|
||||
const logout = store.logout()
|
||||
expect(store.user).toBeNull()
|
||||
expect(store.space).toBeNull()
|
||||
expect(sessionStorage.getItem(TOKEN_KEY)).toBeNull()
|
||||
await expect(logout).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('does not resurrect private space from a response arriving after logout', async () => {
|
||||
let finish!: (value: Response) => void
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(loginResult()).mockImplementationOnce(() => new Promise(resolve => { finish = resolve })).mockResolvedValueOnce(ok(null))
|
||||
const store = useSessionStore()
|
||||
await store.login('fictional-reader', 'fictional-password')
|
||||
const request = store.loadSpace()
|
||||
await store.logout()
|
||||
finish(ok({ ownerId: 7, language: 'en' }))
|
||||
await request
|
||||
expect(store.space).toBeNull()
|
||||
expect(store.user).toBeNull()
|
||||
})
|
||||
|
||||
it('an old request 401 cannot clear a newly signed-in account', async () => {
|
||||
let finish!: (value: Response) => void
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(loginResult()).mockImplementationOnce(() => new Promise(resolve => { finish = resolve })).mockResolvedValueOnce(ok({ token: 'fictional-new-token', user: { ...user, id: 9 } }))
|
||||
const store = useSessionStore()
|
||||
await store.login('fictional-reader', 'fictional-password')
|
||||
const request = store.loadSpace()
|
||||
await store.login('fictional-other', 'fictional-password')
|
||||
finish(denied())
|
||||
await expect(request).rejects.toThrow()
|
||||
expect(store.user?.id).toBe(9)
|
||||
})
|
||||
|
||||
it('a late login response cannot restore a session after logout', async () => {
|
||||
let finish!: (value: Response) => void
|
||||
vi.spyOn(globalThis, 'fetch').mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
|
||||
const store = useSessionStore()
|
||||
const request = store.login('fictional-reader', 'fictional-password')
|
||||
await store.logout()
|
||||
finish(loginResult())
|
||||
await request
|
||||
expect(store.user).toBeNull()
|
||||
expect(sessionStorage.getItem(TOKEN_KEY)).toBeNull()
|
||||
})
|
||||
|
||||
it('does not expose a space whose owner differs from the authenticated account', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(loginResult()).mockResolvedValueOnce(ok({ ownerId: 99, language: 'en' }))
|
||||
const store = useSessionStore()
|
||||
await store.login('fictional-reader', 'fictional-password')
|
||||
await expect(store.loadSpace()).rejects.toThrow()
|
||||
expect(store.space).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,6 @@
|
||||
<template>
|
||||
<svg class="book-mark" viewBox="0 0 64 64" fill="none" aria-hidden="true">
|
||||
<path d="M32 18C24 12 14 12 6 15v36c8-3 18-3 26 3 8-6 18-6 26-3V15c-8-3-18-3-26 3Z" stroke="currentColor" stroke-width="2" stroke-linejoin="round" />
|
||||
<path d="M32 18v36M15 24c4-1 7 0 10 1M15 32c4-1 7 0 10 1M40 25c3-1 6-2 10-1M40 33c3-1 6-2 10-1" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
|
||||
</svg>
|
||||
</template>
|
||||
@@ -0,0 +1,9 @@
|
||||
import { createApp } from 'vue'
|
||||
import { createPinia } from 'pinia'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
import 'element-plus/es/components/button/style/css'
|
||||
import 'element-plus/es/components/input/style/css'
|
||||
import './style.css'
|
||||
|
||||
createApp(App).use(createPinia()).use(router).mount('#app')
|
||||
@@ -0,0 +1,18 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import { useSessionStore } from '../stores/session'
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(import.meta.env.BASE_URL),
|
||||
routes: [
|
||||
{ path: '/login', name: 'login', component: () => import('../views/LoginView.vue') },
|
||||
{ path: '/', name: 'library', meta: { private: true }, component: () => import('../views/LibraryView.vue') },
|
||||
{ path: '/:pathMatch(.*)*', redirect: '/' },
|
||||
],
|
||||
})
|
||||
router.beforeEach(async to => {
|
||||
const session = useSessionStore()
|
||||
await session.restore()
|
||||
if (to.meta.private && !session.user) return '/login'
|
||||
if (to.name === 'login' && session.user) return '/'
|
||||
})
|
||||
export default router
|
||||
@@ -0,0 +1,95 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
|
||||
export const TOKEN_KEY = 'lexgo-learner-token'
|
||||
interface User { id: number; username: string; role: 'admin' | 'learner' }
|
||||
interface Space { ownerId: number; language: 'en' }
|
||||
interface Login { token: string; expiresAt: string; user: User }
|
||||
|
||||
export const useSessionStore = defineStore('session', () => {
|
||||
const user = ref<User | null>(null)
|
||||
const space = ref<Space | null>(null)
|
||||
const notice = ref('')
|
||||
let token = sessionStorage.getItem(TOKEN_KEY) ?? ''
|
||||
// Invalidate all in-flight work on any session boundary, including failed switches.
|
||||
let generation = 0
|
||||
let initialized = false
|
||||
let restoring: Promise<void> | undefined
|
||||
|
||||
function clear() {
|
||||
generation++
|
||||
token = ''
|
||||
user.value = null
|
||||
space.value = null
|
||||
sessionStorage.removeItem(TOKEN_KEY)
|
||||
}
|
||||
|
||||
async function request<T>(path: string, method = 'GET', body?: unknown, auth = token, version = generation): Promise<T> {
|
||||
const response = await fetch(`/api/v1/${path}`, {
|
||||
method,
|
||||
headers: { ...(auth ? { Authorization: `Bearer ${auth}` } : {}), ...(body ? { 'Content-Type': 'application/json' } : {}) },
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
cache: 'no-store',
|
||||
})
|
||||
if (response.status === 401 && version === generation) {
|
||||
clear()
|
||||
notice.value = '登录已失效,请重新登录。'
|
||||
}
|
||||
const result = await response.json()
|
||||
if (!response.ok || result.code !== 200) throw new Error(result.msg || '请求失败,请稍后重试。')
|
||||
return result.data as T
|
||||
}
|
||||
|
||||
async function login(username: string, password: string) {
|
||||
clear()
|
||||
initialized = true
|
||||
notice.value = ''
|
||||
const version = generation
|
||||
const result = await request<Login>('login', 'POST', { username, password }, '', version)
|
||||
if (version !== generation) return
|
||||
sessionStorage.setItem(TOKEN_KEY, result.token)
|
||||
token = result.token
|
||||
user.value = result.user
|
||||
}
|
||||
|
||||
async function restore() {
|
||||
if (initialized) return
|
||||
if (restoring) return restoring
|
||||
const version = generation
|
||||
restoring = (async () => {
|
||||
try {
|
||||
if (!token) return
|
||||
const account = await request<User>('me')
|
||||
if (version === generation) user.value = account
|
||||
} catch {
|
||||
if (version === generation) {
|
||||
clear()
|
||||
notice.value = '暂时无法恢复登录,请重新登录。'
|
||||
}
|
||||
} finally {
|
||||
initialized = true
|
||||
restoring = undefined
|
||||
}
|
||||
})()
|
||||
return restoring
|
||||
}
|
||||
|
||||
async function loadSpace() {
|
||||
if (!user.value) throw new Error('请先登录。')
|
||||
const version = generation
|
||||
const ownerId = user.value.id
|
||||
const result = await request<Space>('space')
|
||||
if (version !== generation) return
|
||||
if (result.ownerId !== ownerId || result.language !== 'en') throw new Error('学习空间暂时无法加载,请稍后重试。')
|
||||
space.value = result
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
const previousToken = token
|
||||
clear()
|
||||
notice.value = ''
|
||||
if (previousToken) await request<null>('logout', 'POST', undefined, previousToken, -1)
|
||||
}
|
||||
|
||||
return { user, space, notice, login, restore, logout, loadSpace }
|
||||
})
|
||||
@@ -0,0 +1,65 @@
|
||||
:root {
|
||||
font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
|
||||
color: #233d31;
|
||||
background: #f7f5ee;
|
||||
font-synthesis: none;
|
||||
--el-color-primary: #315c43;
|
||||
--el-color-primary-light-3: #597f66;
|
||||
--el-color-primary-light-5: #8da493;
|
||||
--el-color-primary-light-7: #bdccc0;
|
||||
--el-color-primary-light-9: #eef2eb;
|
||||
--el-color-primary-dark-2: #264a35;
|
||||
--el-border-radius-base: 8px;
|
||||
--el-font-size-base: 15px;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; min-width: 320px; }
|
||||
button, input { font: inherit; }
|
||||
button:focus-visible, a:focus-visible { outline: 3px solid #bc803d; outline-offset: 4px; }
|
||||
a { color: inherit; }
|
||||
.brand { font-family: Georgia, serif; font-size: 30px; font-weight: 700; letter-spacing: -1px; text-decoration: none; }
|
||||
.brand-dot { color: #ba8345; }
|
||||
.login-page { min-height: 100dvh; display: grid; grid-template-columns: minmax(340px, 1fr) minmax(400px, 1fr); }
|
||||
.welcome { background: #284c38; color: #f7f5ee; padding: 46px 10%; display: flex; flex-direction: column; justify-content: space-between; }
|
||||
.welcome .brand { color: #f7f5ee; }
|
||||
.welcome-copy { padding: 80px 0; max-width: 450px; }
|
||||
.welcome-copy h2 { font-family: Georgia, 'Microsoft YaHei', serif; font-weight: 400; font-size: clamp(32px, 3.3vw, 52px); line-height: 1.55; letter-spacing: 2px; margin: 26px 0; }
|
||||
.welcome-copy p { font-size: 16px; color: #d4dfd2; line-height: 1.9; }
|
||||
.book-mark { width: 60px; height: 60px; color: #d6b980; }
|
||||
.welcome-foot { font-size: 13px; letter-spacing: 2px; color: #c4d1c0; }
|
||||
.login-main { display: grid; place-items: center; padding: 48px 28px; }
|
||||
.login-form { width: min(100%, 360px); }
|
||||
.eyebrow { color: #687568; font-size: 12px; letter-spacing: 3px; }
|
||||
h1 { font-size: 30px; font-weight: 600; margin: 14px 0; letter-spacing: 1px; }
|
||||
.subtle { color: #748073; font-size: 14px; line-height: 1.8; }
|
||||
.login-form form { margin-top: 36px; }
|
||||
.field { display: block; margin-bottom: 22px; }
|
||||
.field label { display: block; font-size: 14px; margin-bottom: 10px; }
|
||||
.el-input { --el-input-height: 46px; --el-input-bg-color: #fffefa; --el-input-border-color: #d6dccf; }
|
||||
.el-button { min-height: 42px; }
|
||||
.login-submit { width: 100%; margin-top: 8px; height: 48px; letter-spacing: 4px; }
|
||||
.notice { padding: 12px 15px; background: #fff0e7; border: 1px solid #ebc3a8; color: #8b4324; border-radius: 6px; font-size: 14px; line-height: 1.6; }
|
||||
.site-header { padding: 24px max(24px, calc((100vw - 1200px) / 2)); border-bottom: 1px solid #e0e3d8; display: flex; align-items: center; gap: 32px; background: #fffdf7; }
|
||||
.site-header nav { flex: 1; }
|
||||
.active-nav { font-size: 15px; text-decoration: none; padding: 13px 0; border-bottom: 2px solid #315c43; }
|
||||
.account { display: flex; align-items: center; gap: 18px; font-size: 14px; }
|
||||
.account-name { max-width: 200px; overflow: hidden; text-overflow: ellipsis; }
|
||||
.library { max-width: 1120px; margin: 60px auto; padding: 0 28px; }
|
||||
.library-title { display: flex; align-items: center; justify-content: space-between; gap: 20px; margin-bottom: 38px; }
|
||||
.language { border: 1px solid #d9decf; padding: 9px 17px; border-radius: 20px; font-size: 13px; background: #fffdf7; }
|
||||
.empty-library { background: #fffdf8; border: 1px solid #e0e3d8; border-radius: 12px; min-height: 360px; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 44px 20px; text-align: center; }
|
||||
.empty-library .book-mark { color: #6e8967; width: 56px; height: 56px; }
|
||||
.empty-library h2 { font-weight: 500; font-size: 21px; margin: 26px 0 4px; }
|
||||
.loading { padding: 80px 24px; text-align: center; color: #748073; }
|
||||
@media (max-width: 760px) {
|
||||
.login-page { grid-template-columns: 1fr; }
|
||||
.welcome { padding: 28px; }
|
||||
.welcome-copy, .welcome-foot { display: none; }
|
||||
.login-main { padding: 50px 28px 70px; align-items: start; }
|
||||
.site-header { padding: 20px; gap: 22px; flex-wrap: wrap; }
|
||||
.account { margin-left: auto; gap: 10px; }
|
||||
.account-name { max-width: 120px; }
|
||||
.site-header nav { order: 3; flex-basis: 100%; padding-top: 8px; }
|
||||
.library { margin-top: 32px; padding: 0 20px; }
|
||||
h1 { font-size: 26px; }
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { RouterLink, useRouter } from 'vue-router'
|
||||
import { ElButton } from 'element-plus'
|
||||
import BookMark from '../components/BookMark.vue'
|
||||
import { useSessionStore } from '../stores/session'
|
||||
const session = useSessionStore()
|
||||
const router = useRouter()
|
||||
const loading = ref(true)
|
||||
const error = ref('')
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try { await session.loadSpace() }
|
||||
catch (reason) { error.value = reason instanceof Error ? reason.message : '暂时无法加载,请重试。' }
|
||||
finally { loading.value = false }
|
||||
}
|
||||
async function logout() {
|
||||
try { await session.logout() }
|
||||
catch { session.notice = '已退出此设备。服务器暂时无法连接,请稍后重试。' }
|
||||
finally { await router.replace('/login') }
|
||||
}
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="session.user">
|
||||
<header class="site-header">
|
||||
<RouterLink to="/" class="brand">LexGo<span class="brand-dot">.</span></RouterLink>
|
||||
<nav aria-label="学习导航"><RouterLink to="/" class="active-nav">我的书库</RouterLink></nav>
|
||||
<div class="account">
|
||||
<span class="account-name">{{ session.user.username }}</span>
|
||||
<ElButton text @click="logout">退出登录</ElButton>
|
||||
</div>
|
||||
</header>
|
||||
<main class="library">
|
||||
<div class="library-title"><div><h1>我的书库</h1><p class="subtle">你的阅读与学习,从这里开始。</p></div><span class="language">英语</span></div>
|
||||
<p v-if="loading" role="status" class="loading">正在加载…</p>
|
||||
<div v-else-if="error" class="notice"><p role="alert">{{ error }}</p><ElButton @click="load">重试</ElButton></div>
|
||||
<section v-else-if="session.space" class="empty-library" aria-label="书库内容">
|
||||
<BookMark /><h2>书库还是空的</h2><p class="subtle">这里将收纳你的阅读内容。</p>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,61 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { ElButton, ElInput } from 'element-plus'
|
||||
import BookMark from '../components/BookMark.vue'
|
||||
import { useSessionStore } from '../stores/session'
|
||||
const session = useSessionStore()
|
||||
const router = useRouter()
|
||||
const username = ref('')
|
||||
const password = ref('')
|
||||
const busy = ref(false)
|
||||
const error = ref('')
|
||||
async function submit() {
|
||||
if (busy.value) return
|
||||
error.value = ''
|
||||
session.notice = ''
|
||||
if (!username.value.trim() || !password.value) {
|
||||
error.value = '请输入账号和密码。'
|
||||
return
|
||||
}
|
||||
busy.value = true
|
||||
try {
|
||||
await session.login(username.value.trim(), password.value)
|
||||
if (session.user) await router.replace('/')
|
||||
} catch (reason) {
|
||||
error.value = reason instanceof Error ? reason.message : '登录失败,请稍后重试。'
|
||||
session.notice = ''
|
||||
} finally {
|
||||
password.value = ''
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="login-page">
|
||||
<aside class="welcome">
|
||||
<div class="brand">LexGo<span class="brand-dot">.</span></div>
|
||||
<div class="welcome-copy">
|
||||
<BookMark />
|
||||
</div>
|
||||
</aside>
|
||||
<main class="login-main">
|
||||
<div class="login-form">
|
||||
<h1>欢迎回来</h1>
|
||||
<p v-if="error || session.notice" role="alert" class="notice">{{ error || session.notice }}</p>
|
||||
<form @submit.prevent="submit">
|
||||
<div class="field">
|
||||
<label for="username">账号</label>
|
||||
<ElInput id="username" v-model="username" type="text" autocomplete="username" placeholder="请输入账号" :disabled="busy" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="password">密码</label>
|
||||
<ElInput id="password" v-model="password" type="password" autocomplete="current-password" placeholder="请输入密码" show-password :disabled="busy" />
|
||||
</div>
|
||||
<ElButton class="login-submit" type="primary" native-type="submit" :loading="busy">登录</ElButton>
|
||||
</form>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</template>
|
||||
Reference in New Issue
Block a user