session.go 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. package session
  2. import (
  3. "crypto/sha1"
  4. "encoding/json"
  5. "fmt"
  6. "io/fs"
  7. "math/rand"
  8. "net/http"
  9. "os"
  10. "strings"
  11. "time"
  12. )
  13. // vars in memory storage for session variables
  14. type vars struct {
  15. Bool map[string]bool
  16. Int map[string]int
  17. Int64 map[string]int64
  18. String map[string]string
  19. }
  20. // Session session for managing session variables
  21. type Session struct {
  22. w http.ResponseWriter
  23. r *http.Request
  24. tmpdir string
  25. varlist *vars
  26. changed bool
  27. hash string
  28. }
  29. // New to create new or load saved session,
  30. // returns error if can't load saved session
  31. func New(w http.ResponseWriter, r *http.Request, tmpdir string) (*Session, error) {
  32. s := Session{
  33. w: w,
  34. r: r,
  35. tmpdir: tmpdir,
  36. varlist: &vars{
  37. Bool: map[string]bool{},
  38. Int: map[string]int{},
  39. Int64: map[string]int64{},
  40. String: map[string]string{},
  41. },
  42. changed: false,
  43. hash: "",
  44. }
  45. cookie, err := r.Cookie("session")
  46. if err == nil && len(cookie.Value) == 40 {
  47. // Load from file
  48. s.hash = cookie.Value
  49. fname := strings.Join([]string{s.tmpdir, s.hash}, string(os.PathSeparator))
  50. var f *os.File
  51. f, err = os.Open(fname)
  52. if err != nil {
  53. return &s, err
  54. }
  55. defer f.Close()
  56. dec := json.NewDecoder(f)
  57. err = dec.Decode(&s.varlist)
  58. if err != nil {
  59. return &s, err
  60. }
  61. // Update file last modify time
  62. var info fs.FileInfo
  63. info, err = os.Stat(fname)
  64. if err != nil {
  65. return &s, err
  66. }
  67. if time.Since(info.ModTime()) > 30*time.Minute {
  68. if err := os.Chtimes(fname, time.Now(), time.Now()); err != nil {
  69. return &s, err
  70. }
  71. }
  72. } else {
  73. // Create new
  74. rand.Seed(time.Now().Unix())
  75. // Real remote IP for proxy servers
  76. rRemoteAddr := r.RemoteAddr
  77. if r.Header.Get("X-Real-IP") != "" && len(r.Header.Get("X-Real-IP")) <= 25 {
  78. rRemoteAddr = rRemoteAddr + ", " + strings.TrimSpace(r.Header.Get("X-Real-IP"))
  79. } else if r.Header.Get("X-Forwarded-For") != "" && len(r.Header.Get("X-Forwarded-For")) <= 25 {
  80. rRemoteAddr = rRemoteAddr + ", " + strings.TrimSpace(r.Header.Get("X-Forwarded-For"))
  81. }
  82. sign := rRemoteAddr + r.Header.Get("User-Agent") + fmt.Sprintf("%d", int64(time.Now().Unix())) + fmt.Sprintf("%d", int64(rand.Intn(9999999-99)+99))
  83. s.hash = fmt.Sprintf("%x", sha1.Sum([]byte(sign)))
  84. http.SetCookie(w, &http.Cookie{
  85. Name: "session",
  86. Value: s.hash,
  87. Path: "/",
  88. Expires: time.Now().Add(7 * 24 * time.Hour),
  89. HttpOnly: true,
  90. })
  91. }
  92. return &s, nil
  93. }
  94. // Close to close session and save data to local file
  95. func (s *Session) Close() bool {
  96. if !s.changed {
  97. return false
  98. }
  99. r, err := json.Marshal(s.varlist)
  100. if err == nil {
  101. f, err := os.Create(strings.Join([]string{s.tmpdir, s.hash}, string(os.PathSeparator)))
  102. if err == nil {
  103. defer f.Close()
  104. _, err = f.Write(r)
  105. if err == nil {
  106. s.changed = false
  107. return true
  108. }
  109. }
  110. }
  111. return false
  112. }
  113. // Destroy to remove session local file
  114. func (s *Session) Destroy() error {
  115. if s.tmpdir == "" || s.hash == "" {
  116. return nil
  117. }
  118. err := os.Remove(strings.Join([]string{s.tmpdir, s.hash}, string(os.PathSeparator)))
  119. if err == nil {
  120. s.changed = false
  121. }
  122. return err
  123. }