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

@@ -15,6 +15,7 @@ import (
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/minio/minio-go/v7"
@@ -27,8 +28,9 @@ import (
)
const (
loginURL = "/login"
tokenURL = "/token"
loginURL = "/login"
logoutURL = "/logout"
tokenURL = "/token"
getProfileURL = "/get-profile"
fileUploadURL = "/file"
@@ -49,11 +51,11 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
func (h *handler) Register(router *gin.RouterGroup) {
router.POST(loginURL, h.login)
router.POST(logoutURL, h.logout)
router.GET(getProfileURL, appresult.JwtTokenCheck(), h.getProfile)
router.POST(fileUploadURL, appresult.JwtTokenCheck(), h.fileUpload)
router.DELETE(fileRemoveURL, appresult.JwtTokenCheck(), h.DeleteObject)
router.POST(tokenURL, h.token)
}
// =================================================================================
@@ -100,11 +102,20 @@ func (h *handler) login(c *gin.Context) {
return
}
appresult.SetAuthCookies(c, newTokenPair["accessToken"], newTokenPair["refreshToken"])
successResult := appresult.Success
successResult.Data = newTokenPair
c.JSON(http.StatusOK, successResult)
return
}
// logout clears HttpOnly auth cookies.
func (h *handler) logout(c *gin.Context) {
appresult.ClearAuthCookies(c)
successResult := appresult.Success
successResult.Data = ""
c.JSON(http.StatusOK, successResult)
}
// getProfile godoc
@@ -292,47 +303,57 @@ func DeleteItemInMinio(ctx context.Context, minioClient *minio.Client, value str
// @Success 200 {string} string true "token"
// @Router /admin/token [post]
func (h *handler) token(c *gin.Context) {
var (
err error
tokenReq TokenReqBody
)
var tokenReq TokenReqBody
if err = c.ShouldBindJSON(&tokenReq); err != nil {
// Body is optional when refresh token is in HttpOnly cookie.
_ = c.ShouldBindJSON(&tokenReq)
refresh := strings.TrimSpace(tokenReq.RefreshToken)
if refresh == "" {
refresh = appresult.RefreshTokenFromCookie(c)
}
if refresh == "" {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
token, err := jwt.Parse(tokenReq.RefreshToken, func(token *jwt.Token) (interface{}, error) {
token, err := jwt.Parse(refresh, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(utils.SecretKey), nil
})
if err != nil || token == nil || !token.Valid {
appresult.ClearAuthCookies(c)
c.JSON(http.StatusUnauthorized, appresult.ErrNotAcceptable)
return
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
c.JSON(http.StatusUnauthorized, appresult.ErrNotAcceptable)
return
}
res, err := h.repository.CheckAdmin(context.TODO(), int(claims["id"].(float64)))
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrInternalServer)
return
}
res, err := h.repository.CheckAdmin(context.TODO(), int(claims["id"].(float64)))
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrInternalServer)
return
}
if int(claims["id"].(float64)) == res.Id {
newTokenPair, err := utils.GenerateTokenPair(int(claims["id"].(float64)))
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
}
successResult := appresult.Success
successResult.Data = newTokenPair
c.JSON(http.StatusOK, successResult)
return
}
if int(claims["id"].(float64)) != res.Id {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
return
newTokenPair, err := utils.GenerateTokenPair(int(claims["id"].(float64)))
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
}
appresult.SetAuthCookies(c, newTokenPair["accessToken"], newTokenPair["refreshToken"])
successResult := appresult.Success
successResult.Data = newTokenPair
c.JSON(http.StatusOK, successResult)
}

View File

@@ -4,6 +4,7 @@
package ui
import (
"bankline/internal/appresult"
"net/http"
"strings"
@@ -34,14 +35,17 @@ func Register(router *gin.Engine) {
admin := router.Group("/admin")
admin.GET("/login", func(c *gin.Context) {
admin.GET("/login", appresult.AdminGuestOnly(), func(c *gin.Context) {
c.HTML(http.StatusOK, "pages/login", gin.H{
"Title": "Login",
"Page": "login",
})
})
admin.GET("", func(c *gin.Context) {
authed := admin.Group("")
authed.Use(appresult.AdminPageAuth())
authed.GET("", func(c *gin.Context) {
c.HTML(http.StatusOK, "pages/dashboard", gin.H{
"Title": "Dashboard",
"Page": "dashboard",
@@ -49,7 +53,7 @@ func Register(router *gin.Engine) {
})
})
admin.GET("/settings", func(c *gin.Context) {
authed.GET("/settings", func(c *gin.Context) {
c.HTML(http.StatusOK, "pages/settings", gin.H{
"Title": "Settings",
"Page": "settings",
@@ -60,7 +64,7 @@ func Register(router *gin.Engine) {
for _, res := range resources {
res := res
admin.GET("/"+res.Slug, func(c *gin.Context) {
authed.GET("/"+res.Slug, func(c *gin.Context) {
c.HTML(http.StatusOK, "pages/list", gin.H{
"Title": res.Title,
"Page": "list",
@@ -69,7 +73,7 @@ func Register(router *gin.Engine) {
})
})
admin.GET("/"+res.Slug+"/new", func(c *gin.Context) {
authed.GET("/"+res.Slug+"/new", func(c *gin.Context) {
c.HTML(http.StatusOK, "pages/form", gin.H{
"Title": "New — " + res.Title,
"Page": "form",
@@ -79,7 +83,7 @@ func Register(router *gin.Engine) {
})
})
admin.GET("/"+res.Slug+"/:id/edit", func(c *gin.Context) {
authed.GET("/"+res.Slug+"/:id/edit", func(c *gin.Context) {
c.HTML(http.StatusOK, "pages/form", gin.H{
"Title": "Edit — " + res.Title,
"Page": "form",

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