mirror of
https://github.com/MengMengCode/VoCat.git
synced 2026-08-13 03:13:43 +08:00
fix: redirect expired sessions to login
This commit is contained in:
@@ -260,8 +260,7 @@ func (s *Server) handleSession(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
session, csrfToken, err := s.auth.CSRFToken(r.Context(), sessionToken, existingCSRF)
|
||||
if errors.Is(err, auth.ErrUnauthorized) {
|
||||
s.clearAuthCookies(w)
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "authentication is required")
|
||||
s.authenticationRequired(w, r)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
@@ -296,8 +295,7 @@ func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
|
||||
if _, err := s.auth.ValidateCSRF(r.Context(), sessionToken, csrfToken); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, auth.ErrUnauthorized):
|
||||
s.clearAuthCookies(w)
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "authentication is required")
|
||||
s.authenticationRequired(w, r)
|
||||
case errors.Is(err, auth.ErrInvalidCSRF):
|
||||
writeError(w, http.StatusForbidden, "invalid_csrf", "CSRF validation failed")
|
||||
default:
|
||||
@@ -346,8 +344,7 @@ func (s *Server) handleAPI(w http.ResponseWriter, r *http.Request) {
|
||||
if _, err := s.auth.ValidateCSRF(r.Context(), sessionToken, csrfToken); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, auth.ErrUnauthorized):
|
||||
s.clearAuthCookies(w)
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "authentication is required")
|
||||
s.authenticationRequired(w, r)
|
||||
case errors.Is(err, auth.ErrInvalidCSRF):
|
||||
writeError(w, http.StatusForbidden, "invalid_csrf", "CSRF validation failed")
|
||||
default:
|
||||
@@ -419,7 +416,7 @@ func (s *Server) decodeJSON(w http.ResponseWriter, r *http.Request, destination
|
||||
func (s *Server) sessionToken(w http.ResponseWriter, r *http.Request) (string, bool) {
|
||||
cookie, err := r.Cookie(sessionCookieName)
|
||||
if err != nil || cookie.Value == "" {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "authentication is required")
|
||||
s.authenticationRequired(w, r)
|
||||
return "", false
|
||||
}
|
||||
return cookie.Value, true
|
||||
@@ -432,8 +429,7 @@ func (s *Server) requireAuthenticated(w http.ResponseWriter, r *http.Request) bo
|
||||
}
|
||||
if _, err := s.auth.Authenticate(r.Context(), sessionToken); err != nil {
|
||||
if errors.Is(err, auth.ErrUnauthorized) {
|
||||
s.clearAuthCookies(w)
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "authentication is required")
|
||||
s.authenticationRequired(w, r)
|
||||
} else {
|
||||
s.logger.Error("request authentication failed", "error", err)
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "an internal error occurred")
|
||||
@@ -443,6 +439,21 @@ func (s *Server) requireAuthenticated(w http.ResponseWriter, r *http.Request) bo
|
||||
return true
|
||||
}
|
||||
|
||||
// authenticationRequired preserves JSON semantics for API clients while
|
||||
// making a direct browser navigation land on the login screen instead of a
|
||||
// raw {"error":...} document. Frontend fetches explicitly request JSON and
|
||||
// are handled by the shared vocat:unauthorized event.
|
||||
func (s *Server) authenticationRequired(w http.ResponseWriter, r *http.Request) {
|
||||
s.clearAuthCookies(w)
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if (r.Method == http.MethodGet || r.Method == http.MethodHead) &&
|
||||
strings.Contains(strings.ToLower(r.Header.Get("Accept")), "text/html") {
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "authentication is required")
|
||||
}
|
||||
|
||||
func (s *Server) validateDoubleSubmitCSRF(w http.ResponseWriter, r *http.Request) (string, bool) {
|
||||
headerToken := r.Header.Get(csrfHeaderName)
|
||||
cookie, err := r.Cookie(csrfCookieName)
|
||||
|
||||
@@ -241,6 +241,30 @@ func TestUnifiedAPIErrors(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnauthenticatedBrowserNavigationRedirectsToLogin(t *testing.T) {
|
||||
app := newTestApplication(t)
|
||||
client := *app.client
|
||||
client.CheckRedirect = func(_ *http.Request, _ []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
}
|
||||
request, err := http.NewRequest(http.MethodGet, app.server.URL+"/api/devices", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request.Header.Set("Accept", "text/html,application/xhtml+xml")
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusSeeOther {
|
||||
t.Fatalf("navigation status = %d", response.StatusCode)
|
||||
}
|
||||
if location := response.Header.Get("Location"); location != "/login" {
|
||||
t.Fatalf("navigation location = %q", location)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewRequiresIndex(t *testing.T) {
|
||||
database, err := store.Open(context.Background(), ":memory:")
|
||||
if err != nil {
|
||||
|
||||
+2
-1
@@ -45,7 +45,8 @@ function RequireAuth({ children }: { children: ReactElement }) {
|
||||
const location = useLocation();
|
||||
if (!ready) return <LoadingScreen />;
|
||||
if (!isAuthenticated) {
|
||||
return <Navigate to={`/login?redirect=${encodeURIComponent(location.pathname)}`} replace />;
|
||||
const redirect = `${location.pathname}${location.search}${location.hash}`;
|
||||
return <Navigate to={`/login?redirect=${encodeURIComponent(redirect)}`} replace />;
|
||||
}
|
||||
return children;
|
||||
}
|
||||
|
||||
+17
-2
@@ -9,6 +9,18 @@ import { tl } from "./lib/i18n";
|
||||
|
||||
const CSRF_KEY = "vocat.csrf";
|
||||
|
||||
// Authenticated pages and same-origin plugin frames share this signal. Clear
|
||||
// the mutation token immediately so a revoked session cannot leave stale auth
|
||||
// state behind in the browser.
|
||||
export function notifyUnauthorized() {
|
||||
try {
|
||||
sessionStorage.removeItem(CSRF_KEY);
|
||||
} catch {
|
||||
/* ignore unavailable storage */
|
||||
}
|
||||
window.dispatchEvent(new Event("vocat:unauthorized"));
|
||||
}
|
||||
|
||||
function isMutation(method: string) {
|
||||
return !["GET", "HEAD", "OPTIONS"].includes(method.toUpperCase());
|
||||
}
|
||||
@@ -94,14 +106,17 @@ export async function api<T>(path: string, options: RequestOptions = {}): Promis
|
||||
: JSON.stringify(snakeize(options.body)),
|
||||
});
|
||||
|
||||
if (options.raw) return response as T;
|
||||
if (options.raw) {
|
||||
if (response.status === 401) notifyUnauthorized();
|
||||
return response as T;
|
||||
}
|
||||
const contentType = response.headers.get("content-type") || "";
|
||||
const payload = contentType.includes("application/json")
|
||||
? await response.json()
|
||||
: { message: await response.text() };
|
||||
const normalized = camelize<Record<string, unknown>>(payload);
|
||||
if (!response.ok) {
|
||||
if (response.status === 401) window.dispatchEvent(new Event("vocat:unauthorized"));
|
||||
if (response.status === 401) notifyUnauthorized();
|
||||
const nested = normalized.error;
|
||||
const detail = nested && typeof nested === "object"
|
||||
? {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { message } from "../ui";
|
||||
import type { DeviceDetail, DeviceModem, ModemPnn } from "./types";
|
||||
import { tl } from "../../lib/i18n";
|
||||
import { lookupCarrier } from "../../lib/carrier";
|
||||
import { notifyUnauthorized } from "../../api";
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* Lifecycle / status helpers (ported from the VoHive reference).
|
||||
@@ -283,6 +284,7 @@ export async function readEventStream(
|
||||
credentials: "include",
|
||||
signal: handlers.signal,
|
||||
});
|
||||
if (response.status === 401) notifyUnauthorized();
|
||||
if (!response.ok) throw new Error((await response.text()) || `HTTP ${response.status}`);
|
||||
if (!response.body) throw new Error("No stream body");
|
||||
|
||||
|
||||
@@ -271,9 +271,12 @@ export default function SettingsPage() {
|
||||
if (!confirmed) return;
|
||||
setApplyingUpdate(true);
|
||||
try {
|
||||
const data = await api<{ message?: string }>("/system/update/apply", { method: "POST", body: {} });
|
||||
const data = await api<{ message?: string; reauthenticationRequired?: boolean }>("/system/update/apply", { method: "POST", body: {} });
|
||||
message.success(data?.message || t("正在更新..."));
|
||||
window.setTimeout(() => window.location.reload(), 5000);
|
||||
window.setTimeout(() => {
|
||||
if (data?.reauthenticationRequired) window.location.replace("/login");
|
||||
else window.location.reload();
|
||||
}, 1500);
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : t("应用更新失败"));
|
||||
} finally {
|
||||
|
||||
@@ -62,6 +62,15 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const unauthorized = () => {
|
||||
setUser(null);
|
||||
setReady(true);
|
||||
};
|
||||
window.addEventListener("vocat:unauthorized", unauthorized);
|
||||
return () => window.removeEventListener("vocat:unauthorized", unauthorized);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
}, [refresh]);
|
||||
|
||||
Reference in New Issue
Block a user