session.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Package session provides session management utilities for the 3x-ui web panel.
  2. // It handles user authentication state, login sessions, and session storage using Gin sessions.
  3. package session
  4. import (
  5. "encoding/gob"
  6. "net/http"
  7. "github.com/mhsanaei/3x-ui/v2/database/model"
  8. "github.com/gin-contrib/sessions"
  9. "github.com/gin-gonic/gin"
  10. )
  11. const (
  12. loginUserKey = "LOGIN_USER"
  13. )
  14. func init() {
  15. gob.Register(model.User{})
  16. }
  17. // SetLoginUser stores the authenticated user in the session.
  18. // The user object is serialized and stored for subsequent requests.
  19. func SetLoginUser(c *gin.Context, user *model.User) {
  20. if user == nil {
  21. return
  22. }
  23. s := sessions.Default(c)
  24. s.Set(loginUserKey, *user)
  25. }
  26. // GetLoginUser retrieves the authenticated user from the session.
  27. // Returns nil if no user is logged in or if the session data is invalid.
  28. func GetLoginUser(c *gin.Context) *model.User {
  29. s := sessions.Default(c)
  30. obj := s.Get(loginUserKey)
  31. if obj == nil {
  32. return nil
  33. }
  34. user, ok := obj.(model.User)
  35. if !ok {
  36. s.Delete(loginUserKey)
  37. return nil
  38. }
  39. return &user
  40. }
  41. // IsLogin checks if a user is currently authenticated in the session.
  42. // Returns true if a valid user session exists, false otherwise.
  43. func IsLogin(c *gin.Context) bool {
  44. return GetLoginUser(c) != nil
  45. }
  46. // ClearSession removes all session data and invalidates the session.
  47. // This effectively logs out the user and clears any stored session information.
  48. func ClearSession(c *gin.Context) {
  49. s := sessions.Default(c)
  50. s.Clear()
  51. cookiePath := c.GetString("base_path")
  52. if cookiePath == "" {
  53. cookiePath = "/"
  54. }
  55. s.Options(sessions.Options{
  56. Path: cookiePath,
  57. MaxAge: -1,
  58. HttpOnly: true,
  59. SameSite: http.SameSiteLaxMode,
  60. })
  61. }