session.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. defaultPath = "/"
  14. )
  15. func init() {
  16. gob.Register(model.User{})
  17. }
  18. // SetLoginUser stores the authenticated user in the session.
  19. // The user object is serialized and stored for subsequent requests.
  20. func SetLoginUser(c *gin.Context, user *model.User) {
  21. if user == nil {
  22. return
  23. }
  24. s := sessions.Default(c)
  25. s.Set(loginUserKey, *user)
  26. }
  27. // GetLoginUser retrieves the authenticated user from the session.
  28. // Returns nil if no user is logged in or if the session data is invalid.
  29. func GetLoginUser(c *gin.Context) *model.User {
  30. s := sessions.Default(c)
  31. obj := s.Get(loginUserKey)
  32. if obj == nil {
  33. return nil
  34. }
  35. user, ok := obj.(model.User)
  36. if !ok {
  37. s.Delete(loginUserKey)
  38. return nil
  39. }
  40. return &user
  41. }
  42. // IsLogin checks if a user is currently authenticated in the session.
  43. // Returns true if a valid user session exists, false otherwise.
  44. func IsLogin(c *gin.Context) bool {
  45. return GetLoginUser(c) != nil
  46. }
  47. // ClearSession removes all session data and invalidates the session.
  48. // This effectively logs out the user and clears any stored session information.
  49. func ClearSession(c *gin.Context) {
  50. s := sessions.Default(c)
  51. s.Clear()
  52. s.Options(sessions.Options{
  53. Path: defaultPath,
  54. MaxAge: -1,
  55. HttpOnly: true,
  56. SameSite: http.SameSiteLaxMode,
  57. })
  58. }