改用流式鉴权播放设备教程视频
This commit is contained in:
Vendored
+1
-1
@@ -366,7 +366,7 @@
|
|||||||
|
|
||||||
<div id="toast" class="toast hidden" role="status" aria-live="polite"></div>
|
<div id="toast" class="toast hidden" role="status" aria-live="polite"></div>
|
||||||
|
|
||||||
<script src="/js/app.js?v=49"></script>
|
<script src="/js/app.js?v=50"></script>
|
||||||
</div>
|
</div>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
Vendored
+14
-33
@@ -45,7 +45,17 @@
|
|||||||
|
|
||||||
// ------------------------------------------------------------- API
|
// ------------------------------------------------------------- API
|
||||||
const getToken = () => localStorage.getItem(TOKEN_KEY) || "";
|
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) {
|
function apiErrorMessage(detail, status) {
|
||||||
if (typeof detail === "string" && detail) return detail;
|
if (typeof detail === "string" && detail) return detail;
|
||||||
@@ -1642,7 +1652,6 @@
|
|||||||
// ---- 设备使用教程
|
// ---- 设备使用教程
|
||||||
const TUTORIAL_PAGE = 60;
|
const TUTORIAL_PAGE = 60;
|
||||||
const tutorialState = { items: [], q: '', hasMore: false, seq: 0 };
|
const tutorialState = { items: [], q: '', hasMore: false, seq: 0 };
|
||||||
const tutorialVideoUrls = new Map();
|
|
||||||
let tutorialDebounce = null, tutorialProgressHandler = null;
|
let tutorialDebounce = null, tutorialProgressHandler = null;
|
||||||
const fmtBytes = (bytes) => {
|
const fmtBytes = (bytes) => {
|
||||||
if (!bytes) return '';
|
if (!bytes) return '';
|
||||||
@@ -1662,48 +1671,20 @@
|
|||||||
}
|
}
|
||||||
function paintTutorials() {
|
function paintTutorials() {
|
||||||
const list = $('#tutorial-list');
|
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('');
|
list.innerHTML = tutorialState.items.map(tutorialCard).join('');
|
||||||
$('#tutorial-empty').classList.toggle('hidden', !!tutorialState.items.length || !!tutorialState.q);
|
$('#tutorial-empty').classList.toggle('hidden', !!tutorialState.items.length || !!tutorialState.q);
|
||||||
$('#tutorial-more').classList.toggle('hidden', !tutorialState.hasMore);
|
$('#tutorial-more').classList.toggle('hidden', !tutorialState.hasMore);
|
||||||
$('#tutorial-empty').textContent = tutorialState.q ? '没有匹配的教程,换个教室号或器材名试试。' : '还没有教程,点「+ 上传教程」添加第一份。';
|
$('#tutorial-empty').textContent = tutorialState.q ? '没有匹配的教程,换个教室号或器材名试试。' : '还没有教程,点「+ 上传教程」添加第一份。';
|
||||||
}
|
}
|
||||||
async function playTutorial(index) {
|
function playTutorial(index) {
|
||||||
const card = $('#tutorial-list article:nth-child(' + (index + 1) + ')');
|
const card = $('#tutorial-list article:nth-child(' + (index + 1) + ')');
|
||||||
const video = card?.querySelector('video');
|
const video = card?.querySelector('video');
|
||||||
const item = tutorialState.items[index];
|
const item = tutorialState.items[index];
|
||||||
if (!video || !item) return;
|
if (!video || !item) return;
|
||||||
if (video.dataset.loading === '1') return;
|
|
||||||
if (video.dataset.loaded === '0') {
|
if (video.dataset.loaded === '0') {
|
||||||
video.dataset.loading = '1';
|
video.addEventListener('error', () => toast('视频加载失败,请重新登录或稍后重试', true), { once: true });
|
||||||
video.setAttribute('aria-busy', 'true');
|
video.src = `/api/center/tutorials/${encodeURIComponent(item.id)}`;
|
||||||
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';
|
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.play().catch(() => {});
|
video.play().catch(() => {});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -201,6 +201,8 @@ async def get_db():
|
|||||||
async def current_user(request: Request, db: AsyncSession = Depends(get_db)) -> dict:
|
async def current_user(request: Request, db: AsyncSession = Depends(get_db)) -> dict:
|
||||||
header = request.headers.get("authorization", "")
|
header = request.headers.get("authorization", "")
|
||||||
token = header[7:].strip() if header.lower().startswith("bearer ") else ""
|
token = header[7:].strip() if header.lower().startswith("bearer ") else ""
|
||||||
|
if not token:
|
||||||
|
token = request.cookies.get("worklog_token", "").strip()
|
||||||
if not token:
|
if not token:
|
||||||
raise HTTPException(status_code=401, detail="请先登录")
|
raise HTTPException(status_code=401, detail="请先登录")
|
||||||
row = (await db.execute(select(sessions).where(sessions.c.token == token_digest(token)))).mappings().first()
|
row = (await db.execute(select(sessions).where(sessions.c.token == token_digest(token)))).mappings().first()
|
||||||
|
|||||||
@@ -47,6 +47,51 @@ def auth(token: str) -> dict:
|
|||||||
return {"Authorization": f"Bearer {token}"}
|
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):
|
class ApiTestCase(unittest.IsolatedAsyncioTestCase):
|
||||||
@classmethod
|
@classmethod
|
||||||
def setUpClass(cls):
|
def setUpClass(cls):
|
||||||
|
|||||||
Reference in New Issue
Block a user