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,68 @@
package appresult
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
const (
AccessCookieName = "admin_access"
RefreshCookieName = "admin_refresh"
accessMaxAge = 60 * 60 // 1 hour (matches JWT exp)
refreshMaxAge = 60 * 60 * 24 * 30 // 30 days
)
func isSecureRequest(c *gin.Context) bool {
if c.Request.TLS != nil {
return true
}
return strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https")
}
// SetAuthCookies stores JWT pair in HttpOnly cookies (readable by server middleware).
func SetAuthCookies(c *gin.Context, accessToken, refreshToken string) {
secure := isSecureRequest(c)
c.SetSameSite(http.SameSiteLaxMode)
c.SetCookie(AccessCookieName, accessToken, accessMaxAge, "/", "", secure, true)
c.SetCookie(RefreshCookieName, refreshToken, refreshMaxAge, "/", "", secure, true)
}
// ClearAuthCookies removes admin auth cookies.
// Both Secure and non-Secure variants are cleared so a cookie set behind TLS
// is still removed if this request is missing X-Forwarded-Proto.
func ClearAuthCookies(c *gin.Context) {
c.SetSameSite(http.SameSiteLaxMode)
for _, secure := range []bool{true, false} {
c.SetCookie(AccessCookieName, "", -1, "/", "", secure, true)
c.SetCookie(RefreshCookieName, "", -1, "/", "", secure, true)
}
}
// AccessTokenFromRequest prefers Authorization header, then admin_access cookie.
func AccessTokenFromRequest(c *gin.Context) string {
if token := strings.TrimSpace(c.GetHeader("Authorization")); token != "" {
return stripBearer(token)
}
if token, err := c.Cookie(AccessCookieName); err == nil {
return strings.TrimSpace(token)
}
return ""
}
func stripBearer(token string) string {
if len(token) > 7 && strings.EqualFold(token[:7], "Bearer ") {
return strings.TrimSpace(token[7:])
}
return token
}
// RefreshTokenFromCookie reads the HttpOnly refresh cookie.
func RefreshTokenFromCookie(c *gin.Context) string {
if token, err := c.Cookie(RefreshCookieName); err == nil {
return strings.TrimSpace(token)
}
return ""
}

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)
}
}

View File

@@ -3,9 +3,10 @@ package appresult
import (
"bankline/internal/config"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
"net/http"
)
type UnsignedResponse struct {
@@ -25,34 +26,79 @@ func respondWithError(c *gin.Context, code int, message interface{}) {
c.AbortWithStatusJSON(code, gin.H{"error": message})
}
// adminClaimsFromRequest returns admin JWT claims or ok=false.
// Invalid/expired tokens clear auth cookies so GuestOnly and PageAuth agree.
func adminClaimsFromRequest(c *gin.Context) (jwt.MapClaims, bool) {
token := AccessTokenFromRequest(c)
if token == "" {
return nil, false
}
cfg := config.GetConfig()
claims, err := TokenClaims(token, cfg.JwtKey)
if err != nil {
ClearAuthCookies(c)
return nil, false
}
isAdmin, _ := claims["admin"].(bool)
if !isAdmin {
ClearAuthCookies(c)
return nil, false
}
return claims, true
}
func JwtTokenCheck() gin.HandlerFunc {
return func(c *gin.Context) {
token := c.GetHeader("Authorization")
if token == "" {
if AccessTokenFromRequest(c) == "" {
respondWithError(c, 403, "Authorization header is missing")
return
}
cfg := config.GetConfig()
claims, err := TokenClaims(token, cfg.JwtKey)
if err != nil {
claims, ok := adminClaimsFromRequest(c)
if !ok {
respondWithError(c, 401, "Token is expired")
return
}
isAdmin := claims["admin"].(bool)
if isAdmin == false {
respondWithError(c, 403, "Unauthorized")
return
}
c.Set("id", fmt.Sprint(claims["id"]))
c.Next()
}
}
// AdminPageAuth redirects unauthenticated browser requests to /admin/login.
func AdminPageAuth() gin.HandlerFunc {
return func(c *gin.Context) {
claims, ok := adminClaimsFromRequest(c)
if !ok {
ClearAuthCookies(c)
c.Redirect(http.StatusFound, "/admin/login")
c.Abort()
return
}
c.Set("id", fmt.Sprint(claims["id"]))
c.Next()
}
}
// AdminGuestOnly redirects already-authenticated users away from the login page.
func AdminGuestOnly() gin.HandlerFunc {
return func(c *gin.Context) {
claims, ok := adminClaimsFromRequest(c)
if !ok {
c.Next()
return
}
c.Set("id", fmt.Sprint(claims["id"]))
c.Redirect(http.StatusFound, "/admin")
c.Abort()
}
}
func TokenClaims(token, secretKey string) (jwt.MapClaims, error) {
decoded, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {