Files
main-tbbank/backend/internal/appresult/middleware.go
GuwandykA 5f2e2f44ca 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>
2026-08-07 11:20:22 +05:00

125 lines
2.7 KiB
Go
Executable File

package appresult
import (
"bankline/internal/config"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
)
type UnsignedResponse struct {
Message interface{} `json:"message"`
}
type appHandler func(w http.ResponseWriter, r *http.Request) error
func HeaderContentTypeJson() (string, string) {
return "Content-Type", "application/json"
}
func AccessControlAllow() (string, string) {
return "Access-Control-Allow-Origin", "*"
}
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) {
if AccessTokenFromRequest(c) == "" {
respondWithError(c, 403, "Authorization header is missing")
return
}
claims, ok := adminClaimsFromRequest(c)
if !ok {
respondWithError(c, 401, "Token is expired")
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) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(secretKey), nil
})
if err != nil {
fmt.Println("err", err)
return nil, err
}
claims, ok := decoded.Claims.(jwt.MapClaims)
if !ok {
// TODO tokenin omrini test etmeli
return nil, ErrInternalServer
}
return claims, nil
}