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" "net/http"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"time" "time"
"github.com/minio/minio-go/v7" "github.com/minio/minio-go/v7"
@@ -27,8 +28,9 @@ import (
) )
const ( const (
loginURL = "/login" loginURL = "/login"
tokenURL = "/token" logoutURL = "/logout"
tokenURL = "/token"
getProfileURL = "/get-profile" getProfileURL = "/get-profile"
fileUploadURL = "/file" fileUploadURL = "/file"
@@ -49,11 +51,11 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
func (h *handler) Register(router *gin.RouterGroup) { func (h *handler) Register(router *gin.RouterGroup) {
router.POST(loginURL, h.login) router.POST(loginURL, h.login)
router.POST(logoutURL, h.logout)
router.GET(getProfileURL, appresult.JwtTokenCheck(), h.getProfile) router.GET(getProfileURL, appresult.JwtTokenCheck(), h.getProfile)
router.POST(fileUploadURL, appresult.JwtTokenCheck(), h.fileUpload) router.POST(fileUploadURL, appresult.JwtTokenCheck(), h.fileUpload)
router.DELETE(fileRemoveURL, appresult.JwtTokenCheck(), h.DeleteObject) router.DELETE(fileRemoveURL, appresult.JwtTokenCheck(), h.DeleteObject)
router.POST(tokenURL, h.token) router.POST(tokenURL, h.token)
} }
// ================================================================================= // =================================================================================
@@ -100,11 +102,20 @@ func (h *handler) login(c *gin.Context) {
return return
} }
appresult.SetAuthCookies(c, newTokenPair["accessToken"], newTokenPair["refreshToken"])
successResult := appresult.Success successResult := appresult.Success
successResult.Data = newTokenPair successResult.Data = newTokenPair
c.JSON(http.StatusOK, successResult) 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 // getProfile godoc
@@ -292,47 +303,57 @@ func DeleteItemInMinio(ctx context.Context, minioClient *minio.Client, value str
// @Success 200 {string} string true "token" // @Success 200 {string} string true "token"
// @Router /admin/token [post] // @Router /admin/token [post]
func (h *handler) token(c *gin.Context) { func (h *handler) token(c *gin.Context) {
var ( var tokenReq TokenReqBody
err error
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) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return 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 { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
} }
return []byte(utils.SecretKey), nil 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))) res, err := h.repository.CheckAdmin(context.TODO(), int(claims["id"].(float64)))
if err != nil { if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrInternalServer) c.JSON(http.StatusBadRequest, appresult.ErrInternalServer)
return return
} }
if int(claims["id"].(float64)) == res.Id { 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
}
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return 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 package ui
import ( import (
"bankline/internal/appresult"
"net/http" "net/http"
"strings" "strings"
@@ -34,14 +35,17 @@ func Register(router *gin.Engine) {
admin := router.Group("/admin") 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{ c.HTML(http.StatusOK, "pages/login", gin.H{
"Title": "Login", "Title": "Login",
"Page": "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{ c.HTML(http.StatusOK, "pages/dashboard", gin.H{
"Title": "Dashboard", "Title": "Dashboard",
"Page": "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{ c.HTML(http.StatusOK, "pages/settings", gin.H{
"Title": "Settings", "Title": "Settings",
"Page": "settings", "Page": "settings",
@@ -60,7 +64,7 @@ func Register(router *gin.Engine) {
for _, res := range resources { for _, res := range resources {
res := res 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{ c.HTML(http.StatusOK, "pages/list", gin.H{
"Title": res.Title, "Title": res.Title,
"Page": "list", "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{ c.HTML(http.StatusOK, "pages/form", gin.H{
"Title": "New — " + res.Title, "Title": "New — " + res.Title,
"Page": "form", "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{ c.HTML(http.StatusOK, "pages/form", gin.H{
"Title": "Edit — " + res.Title, "Title": "Edit — " + res.Title,
"Page": "form", "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 ( import (
"bankline/internal/config" "bankline/internal/config"
"fmt" "fmt"
"net/http"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt" "github.com/golang-jwt/jwt"
"net/http"
) )
type UnsignedResponse struct { type UnsignedResponse struct {
@@ -25,34 +26,79 @@ func respondWithError(c *gin.Context, code int, message interface{}) {
c.AbortWithStatusJSON(code, gin.H{"error": message}) 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 { func JwtTokenCheck() gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
token := c.GetHeader("Authorization") if AccessTokenFromRequest(c) == "" {
if token == "" {
respondWithError(c, 403, "Authorization header is missing") respondWithError(c, 403, "Authorization header is missing")
return return
} }
cfg := config.GetConfig() claims, ok := adminClaimsFromRequest(c)
claims, err := TokenClaims(token, cfg.JwtKey) if !ok {
if err != nil {
respondWithError(c, 401, "Token is expired") respondWithError(c, 401, "Token is expired")
return return
} }
isAdmin := claims["admin"].(bool)
if isAdmin == false {
respondWithError(c, 403, "Unauthorized")
return
}
c.Set("id", fmt.Sprint(claims["id"])) c.Set("id", fmt.Sprint(claims["id"]))
c.Next() 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) { func TokenClaims(token, secretKey string) (jwt.MapClaims, error) {
decoded, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) { decoded, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {

View File

@@ -1,8 +1,10 @@
/** /**
* API client for the bankline admin API. * API client for the bankline admin API.
* *
* - Sends the raw JWT access token in the Authorization header * Auth is cookie-based (HttpOnly admin_access / admin_refresh).
* (the backend middleware expects the bare token, no "Bearer " prefix). * Requests use credentials: "include". Authorization header is optional
* when a legacy localStorage token is still present.
*
* - Unwraps the response envelope { status, message, code, data }. * - Unwraps the response envelope { status, message, code, data }.
* - On 401 tries a one-shot refresh via POST /api/v1/admin/token, then retries. * - On 401 tries a one-shot refresh via POST /api/v1/admin/token, then retries.
* - Throws ApiError with a friendly, human-readable message. * - Throws ApiError with a friendly, human-readable message.
@@ -42,6 +44,7 @@
} }
} }
// Legacy localStorage tokens (optional). Session source of truth is HttpOnly cookies.
const tokens = { const tokens = {
get access() { get access() {
return localStorage.getItem(ACCESS_KEY) || ""; return localStorage.getItem(ACCESS_KEY) || "";
@@ -50,8 +53,12 @@
return localStorage.getItem(REFRESH_KEY) || ""; return localStorage.getItem(REFRESH_KEY) || "";
}, },
set(pair) { set(pair) {
localStorage.setItem(ACCESS_KEY, pair.accessToken || ""); if (pair && pair.accessToken) {
localStorage.setItem(REFRESH_KEY, pair.refreshToken || ""); localStorage.setItem(ACCESS_KEY, pair.accessToken);
}
if (pair && pair.refreshToken) {
localStorage.setItem(REFRESH_KEY, pair.refreshToken);
}
}, },
clear() { clear() {
localStorage.removeItem(ACCESS_KEY); localStorage.removeItem(ACCESS_KEY);
@@ -78,7 +85,6 @@
return payload.data; return payload.data;
} }
if (response.ok && payload && payload.status === undefined) { if (response.ok && payload && payload.status === undefined) {
// A few endpoints (e.g. JWT middleware errors) don't use the envelope.
return payload; return payload;
} }
@@ -92,13 +98,14 @@
} }
async function refreshTokens() { async function refreshTokens() {
const refreshToken = tokens.refresh;
if (!refreshToken) return false;
try { try {
const body = {};
if (tokens.refresh) body.refreshToken = tokens.refresh;
const response = await fetch("/api/v1/admin/token", { const response = await fetch("/api/v1/admin/token", {
method: "POST", method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refreshToken }), body: JSON.stringify(body),
}); });
if (!response.ok) return false; if (!response.ok) return false;
const payload = await response.json(); const payload = await response.json();
@@ -107,7 +114,8 @@
tokens.set(pair); tokens.set(pair);
return true; return true;
} }
return false; // Cookie-only refresh may return a pair; accept any 200 with status true.
return !!(payload && payload.status === true);
} catch (_) { } catch (_) {
return false; return false;
} }
@@ -147,7 +155,12 @@
let response; let response;
try { try {
response = await fetch(url, { method, headers, body }); response = await fetch(url, {
method,
headers,
body,
credentials: "include",
});
} catch (_) { } catch (_) {
throw new ApiError( throw new ApiError(
"Network error. Please check your connection and try again.", "Network error. Please check your connection and try again.",

View File

@@ -1,19 +1,19 @@
/** /**
* Authentication helpers: login, logout, page guard and header profile. * Authentication helpers: login, logout, page guard and header profile.
* Session is stored in HttpOnly cookies by the server; localStorage is optional cache.
*/ */
(function () { (function () {
"use strict"; "use strict";
/** Redirect to the login page when no access token is stored. */ /**
* Page shells are already gated by AdminPageAuth middleware.
* Keep a soft client check for pages that still call this.
*/
function requireAuth() { function requireAuth() {
if (!Api.tokens.access) {
Api.redirectToLogin();
return false;
}
return true; return true;
} }
/** Sign in and store the token pair. */ /** Sign in; server sets HttpOnly cookies. */
async function login(loginValue, password) { async function login(loginValue, password) {
const pair = await Api.post("/api/v1/admin/login", { const pair = await Api.post("/api/v1/admin/login", {
login: loginValue, login: loginValue,
@@ -25,7 +25,12 @@
Api.tokens.set(pair); Api.tokens.set(pair);
} }
function logout() { async function logout() {
try {
await Api.post("/api/v1/admin/logout", {});
} catch (_) {
/* still clear local state and leave */
}
Api.tokens.clear(); Api.tokens.clear();
window.location.href = "/admin/login"; window.location.href = "/admin/login";
} }

View File

@@ -1,5 +1,8 @@
/** /**
* Login page: submit credentials, store the token pair and redirect. * Login page: submit credentials; server sets cookies and we redirect.
*
* Do not bounce to /admin based on localStorage. Stale client tokens caused a
* reload loop with cookie-gated AdminPageAuth (login → /admin → login).
*/ */
(function () { (function () {
"use strict"; "use strict";
@@ -7,10 +10,10 @@
document.addEventListener("DOMContentLoaded", () => { document.addEventListener("DOMContentLoaded", () => {
if (document.body.dataset.page !== "login") return; if (document.body.dataset.page !== "login") return;
// Already signed in? Go straight to the dashboard. // Drop any legacy localStorage session. Auth is HttpOnly cookies + server
if (Api.tokens.access) { // AdminGuestOnly; a leftover access token must not auto-navigate to /admin.
window.location.href = "/admin"; if (window.Api && Api.tokens) {
return; Api.tokens.clear();
} }
const form = document.getElementById("login-form"); const form = document.getElementById("login-form");