session.go 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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. Bool: map[string]bool{},
  36. Int: map[string]int{},
  37. Int64: map[string]int64{},
  38. String: map[string]string{},
  39. },
  40. changed: false,
  41. hash: "",
  42. }
  43. cookie, err := r.Cookie("session")
  44. if err == nil && len(cookie.Value) == 40 {
  45. // Load from file
  46. s.hash = cookie.Value
  47. fname := strings.Join([]string{s.tmpdir, s.hash}, string(os.PathSeparator))
  48. if f, err := os.Open(fname); err == nil {
  49. defer f.Close()
  50. dec := json.NewDecoder(f)
  51. if err := dec.Decode(&s.varlist); err == nil {
  52. // Update file last modify time
  53. if info, err := os.Stat(fname); err == nil {
  54. if time.Since(info.ModTime()) > 30*time.Minute {
  55. _ = os.Chtimes(fname, time.Now(), time.Now())
  56. }
  57. }
  58. }
  59. }
  60. } else {
  61. // Create new
  62. rand.Seed(time.Now().Unix())
  63. // Real remote IP for proxy servers
  64. rRemoteAddr := r.RemoteAddr
  65. if r.Header.Get("X-Real-IP") != "" && len(r.Header.Get("X-Real-IP")) <= 25 {
  66. rRemoteAddr = rRemoteAddr + ", " + strings.TrimSpace(r.Header.Get("X-Real-IP"))
  67. } else if r.Header.Get("X-Forwarded-For") != "" && len(r.Header.Get("X-Forwarded-For")) <= 25 {
  68. rRemoteAddr = rRemoteAddr + ", " + strings.TrimSpace(r.Header.Get("X-Forwarded-For"))
  69. }
  70. sign := rRemoteAddr + r.Header.Get("User-Agent") + fmt.Sprintf("%d", int64(time.Now().Unix())) + fmt.Sprintf("%d", int64(rand.Intn(9999999-99)+99))
  71. s.hash = fmt.Sprintf("%x", sha1.Sum([]byte(sign)))
  72. http.SetCookie(w, &http.Cookie{
  73. Name: "session",
  74. Value: s.hash,
  75. Path: "/",
  76. Expires: time.Now().Add(7 * 24 * time.Hour),
  77. HttpOnly: true,
  78. })
  79. }
  80. return &s
  81. }
  82. // Close to close session and save data to local file
  83. func (s *Session) Close() bool {
  84. if !s.changed {
  85. return false
  86. }
  87. r, err := json.Marshal(s.varlist)
  88. if err == nil {
  89. f, err := os.Create(strings.Join([]string{s.tmpdir, s.hash}, string(os.PathSeparator)))
  90. if err == nil {
  91. defer f.Close()
  92. _, err = f.Write(r)
  93. if err == nil {
  94. s.changed = false
  95. return true
  96. }
  97. }
  98. }
  99. return false
  100. }
  101. // Destroy to remove session local file
  102. func (s *Session) Destroy() error {
  103. if s.tmpdir == "" || s.hash == "" {
  104. return nil
  105. }
  106. err := os.Remove(strings.Join([]string{s.tmpdir, s.hash}, string(os.PathSeparator)))
  107. if err == nil {
  108. s.changed = false
  109. }
  110. return err
  111. }