session.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package session
  2. import (
  3. "encoding/gob"
  4. "x-ui/database/model"
  5. "github.com/gin-contrib/sessions"
  6. "github.com/gin-gonic/gin"
  7. )
  8. const (
  9. loginUser = "LOGIN_USER"
  10. defaultPath = "/"
  11. )
  12. func init() {
  13. gob.Register(model.User{})
  14. }
  15. func SetLoginUser(c *gin.Context, user *model.User) error {
  16. s := sessions.Default(c)
  17. s.Set(loginUser, user)
  18. return s.Save()
  19. }
  20. func SetMaxAge(c *gin.Context, maxAge int) error {
  21. s := sessions.Default(c)
  22. s.Options(sessions.Options{
  23. Path: defaultPath,
  24. MaxAge: maxAge,
  25. HttpOnly: true,
  26. })
  27. return s.Save()
  28. }
  29. func GetLoginUser(c *gin.Context) *model.User {
  30. s := sessions.Default(c)
  31. obj := s.Get(loginUser)
  32. if obj == nil {
  33. return nil
  34. }
  35. user, ok := obj.(model.User)
  36. if !ok {
  37. return nil
  38. }
  39. return &user
  40. }
  41. func IsLogin(c *gin.Context) bool {
  42. return GetLoginUser(c) != nil
  43. }
  44. func ClearSession(c *gin.Context) error {
  45. s := sessions.Default(c)
  46. s.Clear()
  47. s.Options(sessions.Options{
  48. Path: defaultPath,
  49. MaxAge: -1,
  50. HttpOnly: true,
  51. })
  52. return s.Save()
  53. }