session.go 2.9 KB

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