diff --git a/dist/index.html b/dist/index.html index 5c24300..aa46a41 100644 --- a/dist/index.html +++ b/dist/index.html @@ -366,7 +366,7 @@ - + diff --git a/dist/js/app.js b/dist/js/app.js index 75dbc02..11e1c48 100644 --- a/dist/js/app.js +++ b/dist/js/app.js @@ -45,7 +45,17 @@ // ------------------------------------------------------------- API const getToken = () => localStorage.getItem(TOKEN_KEY) || ""; - const setToken = (t) => (t ? localStorage.setItem(TOKEN_KEY, t) : localStorage.removeItem(TOKEN_KEY)); + function syncAuthCookie() { + const token = getToken(); + const secure = location.protocol === 'https:' ? '; Secure' : ''; + document.cookie = `${TOKEN_KEY}=${encodeURIComponent(token)}; Path=/; Max-Age=${token ? 30 * 24 * 60 * 60 : 0}; SameSite=Strict${secure}`; + } + function setToken(token) { + if (token) localStorage.setItem(TOKEN_KEY, token); + else localStorage.removeItem(TOKEN_KEY); + syncAuthCookie(); + } + syncAuthCookie(); function apiErrorMessage(detail, status) { if (typeof detail === "string" && detail) return detail; @@ -1642,7 +1652,6 @@ // ---- 设备使用教程 const TUTORIAL_PAGE = 60; const tutorialState = { items: [], q: '', hasMore: false, seq: 0 }; - const tutorialVideoUrls = new Map(); let tutorialDebounce = null, tutorialProgressHandler = null; const fmtBytes = (bytes) => { if (!bytes) return ''; @@ -1662,48 +1671,20 @@ } function paintTutorials() { const list = $('#tutorial-list'); - list.querySelectorAll('video').forEach(video => { - if (video.src) URL.revokeObjectURL(video.src); - }); - tutorialVideoUrls.forEach(url => URL.revokeObjectURL(url)); - tutorialVideoUrls.clear(); list.innerHTML = tutorialState.items.map(tutorialCard).join(''); $('#tutorial-empty').classList.toggle('hidden', !!tutorialState.items.length || !!tutorialState.q); $('#tutorial-more').classList.toggle('hidden', !tutorialState.hasMore); $('#tutorial-empty').textContent = tutorialState.q ? '没有匹配的教程,换个教室号或器材名试试。' : '还没有教程,点「+ 上传教程」添加第一份。'; } - async function playTutorial(index) { + function playTutorial(index) { const card = $('#tutorial-list article:nth-child(' + (index + 1) + ')'); const video = card?.querySelector('video'); const item = tutorialState.items[index]; if (!video || !item) return; - if (video.dataset.loading === '1') return; if (video.dataset.loaded === '0') { - video.dataset.loading = '1'; - video.setAttribute('aria-busy', 'true'); - try { - let url = tutorialVideoUrls.get(item.id); - if (!url) { - const response = await fetch(`/api/center/tutorials/${encodeURIComponent(item.id)}`, { - headers: { Authorization: `Bearer ${getToken()}` }, - }); - if (!response.ok) { - const error = await response.json().catch(() => ({})); - throw new Error(typeof error.detail === 'string' ? error.detail : '视频加载失败,请稍后重试'); - } - url = URL.createObjectURL(await response.blob()); - tutorialVideoUrls.set(item.id, url); - } - video.src = url; - video.dataset.loaded = '1'; - } catch (error) { - toast(error.message, true); - video.dataset.loading = '0'; - video.removeAttribute('aria-busy'); - return; - } - video.dataset.loading = '0'; - video.removeAttribute('aria-busy'); + video.addEventListener('error', () => toast('视频加载失败,请重新登录或稍后重试', true), { once: true }); + video.src = `/api/center/tutorials/${encodeURIComponent(item.id)}`; + video.dataset.loaded = '1'; } video.play().catch(() => {}); } diff --git a/server/main.py b/server/main.py index 9500396..d3de8df 100644 --- a/server/main.py +++ b/server/main.py @@ -201,6 +201,8 @@ async def get_db(): async def current_user(request: Request, db: AsyncSession = Depends(get_db)) -> dict: header = request.headers.get("authorization", "") token = header[7:].strip() if header.lower().startswith("bearer ") else "" + if not token: + token = request.cookies.get("worklog_token", "").strip() if not token: raise HTTPException(status_code=401, detail="请先登录") row = (await db.execute(select(sessions).where(sessions.c.token == token_digest(token)))).mappings().first() diff --git a/tests/test_api.py b/tests/test_api.py index 6b3077b..a29ffc0 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -47,6 +47,51 @@ def auth(token: str) -> dict: return {"Authorization": f"Bearer {token}"} +class AuthCookieApiTest(unittest.IsolatedAsyncioTestCase): + @classmethod + def setUpClass(cls): + cls.directory = Path(tempfile.gettempdir()) / f"worklog-test-cookie-{uuid4().hex}" + cls.directory.mkdir() + with patch.dict(os.environ, { + "WORKLOG_DB": str(cls.directory / "test.db"), + "WORKLOG_PORT": "34199", + }): + import server.main as m + cls.m = m + + @classmethod + def tearDownClass(cls): + import shutil + if cls.directory.resolve().parent != Path(tempfile.gettempdir()).resolve(): + raise RuntimeError("Refusing to remove a test directory outside the temp root") + shutil.rmtree(cls.directory) + + def setUp(self): + self.patch_dev = patch.object(self.m, "DEV_MODE", True) + self.patch_dev.start() + self.engine = self.m.create_async_engine("sqlite+aiosqlite:///:memory:", future=True) + self.sessions = self.m.async_sessionmaker(self.engine, expire_on_commit=False) + self.patch_session = patch.object(self.m, "SessionLocal", self.sessions) + self.patch_session.start() + + def tearDown(self): + self.patch_session.stop() + self.patch_dev.stop() + + async def asyncSetUp(self): + async with self.engine.begin() as conn: + await conn.run_sync(self.m.metadata.create_all) + self.client = AsyncClient(transport=ASGITransport(app=self.m.app), base_url="http://localhost") + + async def asyncTearDown(self): + await self.client.aclose() + + async def test_bearer_or_cookie_can_authenticate(self): + user = await register(self.client, 'cookietester') + self.assertEqual((await self.client.get('/api/auth/me', headers=auth(user['token']))).status_code, 200) + self.assertEqual((await self.client.get('/api/auth/me', cookies={'worklog_token': user['token']})).status_code, 200) + + class ApiTestCase(unittest.IsolatedAsyncioTestCase): @classmethod def setUpClass(cls):