diff --git a/backend/internal/admin/auth/handler.go b/backend/internal/admin/auth/handler.go index 6a2013e..99db498 100755 --- a/backend/internal/admin/auth/handler.go +++ b/backend/internal/admin/auth/handler.go @@ -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) } diff --git a/backend/internal/admin/ui/handler.go b/backend/internal/admin/ui/handler.go index f5cb603..50dd420 100644 --- a/backend/internal/admin/ui/handler.go +++ b/backend/internal/admin/ui/handler.go @@ -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", diff --git a/backend/internal/appresult/cookie.go b/backend/internal/appresult/cookie.go new file mode 100644 index 0000000..097e58f --- /dev/null +++ b/backend/internal/appresult/cookie.go @@ -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 "" +} diff --git a/backend/internal/appresult/cookie_test.go b/backend/internal/appresult/cookie_test.go new file mode 100644 index 0000000..fae2f6f --- /dev/null +++ b/backend/internal/appresult/cookie_test.go @@ -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) + } +} diff --git a/backend/internal/appresult/middleware.go b/backend/internal/appresult/middleware.go index c9d484f..734c188 100755 --- a/backend/internal/appresult/middleware.go +++ b/backend/internal/appresult/middleware.go @@ -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) { diff --git a/backend/web/admin/assets/js/api.js b/backend/web/admin/assets/js/api.js index 239f2b7..afa2dc9 100644 --- a/backend/web/admin/assets/js/api.js +++ b/backend/web/admin/assets/js/api.js @@ -1,8 +1,10 @@ /** * API client for the bankline admin API. * - * - Sends the raw JWT access token in the Authorization header - * (the backend middleware expects the bare token, no "Bearer " prefix). + * Auth is cookie-based (HttpOnly admin_access / admin_refresh). + * Requests use credentials: "include". Authorization header is optional + * when a legacy localStorage token is still present. + * * - Unwraps the response envelope { status, message, code, data }. * - On 401 tries a one-shot refresh via POST /api/v1/admin/token, then retries. * - 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 = { get access() { return localStorage.getItem(ACCESS_KEY) || ""; @@ -50,8 +53,12 @@ return localStorage.getItem(REFRESH_KEY) || ""; }, set(pair) { - localStorage.setItem(ACCESS_KEY, pair.accessToken || ""); - localStorage.setItem(REFRESH_KEY, pair.refreshToken || ""); + if (pair && pair.accessToken) { + localStorage.setItem(ACCESS_KEY, pair.accessToken); + } + if (pair && pair.refreshToken) { + localStorage.setItem(REFRESH_KEY, pair.refreshToken); + } }, clear() { localStorage.removeItem(ACCESS_KEY); @@ -78,7 +85,6 @@ return payload.data; } if (response.ok && payload && payload.status === undefined) { - // A few endpoints (e.g. JWT middleware errors) don't use the envelope. return payload; } @@ -92,13 +98,14 @@ } async function refreshTokens() { - const refreshToken = tokens.refresh; - if (!refreshToken) return false; try { + const body = {}; + if (tokens.refresh) body.refreshToken = tokens.refresh; const response = await fetch("/api/v1/admin/token", { method: "POST", + credentials: "include", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ refreshToken }), + body: JSON.stringify(body), }); if (!response.ok) return false; const payload = await response.json(); @@ -107,7 +114,8 @@ tokens.set(pair); return true; } - return false; + // Cookie-only refresh may return a pair; accept any 200 with status true. + return !!(payload && payload.status === true); } catch (_) { return false; } @@ -147,7 +155,12 @@ let response; try { - response = await fetch(url, { method, headers, body }); + response = await fetch(url, { + method, + headers, + body, + credentials: "include", + }); } catch (_) { throw new ApiError( "Network error. Please check your connection and try again.", diff --git a/backend/web/admin/assets/js/auth.js b/backend/web/admin/assets/js/auth.js index acb92d0..3b62198 100644 --- a/backend/web/admin/assets/js/auth.js +++ b/backend/web/admin/assets/js/auth.js @@ -1,19 +1,19 @@ /** * Authentication helpers: login, logout, page guard and header profile. + * Session is stored in HttpOnly cookies by the server; localStorage is optional cache. */ (function () { "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() { - if (!Api.tokens.access) { - Api.redirectToLogin(); - return false; - } return true; } - /** Sign in and store the token pair. */ + /** Sign in; server sets HttpOnly cookies. */ async function login(loginValue, password) { const pair = await Api.post("/api/v1/admin/login", { login: loginValue, @@ -25,7 +25,12 @@ 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(); window.location.href = "/admin/login"; } diff --git a/backend/web/admin/assets/js/login.js b/backend/web/admin/assets/js/login.js index 47e9c94..514efd1 100644 --- a/backend/web/admin/assets/js/login.js +++ b/backend/web/admin/assets/js/login.js @@ -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 () { "use strict"; @@ -7,10 +10,10 @@ document.addEventListener("DOMContentLoaded", () => { if (document.body.dataset.page !== "login") return; - // Already signed in? Go straight to the dashboard. - if (Api.tokens.access) { - window.location.href = "/admin"; - return; + // Drop any legacy localStorage session. Auth is HttpOnly cookies + server + // AdminGuestOnly; a leftover access token must not auto-navigate to /admin. + if (window.Api && Api.tokens) { + Api.tokens.clear(); } const form = document.getElementById("login-form");