3x-ui/web/session/session.go

72 lines
1.7 KiB
Go
Raw Permalink Normal View History

2025-09-20 07:35:50 +00:00
// Package session provides session management utilities for the 3x-ui web panel.
// It handles user authentication state, login sessions, and session storage using Gin sessions.
2023-02-09 19:18:06 +00:00
package session
import (
"encoding/gob"
2025-09-12 11:04:36 +00:00
"net/http"
2025-09-19 08:05:43 +00:00
"github.com/mhsanaei/3x-ui/v2/database/model"
2024-04-20 21:26:55 +00:00
"github.com/gin-contrib/sessions"
2023-02-09 19:18:06 +00:00
"github.com/gin-gonic/gin"
)
2024-08-06 11:44:48 +00:00
const (
2024-12-16 13:24:59 +00:00
loginUserKey = "LOGIN_USER"
2024-08-06 11:44:48 +00:00
)
2023-02-09 19:18:06 +00:00
func init() {
gob.Register(model.User{})
}
2025-09-20 07:35:50 +00:00
// SetLoginUser stores the authenticated user in the session.
// The user object is serialized and stored for subsequent requests.
2024-12-16 13:24:59 +00:00
func SetLoginUser(c *gin.Context, user *model.User) {
if user == nil {
return
}
2023-02-09 19:18:06 +00:00
s := sessions.Default(c)
2024-12-16 13:24:59 +00:00
s.Set(loginUserKey, *user)
2023-02-09 19:18:06 +00:00
}
2025-09-20 07:35:50 +00:00
// GetLoginUser retrieves the authenticated user from the session.
// Returns nil if no user is logged in or if the session data is invalid.
2023-02-09 19:18:06 +00:00
func GetLoginUser(c *gin.Context) *model.User {
s := sessions.Default(c)
2024-12-16 13:24:59 +00:00
obj := s.Get(loginUserKey)
2024-08-06 11:44:48 +00:00
if obj == nil {
return nil
2023-02-09 19:18:06 +00:00
}
2024-08-06 11:44:48 +00:00
user, ok := obj.(model.User)
if !ok {
2024-12-16 13:24:59 +00:00
s.Delete(loginUserKey)
2024-08-06 11:44:48 +00:00
return nil
}
return &user
2023-02-09 19:18:06 +00:00
}
2025-09-20 07:35:50 +00:00
// IsLogin checks if a user is currently authenticated in the session.
// Returns true if a valid user session exists, false otherwise.
2023-02-09 19:18:06 +00:00
func IsLogin(c *gin.Context) bool {
return GetLoginUser(c) != nil
}
2025-09-20 07:35:50 +00:00
// ClearSession removes all session data and invalidates the session.
// This effectively logs out the user and clears any stored session information.
2024-12-16 13:24:59 +00:00
func ClearSession(c *gin.Context) {
2023-02-09 19:18:06 +00:00
s := sessions.Default(c)
s.Clear()
2026-04-20 18:03:40 +00:00
cookiePath := c.GetString("base_path")
if cookiePath == "" {
cookiePath = "/"
}
2023-02-09 19:18:06 +00:00
s.Options(sessions.Options{
2026-04-20 18:03:40 +00:00
Path: cookiePath,
2024-08-06 11:44:48 +00:00
MaxAge: -1,
HttpOnly: true,
2025-09-12 11:04:36 +00:00
SameSite: http.SameSiteLaxMode,
2023-02-09 19:18:06 +00:00
})
}