Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
refactor: refactor and simplify cookies
Kyle Mendellc70523aa346a
diff --git a/backend/internal/api/auth_handler.go b/backend/internal/api/auth_handler.goindex c81a02a5a..b2e4c4481 100644--- a/backend/internal/api/auth_handler.go+++ b/backend/internal/api/auth_handler.go@@ -9,6 +9,7 @@ import ("github.com/ofkm/arcane-backend/internal/dto""github.com/ofkm/arcane-backend/internal/middleware""github.com/ofkm/arcane-backend/internal/services"+ "github.com/ofkm/arcane-backend/internal/utils/cookie")type AuthHandler struct {@@ -30,117 +31,27 @@ func NewAuthHandler(group *gin.RouterGroup, userService *services.UserService, a}}-type LoginRequest struct {- Username string `json:"username" binding:"required"`- Password string `json:"password" binding:"required"`-}--type LoginResponse struct {- Success bool `json:"success"`- Token string `json:"token,omitempty"`- RefreshToken string `json:"refreshToken,omitempty"`- ExpiresAt time.Time `json:"expiresAt,omitempty"`- User *dto.UserResponseDto `json:"user,omitempty"`- Error string `json:"error,omitempty"`- RequirePasswordChange bool `json:"requirePasswordChange,omitempty"`-}--type RefreshRequest struct {- RefreshToken string `json:"refreshToken" binding:"required"`-}--type OidcLoginRequest struct {- Code string `json:"code" binding:"required"`- State string `json:"state" binding:"required"`-}--type PasswordChangeRequest struct {- CurrentPassword string `json:"currentPassword"`- NewPassword string `json:"newPassword" binding:"required"`-}-func (h *AuthHandler) Login(c *gin.Context) {- var req LoginRequest+ var req dto.LoginRequestif err := c.ShouldBindJSON(&req); err != nil {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "data": gin.H{"error": "Invalid request format"},- })+ c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": "Invalid request format"}})return}localAuthEnabled, err := h.authService.IsLocalAuthEnabled(c.Request.Context())if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "data": gin.H{"error": "Failed to check authentication settings"},- })+ c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": "Failed to check authentication settings"}})return}-if !localAuthEnabled {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "data": gin.H{"error": "Local authentication is disabled"},- })+ c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": "Local authentication is disabled"}})return}user, tokenPair, err := h.authService.Login(c.Request.Context(), req.Username, req.Password)-- // Handle password change required- if errors.Is(err, services.ErrPasswordChangeRequired) && user != nil {- if tokenPair != nil {- c.SetSameSite(http.SameSiteLaxMode)- maxAge := int(time.Until(tokenPair.ExpiresAt).Seconds())- if maxAge < 0 {- maxAge = 0- }- secure := c.Request.TLS != nil- c.SetCookie("token", tokenPair.AccessToken, maxAge, "/", "", secure, true)- }-- var out dto.UserResponseDto- if mapErr := dto.MapStruct(user, &out); mapErr != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "data": gin.H{"error": "Failed to map user"},- })- return- }-- c.JSON(http.StatusOK, gin.H{- "success": true,- "data": gin.H{- "requirePasswordChange": true,- "token": func() string {- if tokenPair != nil {- return tokenPair.AccessToken- }- return ""- }(),- "refreshToken": func() string {- if tokenPair != nil {- return tokenPair.RefreshToken- }- return ""- }(),- "expiresAt": func() time.Time {- if tokenPair != nil {- return tokenPair.ExpiresAt- }- return time.Time{}- }(),- "user": out,- },- })- return- }-if err != nil {var statusCode intvar errorMsg string-switch {case errors.Is(err, services.ErrInvalidCredentials):statusCode = http.StatusUnauthorized@@ -152,28 +63,17 @@ func (h *AuthHandler) Login(c *gin.Context) {statusCode = http.StatusInternalServerErrorerrorMsg = "Authentication failed"}-- c.JSON(statusCode, gin.H{- "success": false,- "data": gin.H{"error": errorMsg},- })+ c.JSON(statusCode, gin.H{"success": false, "data": gin.H{"error": errorMsg}})return}c.SetSameSite(http.SameSiteLaxMode)maxAge := int(time.Until(tokenPair.ExpiresAt).Seconds())- if maxAge < 0 {- maxAge = 0- }- secure := c.Request.TLS != nil- c.SetCookie("token", tokenPair.AccessToken, maxAge, "/", "", secure, true)+ cookie.CreateTokenCookie(c, maxAge, tokenPair.AccessToken)var out dto.UserResponseDtoif mapErr := dto.MapStruct(user, &out); mapErr != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "data": gin.H{"error": "Failed to map user"},- })+ c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": "Failed to map user"}})return}@@ -190,55 +90,36 @@ func (h *AuthHandler) Login(c *gin.Context) {func (h *AuthHandler) Logout(c *gin.Context) {c.SetSameSite(http.SameSiteLaxMode)- c.SetCookie("token", "", -1, "/", "", false, true)-- c.JSON(http.StatusOK, gin.H{- "success": true,- "data": gin.H{"message": "Logged out successfully"},- })+ cookie.ClearTokenCookie(c)+ c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"message": "Logged out successfully"}})}func (h *AuthHandler) GetCurrentUser(c *gin.Context) {userID, exists := middleware.GetCurrentUserID(c)if !exists {- c.JSON(http.StatusUnauthorized, gin.H{- "success": false,- "data": gin.H{"error": "Not authenticated"},- })+ c.JSON(http.StatusUnauthorized, gin.H{"success": false, "data": gin.H{"error": "Not authenticated"}})return}user, err := h.userService.GetUser(c.Request.Context(), userID)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "data": gin.H{"error": "Failed to get user information"},- })+ c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": "Failed to get user information"}})return}var out dto.UserResponseDtoif mapErr := dto.MapStruct(user, &out); mapErr != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "data": gin.H{"error": "Failed to map user"},- })+ c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": "Failed to map user"}})return}- c.JSON(http.StatusOK, gin.H{- "success": true,- "data": out,- })+ c.JSON(http.StatusOK, gin.H{"success": true, "data": out})}func (h *AuthHandler) RefreshToken(c *gin.Context) {- var req RefreshRequest+ var req dto.RefreshRequestif err := c.ShouldBindJSON(&req); err != nil {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "data": gin.H{"error": "Invalid request format"},- })+ c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": "Invalid request format"}})return}@@ -246,7 +127,6 @@ func (h *AuthHandler) RefreshToken(c *gin.Context) {if err != nil {var statusCode intvar errorMsg string-switch {case errors.Is(err, services.ErrInvalidToken), errors.Is(err, services.ErrExpiredToken):statusCode = http.StatusUnauthorized@@ -255,21 +135,13 @@ func (h *AuthHandler) RefreshToken(c *gin.Context) {statusCode = http.StatusInternalServerErrorerrorMsg = "Failed to refresh token"}-- c.JSON(statusCode, gin.H{- "success": false,- "data": gin.H{"error": errorMsg},- })+ c.JSON(statusCode, gin.H{"success": false, "data": gin.H{"error": errorMsg}})return}c.SetSameSite(http.SameSiteLaxMode)maxAge := int(time.Until(tokenPair.ExpiresAt).Seconds())- if maxAge < 0 {- maxAge = 0- }- secure := c.Request.TLS != nil- c.SetCookie("token", tokenPair.AccessToken, maxAge, "/", "", secure, true)+ cookie.CreateTokenCookie(c, maxAge, tokenPair.AccessToken)c.JSON(http.StatusOK, gin.H{"success": true,@@ -284,41 +156,25 @@ func (h *AuthHandler) RefreshToken(c *gin.Context) {func (h *AuthHandler) ChangePassword(c *gin.Context) {user, exists := middleware.GetCurrentUser(c)if !exists {- c.JSON(http.StatusUnauthorized, gin.H{- "success": false,- "data": gin.H{"error": "Not authenticated"},- })+ c.JSON(http.StatusUnauthorized, gin.H{"success": false, "data": gin.H{"error": "Not authenticated"}})return}- var req PasswordChangeRequest+ var req dto.PasswordChangeRequestif err := c.ShouldBindJSON(&req); err != nil {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "data": gin.H{"error": "Invalid request format"},- })+ c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": "Invalid request format"}})return}- if !user.RequirePasswordChange && req.CurrentPassword == "" {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "data": gin.H{"error": "Current password is required"},- })+ if req.CurrentPassword == "" {+ c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": "Current password is required"}})return}- err := h.authService.ChangePassword(- c.Request.Context(),- user.ID,- req.CurrentPassword,- req.NewPassword,- )-+ err := h.authService.ChangePassword(c.Request.Context(), user.ID, req.CurrentPassword, req.NewPassword)if err != nil {var statusCode intvar errorMsg string-switch {case errors.Is(err, services.ErrInvalidCredentials):statusCode = http.StatusUnauthorized@@ -327,16 +183,9 @@ func (h *AuthHandler) ChangePassword(c *gin.Context) {statusCode = http.StatusInternalServerErrorerrorMsg = "Failed to change password"}-- c.JSON(statusCode, gin.H{- "success": false,- "data": gin.H{"error": errorMsg},- })+ c.JSON(statusCode, gin.H{"success": false, "data": gin.H{"error": errorMsg}})return}- c.JSON(http.StatusOK, gin.H{- "success": true,- "data": gin.H{"message": "Password changed successfully"},- })+ c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"message": "Password changed successfully"}})}diff --git a/backend/internal/api/oidc_handler.go b/backend/internal/api/oidc_handler.goindex 25456ad51..17816340a 100644--- a/backend/internal/api/oidc_handler.go+++ b/backend/internal/api/oidc_handler.go@@ -8,6 +8,7 @@ import ("github.com/ofkm/arcane-backend/internal/config""github.com/ofkm/arcane-backend/internal/dto""github.com/ofkm/arcane-backend/internal/services"+ "github.com/ofkm/arcane-backend/internal/utils/cookie")type OidcHandler struct {@@ -29,20 +30,6 @@ func NewOidcHandler(group *gin.RouterGroup, authService *services.AuthService, o}}-type OidcAuthUrlRequest struct {- RedirectUri string `json:"redirectUri"`-}--type OidcAuthUrlResponse struct {- AuthUrl string `json:"authUrl"`- State string `json:"state"`-}--type OidcCallbackRequest struct {- Code string `json:"code" binding:"required"`- State string `json:"state" binding:"required"`-}-func (h *OidcHandler) GetOidcStatus(c *gin.Context) {status, err := h.authService.GetOidcConfigurationStatus(c.Request.Context())if err != nil {@@ -56,7 +43,7 @@ func (h *OidcHandler) GetOidcStatus(c *gin.Context) {}func (h *OidcHandler) GetOidcAuthUrl(c *gin.Context) {- var req OidcAuthUrlRequest+ var req dto.OidcAuthUrlRequestif err := c.ShouldBindJSON(&req); err != nil {c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": "Invalid request format"})@@ -79,15 +66,7 @@ func (h *OidcHandler) GetOidcAuthUrl(c *gin.Context) {return}- c.SetCookie(- "oidc_state",- stateCookieValue,- 600, // 10 minutes- "/",- "",- c.Request.TLS != nil,- true,- )+ cookie.CreateOidcStateCookie(c, stateCookieValue, 600)c.JSON(http.StatusOK, gin.H{"authUrl": authUrl,@@ -105,13 +84,12 @@ func (h *OidcHandler) HandleOidcCallback(c *gin.Context) {return}- encodedStateFromCookie, err := c.Cookie("oidc_state")+ encodedStateFromCookie, err := cookie.GetOidcStateCookie(c)if err != nil {c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": "Missing or invalid OIDC state cookie"})return}-- c.SetCookie("oidc_state", "", -1, "/", "", c.Request.TLS != nil, true)+ cookie.ClearOidcStateCookie(c)userInfo, tokenResp, err := h.oidcService.HandleCallback(c.Request.Context(), req.Code, req.State, encodedStateFromCookie)if err != nil {@@ -127,11 +105,7 @@ func (h *OidcHandler) HandleOidcCallback(c *gin.Context) {c.SetSameSite(http.SameSiteLaxMode)maxAge := int(time.Until(tokenPair.ExpiresAt).Seconds())- if maxAge < 0 {- maxAge = 0- }- secure := c.Request.TLS != nil- c.SetCookie("token", tokenPair.AccessToken, maxAge, "/", "", secure, true)+ cookie.CreateTokenCookie(c, maxAge, tokenPair.AccessToken)c.JSON(http.StatusOK, gin.H{"success": true,diff --git a/backend/internal/dto/auth_dto.go b/backend/internal/dto/auth_dto.gonew file mode 100644index 000000000..c10ecd8d1--- /dev/null+++ b/backend/internal/dto/auth_dto.go@@ -0,0 +1,15 @@+package dto++type LoginRequest struct {+ Username string `json:"username" binding:"required"`+ Password string `json:"password" binding:"required"`+}++type RefreshRequest struct {+ RefreshToken string `json:"refreshToken" binding:"required"`+}++type PasswordChangeRequest struct {+ CurrentPassword string `json:"currentPassword"`+ NewPassword string `json:"newPassword" binding:"required"`+}diff --git a/backend/internal/dto/oidc.go b/backend/internal/dto/oidc_dto.gosimilarity index 95%rename from backend/internal/dto/oidc.gorename to backend/internal/dto/oidc_dto.goindex ffc46e741..2a4e45a61 100644--- a/backend/internal/dto/oidc.go+++ b/backend/internal/dto/oidc_dto.go@@ -38,3 +38,7 @@ type OidcStatusInfo struct {EnvForced bool `json:"envForced"`EnvConfigured bool `json:"envConfigured"`}++type OidcAuthUrlRequest struct {+ RedirectUri string `json:"redirectUri"`+}diff --git a/backend/internal/middleware/auth_middleware.go b/backend/internal/middleware/auth_middleware.goindex 91b94ce56..563769f5c 100644--- a/backend/internal/middleware/auth_middleware.go+++ b/backend/internal/middleware/auth_middleware.go@@ -9,6 +9,7 @@ import ("github.com/ofkm/arcane-backend/internal/config""github.com/ofkm/arcane-backend/internal/models""github.com/ofkm/arcane-backend/internal/services"+ "github.com/ofkm/arcane-backend/internal/utils/cookie")type AuthOptions struct {@@ -64,7 +65,6 @@ func (m *AuthMiddleware) Add() gin.HandlerFunc {return}- // Require X-Arcane-Agent-Tokenif tok := c.GetHeader("X-Arcane-Agent-Token"); tok != "" && m.cfg.AgentToken != "" && tok == m.cfg.AgentToken {slog.Info("Agent auth: agent token accepted", "path", c.Request.URL.Path, "method", c.Request.Method)agentSudo(c)@@ -149,7 +149,7 @@ func extractBearerOrCookieToken(c *gin.Context) string {if strings.HasPrefix(authHeader, "Bearer ") {return strings.TrimPrefix(authHeader, "Bearer ")}- if tokenCookie, err := c.Cookie("token"); err == nil && tokenCookie != "" {+ if tokenCookie, err := c.Cookie(cookie.TokenCookieName); err == nil && tokenCookie != "" {return tokenCookie}return ""diff --git a/backend/internal/models/user.go b/backend/internal/models/user.goindex 4c7517238..55f029978 100644--- a/backend/internal/models/user.go+++ b/backend/internal/models/user.go@@ -5,14 +5,13 @@ import ()type User struct {- Username string `json:"username" gorm:"uniqueIndex;not null"`- PasswordHash string `json:"-" gorm:"column:password_hash"`- DisplayName *string `json:"displayName,omitempty" gorm:"column:display_name"`- Email *string `json:"email,omitempty"`- Roles StringSlice `json:"roles" gorm:"type:text;not null;default:'[]'"`- RequirePasswordChange bool `json:"requirePasswordChange" gorm:"column:require_password_change;default:false"`- OidcSubjectId *string `json:"oidcSubjectId,omitempty" gorm:"column:oidc_subject_id"`- LastLogin *time.Time `json:"lastLogin,omitempty" gorm:"column:last_login"`+ Username string `json:"username" gorm:"uniqueIndex;not null"`+ PasswordHash string `json:"-" gorm:"column:password_hash"`+ DisplayName *string `json:"displayName,omitempty" gorm:"column:display_name"`+ Email *string `json:"email,omitempty"`+ Roles StringSlice `json:"roles" gorm:"type:text;not null;default:'[]'"`+ OidcSubjectId *string `json:"oidcSubjectId,omitempty" gorm:"column:oidc_subject_id"`+ LastLogin *time.Time `json:"lastLogin,omitempty" gorm:"column:last_login"`// OIDC provider tokensOidcAccessToken *string `json:"-" gorm:"type:text"`diff --git a/backend/internal/services/auth_service.go b/backend/internal/services/auth_service.goindex ea17f276c..94758eb59 100644--- a/backend/internal/services/auth_service.go+++ b/backend/internal/services/auth_service.go@@ -18,13 +18,12 @@ import ()var (- ErrInvalidCredentials = errors.New("invalid credentials")- ErrUserNotFound = errors.New("user not found")- ErrInvalidToken = errors.New("invalid token")- ErrExpiredToken = errors.New("token expired")- ErrLocalAuthDisabled = errors.New("local authentication is disabled")- ErrOidcAuthDisabled = errors.New("OIDC authentication is disabled")- ErrPasswordChangeRequired = errors.New("password change required")+ ErrInvalidCredentials = errors.New("invalid credentials")+ ErrUserNotFound = errors.New("user not found")+ ErrInvalidToken = errors.New("invalid token")+ ErrExpiredToken = errors.New("token expired")+ ErrLocalAuthDisabled = errors.New("local authentication is disabled")+ ErrOidcAuthDisabled = errors.New("OIDC authentication is disabled"))type TokenPair struct {@@ -182,10 +181,6 @@ func (s *AuthService) Login(ctx context.Context, username, password string) (*mo}}- if user.RequirePasswordChange {- return user, nil, ErrPasswordChangeRequired- }-now := time.Now()user.LastLogin = &nowif _, err := s.userService.UpdateUser(ctx, user); err != nil {@@ -531,7 +526,6 @@ func (s *AuthService) ChangePassword(ctx context.Context, userID, currentPasswor}user.PasswordHash = hashedPassword- user.RequirePasswordChange = false_, err = s.userService.UpdateUser(ctx, user)return err}diff --git a/backend/internal/utils/cookie/cookie_util.go b/backend/internal/utils/cookie/cookie_util.gonew file mode 100644index 000000000..8ced64cdf--- /dev/null+++ b/backend/internal/utils/cookie/cookie_util.go@@ -0,0 +1,39 @@+package cookie++import (+ "net/http"++ "github.com/gin-gonic/gin"+)++var (+ TokenCookieName = "__Host-token"+ OidcStateCookieName = "oidc_state"+)++func CreateTokenCookie(c *gin.Context, maxAgeInSeconds int, token string) {+ if maxAgeInSeconds < 0 {+ maxAgeInSeconds = 0+ }+ c.SetCookie(TokenCookieName, token, maxAgeInSeconds, "/", "", true, true)+}++func ClearTokenCookie(c *gin.Context) {+ c.SetCookie(TokenCookieName, "", -1, "/", "", true, true)+}++func CreateOidcStateCookie(c *gin.Context, value string, maxAgeInSeconds int) {+ c.SetSameSite(http.SameSiteLaxMode)+ if maxAgeInSeconds < 0 {+ maxAgeInSeconds = 0+ }+ c.SetCookie(OidcStateCookieName, value, maxAgeInSeconds, "/", "", true, true)+}++func GetOidcStateCookie(c *gin.Context) (string, error) {+ return c.Cookie(OidcStateCookieName)+}++func ClearOidcStateCookie(c *gin.Context) {+ c.SetCookie(OidcStateCookieName, "", -1, "/", "", true, true)+}diff --git a/frontend/src/lib/types/user.type.ts b/frontend/src/lib/types/user.type.tsindex 48d97e95a..102b48198 100644--- a/frontend/src/lib/types/user.type.ts+++ b/frontend/src/lib/types/user.type.ts@@ -7,7 +7,6 @@ export type User = {roles: string[];createdAt: string;lastLogin?: string;- requirePasswordChange?: boolean;updatedAt?: string;oidcSubjectId?: string;};