Fix admin login reload loop from stale localStorage tokens.

Clear client tokens on the login page, gate admin pages with shared cookie JWT checks, and clear Secure cookies reliably behind the proxy.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-08-07 11:20:22 +05:00
parent cde790c690
commit 5f2e2f44ca
8 changed files with 324 additions and 72 deletions

View File

@@ -0,0 +1,92 @@
package appresult
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
func TestStripBearer(t *testing.T) {
tests := []struct {
in, want string
}{
{"raw.jwt.token", "raw.jwt.token"},
{"Bearer raw.jwt.token", "raw.jwt.token"},
{"bearer raw.jwt.token", "raw.jwt.token"},
{"Bearer spaced", "spaced"},
{"", ""},
}
for _, tt := range tests {
if got := stripBearer(tt.in); got != tt.want {
t.Fatalf("stripBearer(%q)=%q want %q", tt.in, got, tt.want)
}
}
}
func TestAccessTokenFromRequest(t *testing.T) {
gin.SetMode(gin.TestMode)
t.Run("authorization header wins and strips bearer", func(t *testing.T) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
c.Request.Header.Set("Authorization", "Bearer header.token")
c.Request.AddCookie(&http.Cookie{Name: AccessCookieName, Value: "cookie.token"})
got := AccessTokenFromRequest(c)
if got != "header.token" {
t.Fatalf("got %q want header.token", got)
}
})
t.Run("falls back to cookie", func(t *testing.T) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
c.Request.AddCookie(&http.Cookie{Name: AccessCookieName, Value: " cookie.token "})
got := AccessTokenFromRequest(c)
if got != "cookie.token" {
t.Fatalf("got %q want cookie.token", got)
}
})
t.Run("empty when missing", func(t *testing.T) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
if got := AccessTokenFromRequest(c); got != "" {
t.Fatalf("got %q want empty", got)
}
})
}
func TestClearAuthCookiesSetsBothSecureVariants(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
ClearAuthCookies(c)
cookies := w.Result().Cookies()
var accessSecure, accessInsecure, refreshSecure, refreshInsecure bool
for _, cookie := range cookies {
switch {
case cookie.Name == AccessCookieName && cookie.Secure && cookie.MaxAge < 0:
accessSecure = true
case cookie.Name == AccessCookieName && !cookie.Secure && cookie.MaxAge < 0:
accessInsecure = true
case cookie.Name == RefreshCookieName && cookie.Secure && cookie.MaxAge < 0:
refreshSecure = true
case cookie.Name == RefreshCookieName && !cookie.Secure && cookie.MaxAge < 0:
refreshInsecure = true
}
}
if !accessSecure || !accessInsecure || !refreshSecure || !refreshInsecure {
t.Fatalf("expected secure+insecure clears for both cookies, got %#v", cookies)
}
}