session.go 2.7 KB

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