Merge branch 'feat/sign-in-state-and-logout'

# Conflicts:
#	backend/sokhan/api/routes_auth.py
#	bot/tests/test_client_errors.py
#	web/messages/en.json
#	web/messages/fa.json
#	web/src/components/site-header.tsx
This commit is contained in:
ahp committed 2026-11-26 18:04:53 +03:30
commit 3895219768
18 files changed
+460 -21

No files matched your search

+12
View File
@@ -97,6 +97,14 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
- `CONTRIBUTING.fa.md`: a Persian translation of the contribution guide,
with a language switcher in both files like the READMEs (#31).
- `POST /auth/logout` revokes the caller's token (204). An account has a
single active token, so it signs out every client holding it.
- The dashboard header shows the sign-in state: a **Sign in** button when
signed out, the account email and **Sign out** when signed in. Sign out
revokes the token on the server and works even when the API is
unreachable. The landing page's sign-in button is hidden and the login
page redirects to the upload page for a signed-in user.
### Changed
@@ -134,6 +142,10 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
kept as is; a comma in a list of numbers (`4090,4080`) still becomes `،`.
The edge cases from #30 (slash dates, Latin digits in Persian sentences,
abbreviations, ellipses, repeated marks) are pinned by tests.
- The Telegram bot recovers when the API revokes the token it cached for a
chat (a newer sign-in or a logout of the same account). Every request
used to fail from then on; the bot now drops the token, re-registers
once and retries, and `/start` only shows a connect code that works.
## [1.4.1] - 2026-11-26
+17 -2
View File
@@ -7,16 +7,17 @@ Deliberately lightweight for v1:
- POST /auth/telegram lets the bot create or resume an account per Telegram id
- POST /auth/token-login lets a user paste the connect code shown by the bot
to link their browser session
- POST /auth/logout revokes the caller's token
"""
import re
from fastapi import APIRouter, Depends, HTTPException, Request, status
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.orm import Session
from sokhan.api.deps import require_bot
from sokhan.api.deps import get_current_user, require_bot
from sokhan.auth import generate_token, hash_password, token_hash, verify_password
from sokhan.config import get_settings
from sokhan.core.throttle import FailureThrottle
@@ -132,6 +133,20 @@ def token_login(payload: TokenLogin, session: Session = Depends(get_db)) -> Auth
return AuthResponse(id=user.id, email=user.email, api_token=payload.api_token)
@router.post("/logout", status_code=status.HTTP_204_NO_CONTENT)
def logout(user: User = Depends(get_current_user), session: Session = Depends(get_db)) -> Response:
"""Revoke the caller's token so it stops working everywhere.
An account has a single active token, so this signs out every client
that holds it: other browsers, API scripts and, for Telegram accounts,
the bot (which re-registers on its next request). The new token is
never returned; signing in again issues a fresh one.
"""
user.token_hash = token_hash(generate_token())
session.commit()
return Response(status_code=status.HTTP_204_NO_CONTENT)
@router.post("/telegram", response_model=AuthResponse, dependencies=[Depends(require_bot)])
def telegram_login(payload: TelegramLogin, session: Session = Depends(get_db)) -> AuthResponse:
"""Register-or-login used by the Telegram bot.
+37
View File
@@ -92,3 +92,40 @@ def test_telegram_login_is_disabled_without_a_configured_secret(client):
def test_jobs_require_token(client):
response = client.get("/jobs")
assert response.status_code == 401
def _bearer(token):
return {"Authorization": f"Bearer {token}"}
def test_logout_revokes_the_token(client):
token = client.post("/auth/register", json=REGISTER).json()["api_token"]
assert client.get("/quota", headers=_bearer(token)).status_code == 200
response = client.post("/auth/logout", headers=_bearer(token))
assert response.status_code == 204
assert client.get("/quota", headers=_bearer(token)).status_code == 401
# The revoked token is no longer a valid connect code either.
assert client.post("/auth/token-login", json={"api_token": token}).status_code == 401
def test_logout_twice_with_the_same_token_is_rejected(client):
token = client.post("/auth/register", json=REGISTER).json()["api_token"]
client.post("/auth/logout", headers=_bearer(token))
assert client.post("/auth/logout", headers=_bearer(token)).status_code == 401
def test_logout_requires_a_token(client):
assert client.post("/auth/logout").status_code == 401
def test_signing_in_after_logout_issues_a_working_token(client):
first = client.post("/auth/register", json=REGISTER).json()["api_token"]
client.post("/auth/logout", headers=_bearer(first))
second = client.post("/auth/login", json=REGISTER).json()["api_token"]
assert second != first
assert client.get("/quota", headers=_bearer(second)).status_code == 200
+12
View File
@@ -9,6 +9,10 @@ class BackendError(Exception):
pass
class AuthError(BackendError):
"""The API rejected the token (401): revoked by a logout or a newer sign-in."""
class QuotaError(BackendError):
"""The user's monthly allowance is exhausted (402, code=quota_exceeded)."""
@@ -46,6 +50,11 @@ class SokhanClient:
def _headers(self, token: str) -> dict[str, str]:
return {"Authorization": f"Bearer {token}"}
@staticmethod
def _raise_for_auth(response: httpx.Response) -> None:
if response.status_code == 401:
raise AuthError("token rejected")
def register_telegram(self, telegram_id: int, username: str | None) -> str:
response = self._client.post(
f"{self.settings.api_base_url}/auth/telegram",
@@ -65,6 +74,7 @@ class SokhanClient:
files={"file": (filename, content)},
headers=self._headers(token),
)
self._raise_for_auth(response)
if response.status_code == 402:
detail = response.json().get("detail", {})
if detail.get("code") == "file_too_long":
@@ -82,6 +92,7 @@ class SokhanClient:
f"{self.settings.api_base_url}/jobs/{job_id}",
headers=self._headers(token),
)
self._raise_for_auth(response)
if response.status_code != 200:
raise BackendError(f"job fetch failed with status {response.status_code}")
return response.json()
@@ -91,6 +102,7 @@ class SokhanClient:
f"{self.settings.api_base_url}/quota",
headers=self._headers(token),
)
self._raise_for_auth(response)
if response.status_code != 200:
raise BackendError(f"quota fetch failed with status {response.status_code}")
return response.json()
+51 -5
View File
@@ -3,6 +3,8 @@
import io
import logging
import time
from collections.abc import Callable
from typing import TypeVar
from aiogram import Bot, F, Router
from aiogram.filters import Command, CommandObject, CommandStart
@@ -11,10 +13,17 @@ from aiogram.types import (
InlineKeyboardButton,
InlineKeyboardMarkup,
Message,
User,
)
from sokhan_bot import texts
from sokhan_bot.client import BackendError, FileTooLongError, QuotaError, SokhanClient
from sokhan_bot.client import (
AuthError,
BackendError,
FileTooLongError,
QuotaError,
SokhanClient,
)
from sokhan_bot.split import split_message
from sokhan_bot.store import TokenStore
@@ -22,6 +31,8 @@ logger = logging.getLogger(__name__)
_RATE_LIMIT_SECONDS = 10.0
T = TypeVar("T")
def _job_keyboard(job_id: str, web_base_url: str) -> InlineKeyboardMarkup:
return InlineKeyboardMarkup(
@@ -82,10 +93,35 @@ class Handlers:
self.store.set(message.chat.id, token)
return token
def _authed(self, chat_id: int, user: User, call: Callable[[str], T]) -> T:
"""Run `call(token)`, re-registering once if the API revoked the token.
A web logout or a newer sign-in revokes the token cached for this
chat; without the retry every later request would fail. Raises
BackendError when the backend is unreachable or rejects again.
"""
token = self.store.get(chat_id)
if token:
try:
return call(token)
except AuthError:
logger.info("token for chat %s was revoked; re-registering", chat_id)
self.store.forget(chat_id)
token = self.client.register_telegram(user.id, user.username)
self.store.set(chat_id, token)
return call(token)
async def start(self, message: Message) -> None:
token = await self._ensure_token(message)
if not token:
return
# The cached token doubles as the connect code, so make sure it still
# works before showing it; a backend outage keeps the cached one.
try:
self._authed(message.chat.id, message.from_user, self.client.get_quota)
except BackendError:
pass
token = self.store.get(message.chat.id) or token
await message.answer(texts.WELCOME.format(connect_code=token))
async def quota(self, message: Message) -> None:
@@ -93,7 +129,7 @@ class Handlers:
if not token:
return
try:
info = self.client.get_quota(token)
info = self._authed(message.chat.id, message.from_user, self.client.get_quota)
except BackendError:
await message.answer(texts.SERVER_UNREACHABLE)
return
@@ -137,7 +173,9 @@ class Handlers:
await message.answer("شناسهٔ پردازش را بنویس، مثلاً: /track 3f2a…")
return
try:
job = self.client.get_job(token, job_id)
job = self._authed(
message.chat.id, message.from_user, lambda t: self.client.get_job(t, job_id)
)
except BackendError:
await message.answer(texts.UNKNOWN_JOB)
return
@@ -196,7 +234,11 @@ class Handlers:
return
try:
job_id = self.client.upload_audio(token, filename, content)
job_id = self._authed(
message.chat.id,
message.from_user,
lambda t: self.client.upload_audio(t, filename, content),
)
except FileTooLongError as exc:
await message.answer(
texts.FILE_TOO_LONG.format(
@@ -229,7 +271,11 @@ class Handlers:
job_id = callback.data.split(":", 1)[1]
try:
job = self.client.get_job(token, job_id)
job = self._authed(
callback.message.chat.id,
callback.from_user,
lambda t: self.client.get_job(t, job_id),
)
except BackendError:
await callback.answer(texts.UNKNOWN_JOB, show_alert=True)
return
+9 -1
View File
@@ -19,7 +19,7 @@ import time
from aiogram import Bot
from sokhan_bot import texts
from sokhan_bot.client import SokhanClient
from sokhan_bot.client import AuthError, SokhanClient
from sokhan_bot.split import split_message
from sokhan_bot.store import TokenStore
@@ -75,6 +75,14 @@ class CompletionNotifier:
try:
job = await asyncio.to_thread(self.client.get_job, token, job_id)
except AuthError:
# Revoked by a web logout or a newer sign-in. The poller has
# no Telegram user to re-register with, so it asks for /start.
logger.warning("token for chat %s was revoked; untracking job %s", chat_id, job_id)
self.store.forget(chat_id)
self.store.untrack(job_id)
await self._send(chat_id, texts.NEED_START)
continue
except Exception:
logger.exception("job fetch failed (%s); will retry", job_id)
continue
+6
View File
@@ -42,6 +42,12 @@ class TokenStore:
self._tokens[str(chat_id)] = token
self._save()
def forget(self, chat_id: int) -> None:
"""Drop a chat's token, e.g. after the API revoked it."""
with self._lock:
if self._tokens.pop(str(chat_id), None) is not None:
self._save()
def track(self, job_id: str, chat_id: int) -> None:
"""Watch a job so the notifier can push its transcript when it finishes."""
with self._lock:
+18 -1
View File
@@ -2,7 +2,7 @@
import httpx
import pytest
from sokhan_bot.client import BackendError, FileTooLongError, QuotaError, SokhanClient
from sokhan_bot.client import AuthError, BackendError, FileTooLongError, QuotaError, SokhanClient
from sokhan_bot.config import BotSettings
@@ -106,3 +106,20 @@ def test_register_telegram_sends_the_bot_secret():
with SokhanClient(settings, transport=httpx.MockTransport(handler)) as client:
assert client.register_telegram(42, None) == "tok"
assert seen["secret"] == "shared"
@pytest.mark.parametrize(
"call",
[
lambda client: client.upload_audio("tok", "voice.ogg", b"bytes"),
lambda client: client.get_job("tok", "job-1"),
lambda client: client.get_quota("tok"),
],
)
def test_revoked_token_raises_auth_error(call):
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(401, json={"detail": "invalid token"})
with _client(handler) as client:
with pytest.raises(AuthError):
call(client)
+128
View File
@@ -0,0 +1,128 @@
"""The bot recovers when the API revokes a chat's cached token (web logout)."""
import asyncio
from types import SimpleNamespace
from sokhan_bot import texts
from sokhan_bot.client import AuthError, BackendError
from sokhan_bot.handlers import Handlers
from sokhan_bot.notify import CompletionNotifier
from sokhan_bot.store import TokenStore
class FakeClient:
"""Accepts only `valid_token`; /auth/telegram hands out `fresh-<n>`."""
def __init__(self, valid_token: str) -> None:
self.valid_token = valid_token
self.registrations = 0
self.settings = SimpleNamespace(web_base_url="http://web.test")
def _check(self, token: str) -> None:
if token != self.valid_token:
raise AuthError("token rejected")
def register_telegram(self, telegram_id: int, username: str | None) -> str:
self.registrations += 1
self.valid_token = f"fresh-{self.registrations}"
return self.valid_token
def get_quota(self, token: str) -> dict:
self._check(token)
return {
"plan": "free",
"used_minutes": 1.0,
"limit_minutes": 30,
"remaining_minutes": 29.0,
"max_file_minutes": 10,
}
def get_job(self, token: str, job_id: str) -> dict:
self._check(token)
return {"status": "processing", "progress": 50.0}
class FakeMessage:
def __init__(self, chat_id: int = 42) -> None:
self.chat = SimpleNamespace(id=chat_id)
self.from_user = SimpleNamespace(id=chat_id, username="sara")
self.answers: list[str] = []
async def answer(self, text: str, **_: object) -> None:
self.answers.append(text)
def _handlers(tmp_path, cached_token: str, client: FakeClient) -> Handlers:
store = TokenStore(str(tmp_path / "store.json"))
store.set(42, cached_token)
return Handlers(client, store)
def test_quota_re_registers_once_after_the_token_was_revoked(tmp_path):
client = FakeClient(valid_token="current")
handlers = _handlers(tmp_path, "revoked", client)
message = FakeMessage()
asyncio.run(handlers.quota(message))
assert client.registrations == 1
assert handlers.store.get(42) == "fresh-1"
assert message.answers and texts.SERVER_UNREACHABLE not in message.answers
def test_a_valid_token_is_used_without_re_registering(tmp_path):
client = FakeClient(valid_token="current")
handlers = _handlers(tmp_path, "current", client)
asyncio.run(handlers.quota(FakeMessage()))
assert client.registrations == 0
assert handlers.store.get(42) == "current"
def test_start_shows_a_working_connect_code_after_revocation(tmp_path):
client = FakeClient(valid_token="current")
handlers = _handlers(tmp_path, "revoked", client)
message = FakeMessage()
asyncio.run(handlers.start(message))
assert "fresh-1" in message.answers[-1]
assert "revoked" not in message.answers[-1]
def test_backend_outage_still_reports_unreachable(tmp_path):
client = FakeClient(valid_token="current")
def unreachable(token: str) -> dict:
raise BackendError("down")
client.get_quota = unreachable
handlers = _handlers(tmp_path, "current", client)
message = FakeMessage()
asyncio.run(handlers.quota(message))
assert message.answers == [texts.SERVER_UNREACHABLE]
assert client.registrations == 0
def test_poller_untracks_and_asks_for_start_when_revoked(tmp_path):
client = FakeClient(valid_token="current")
store = TokenStore(str(tmp_path / "store.json"))
store.set(42, "revoked")
store.track("job-1", 42)
sent: list[tuple[int, str]] = []
notifier = CompletionNotifier(bot=None, client=client, store=store)
async def fake_send(chat_id: int, text: str) -> bool:
sent.append((chat_id, text))
return True
notifier._send = fake_send
asyncio.run(notifier.poll_once())
assert store.tracked() == []
assert store.get(42) is None
assert sent == [(42, texts.NEED_START)]
+12
View File
@@ -47,3 +47,15 @@ def test_legacy_token_file_is_migrated(tmp_path):
reloaded = TokenStore(str(path))
assert reloaded.get(123) == "legacy-token"
assert [job_id for job_id, _, _ in reloaded.tracked()] == ["job-x"]
def test_forget_drops_a_token_and_persists(tmp_path):
path = str(tmp_path / "store.json")
store = TokenStore(path)
store.set(42, "old-token")
store.forget(42)
store.forget(99) # unknown chats are a no-op
assert store.get(42) is None
assert TokenStore(path).get(42) is None
+5 -1
View File
@@ -17,7 +17,11 @@
"switchToEn": "English",
"switchToFa": "فارسی",
"themeToDark": "Switch to dark theme",
"themeToLight": "Switch to light theme"
"themeToLight": "Switch to light theme",
"signIn": "Sign in",
"signOut": "Sign out",
"signedInAs": "Signed in as {email}",
"signOutOf": "Sign out of {email}"
},
"landing": {
"headline": "From speech to text, in moments",
+5 -1
View File
@@ -17,7 +17,11 @@
"switchToEn": "English",
"switchToFa": "فارسی",
"themeToDark": "تم تیره",
"themeToLight": "تم روشن"
"themeToLight": "تم روشن",
"signIn": "ورود",
"signOut": "خروج",
"signedInAs": "واردشده با {email}",
"signOutOf": "خروج از حساب {email}"
},
"landing": {
"headline": "از گفتار به متن، در چند لحظه",
+9 -3
View File
@@ -1,9 +1,10 @@
"use client";
import { useState, type FormEvent } from "react";
import { useEffect, useState, type FormEvent } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "@/i18n/navigation";
import { ApiError, login, register, setToken, tokenLogin } from "@/lib/api";
import { useSession } from "@/lib/session";
type Mode = "login" | "register" | "code";
@@ -13,6 +14,12 @@ export default function LoginPage() {
const t = useTranslations("login");
const te = useTranslations("errors");
const router = useRouter();
const { ready, signedIn } = useSession();
// Already signed in: the login form has nothing to offer.
useEffect(() => {
if (ready && signedIn) router.replace("/new");
}, [ready, signedIn, router]);
const [mode, setMode] = useState<Mode>("login");
const [email, setEmail] = useState("");
@@ -71,8 +78,7 @@ export default function LoginPage() {
: mode === "register"
? await register(email.trim(), password)
: await tokenLogin(code.trim());
setToken(result.api_token);
router.push("/new");
setToken(result.api_token, result.email);
} catch (error) {
setPending(false);
if (error instanceof ApiError) {
+3 -5
View File
@@ -1,6 +1,7 @@
import { getTranslations, setRequestLocale } from "next-intl/server";
import { ArrowRight, GraduationCap, TextSearch, Voicemail, type LucideIcon } from "lucide-react";
import { Link } from "@/i18n/navigation";
import { LoginCta } from "@/components/login-cta";
const waveBars = [12, 20, 30, 22, 34, 40, 28, 16, 26, 36, 20, 30, 14, 24, 32, 18, 26, 12, 22, 16];
@@ -69,12 +70,9 @@ export default async function LandingPage({
{t("startCta")}
<ArrowRight className="h-4 w-4 rtl:-scale-x-100" aria-hidden="true" />
</Link>
<Link
href="/login"
className="inline-flex min-h-11 items-center rounded-xl border border-stone-300 bg-white px-6 text-sm font-bold text-stone-800 transition-colors hover:border-teal-700 hover:text-teal-800 focus-visible:ring-2 focus-visible:ring-teal-700 focus-visible:ring-offset-2"
>
<LoginCta className="inline-flex min-h-11 items-center rounded-xl border border-stone-300 bg-white px-6 text-sm font-bold text-stone-800 transition-colors hover:border-teal-700 hover:text-teal-800 focus-visible:ring-2 focus-visible:ring-teal-700 focus-visible:ring-offset-2">
{t("loginCta")}
</Link>
</LoginCta>
</div>
<svg
viewBox="0 0 200 48"
+16
View File
@@ -0,0 +1,16 @@
"use client";
import type { ReactNode } from "react";
import { Link } from "@/i18n/navigation";
import { useSession } from "@/lib/session";
/** The landing page's sign-in button; hidden once the visitor is signed in. */
export function LoginCta({ className, children }: { className: string; children: ReactNode }) {
const { ready, signedIn } = useSession();
if (!ready || signedIn) return null;
return (
<Link href="/login" className={className}>
{children}
</Link>
);
}
+45 -1
View File
@@ -1,15 +1,27 @@
"use client";
import { useState } from "react";
import { useLocale, useTranslations } from "next-intl";
import { AudioLines } from "lucide-react";
import { AudioLines, LogIn, LogOut } from "lucide-react";
import { Link, usePathname, useRouter } from "@/i18n/navigation";
import { ThemeToggle } from "@/components/theme-toggle";
import { logout } from "@/lib/api";
import { useSession } from "@/lib/session";
export function SiteHeader() {
const t = useTranslations("nav");
const locale = useLocale();
const pathname = usePathname();
const router = useRouter();
const { ready, signedIn, email } = useSession();
const [signingOut, setSigningOut] = useState(false);
async function handleSignOut() {
setSigningOut(true);
await logout();
setSigningOut(false);
router.replace("/login");
}
const otherLocale = locale === "fa" ? "en" : "fa";
@@ -62,6 +74,38 @@ export function SiteHeader() {
{otherLocale === "en" ? "EN" : "فا"}
</button>
<ThemeToggle />
{ready && signedIn && (
<>
{email && (
<span
className="hidden max-w-48 truncate text-sm text-stone-500 md:inline"
title={t("signedInAs", { email })}
>
{email}
</span>
)}
<button
type="button"
onClick={handleSignOut}
disabled={signingOut}
aria-label={email ? t("signOutOf", { email }) : t("signOut")}
className="inline-flex items-center gap-1.5 rounded-lg px-2 py-2 text-sm font-medium text-stone-600 transition-colors hover:bg-stone-100 hover:text-stone-900 focus-visible:ring-2 focus-visible:ring-teal-700 disabled:opacity-60 sm:px-3"
>
<LogOut className="h-4 w-4 rtl:-scale-x-100" aria-hidden="true" />
<span className="hidden sm:inline">{t("signOut")}</span>
</button>
</>
)}
{ready && !signedIn && pathname !== "/login" && (
<Link
href="/login"
className="inline-flex items-center gap-1.5 rounded-lg bg-teal-700 px-3 py-2 text-sm font-medium text-white transition-colors hover:bg-teal-600 focus-visible:ring-2 focus-visible:ring-teal-700 focus-visible:ring-offset-2"
>
<LogIn className="h-4 w-4 rtl:-scale-x-100" aria-hidden="true" />
<span className="hidden sm:inline">{t("signIn")}</span>
<span className="sr-only sm:hidden">{t("signIn")}</span>
</Link>
)}
</nav>
</div>
</header>
+38 -1
View File
@@ -5,6 +5,9 @@
const API_BASE = process.env.NEXT_PUBLIC_API_BASE || "http://localhost:8000";
export const TOKEN_STORAGE_KEY = "sokhan_token";
export const EMAIL_STORAGE_KEY = "sokhan_email";
/** Fired on this tab whenever the stored session changes (sign-in or out). */
export const SESSION_CHANGE_EVENT = "sokhan:session-change";
export type JobStatus = "queued" | "processing" | "completed" | "failed";
export type TranscriptFormat = "txt" | "srt" | "vtt" | "json" | "docx";
@@ -97,14 +100,48 @@ export function getToken(): string | null {
return window.localStorage.getItem(TOKEN_STORAGE_KEY);
}
export function setToken(token: string): void {
export function getEmail(): string | null {
if (typeof window === "undefined") return null;
return window.localStorage.getItem(EMAIL_STORAGE_KEY);
}
function notifySessionChange(): void {
window.dispatchEvent(new Event(SESSION_CHANGE_EVENT));
}
export function setToken(token: string, email?: string): void {
if (typeof window === "undefined") return;
window.localStorage.setItem(TOKEN_STORAGE_KEY, token);
if (email) window.localStorage.setItem(EMAIL_STORAGE_KEY, email);
else window.localStorage.removeItem(EMAIL_STORAGE_KEY);
notifySessionChange();
}
export function clearToken(): void {
if (typeof window === "undefined") return;
window.localStorage.removeItem(TOKEN_STORAGE_KEY);
window.localStorage.removeItem(EMAIL_STORAGE_KEY);
notifySessionChange();
}
/**
* Revoke the token on the server, then forget it locally. The local
* session is cleared even when the API is unreachable or already rejects
* the token, so signing out always works from the user's point of view.
*/
export async function logout(): Promise<void> {
const token = getToken();
if (token) {
try {
await fetch(`${API_BASE}/auth/logout`, {
method: "POST",
headers: { Authorization: `Bearer ${token}` },
});
} catch {
// Offline or API down: the local sign-out below still happens.
}
}
clearToken();
}
function redirectToLogin(): void {
+37
View File
@@ -0,0 +1,37 @@
// Reactive view of the stored session for client components. The token
// lives in localStorage (see api.ts); this hook re-renders on sign-in and
// sign-out in this tab (SESSION_CHANGE_EVENT) and in other tabs ("storage").
import { useSyncExternalStore } from "react";
import { SESSION_CHANGE_EVENT, getEmail, getToken } from "@/lib/api";
// Accounts created by the Telegram bot get a synthetic address that means
// nothing to the user, so it is not shown.
const SYNTHETIC_EMAIL_SUFFIX = "@telegram.sokhan.local";
function subscribe(onChange: () => void): () => void {
window.addEventListener("storage", onChange);
window.addEventListener(SESSION_CHANGE_EVENT, onChange);
return () => {
window.removeEventListener("storage", onChange);
window.removeEventListener(SESSION_CHANGE_EVENT, onChange);
};
}
const onServer = () => false;
export interface Session {
/** False during SSR and the first client render, before storage is readable. */
ready: boolean;
signedIn: boolean;
/** The account email, or null when unknown or a Telegram placeholder. */
email: string | null;
}
export function useSession(): Session {
const ready = useSyncExternalStore(subscribe, () => true, onServer);
const signedIn = useSyncExternalStore(subscribe, () => getToken() !== null, onServer);
const storedEmail = useSyncExternalStore(subscribe, getEmail, () => null);
const email = storedEmail && !storedEmail.endsWith(SYNTHETIC_EMAIL_SUFFIX) ? storedEmail : null;
return { ready, signedIn, email };
}