session.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. // SetMaxAge configures the session cookie maximum age in seconds.
  28. // This controls how long the session remains valid before requiring re-authentication.
  29. func SetMaxAge(c *gin.Context, maxAge int) {
  30. s := sessions.Default(c)
  31. s.Options(sessions.Options{
  32. Path: defaultPath,
  33. MaxAge: maxAge,
  34. HttpOnly: true,
  35. SameSite: http.SameSiteLaxMode,
  36. })
  37. }
  38. // GetLoginUser retrieves the authenticated user from the session.
  39. // Returns nil if no user is logged in or if the session data is invalid.
  40. func GetLoginUser(c *gin.Context) *model.User {
  41. s := sessions.Default(c)
  42. obj := s.Get(loginUserKey)
  43. if obj == nil {
  44. return nil
  45. }
  46. user, ok := obj.(model.User)
  47. if !ok {
  48. s.Delete(loginUserKey)
  49. return nil
  50. }
  51. return &user
  52. }
  53. // IsLogin checks if a user is currently authenticated in the session.
  54. // Returns true if a valid user session exists, false otherwise.
  55. func IsLogin(c *gin.Context) bool {
  56. return GetLoginUser(c) != nil
  57. }
  58. // ClearSession removes all session data and invalidates the session.
  59. // This effectively logs out the user and clears any stored session information.
  60. func ClearSession(c *gin.Context) {
  61. s := sessions.Default(c)
  62. s.Clear()
  63. s.Options(sessions.Options{
  64. Path: defaultPath,
  65. MaxAge: -1,
  66. HttpOnly: true,
  67. SameSite: http.SameSiteLaxMode,
  68. })
  69. }