You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

200 lines
4.9 KiB

  1. // Copyright 2013 Beego Authors
  2. // Copyright 2014 The Macaron Authors
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  5. // not use this file except in compliance with the License. You may obtain
  6. // a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. // License for the specific language governing permissions and limitations
  14. // under the License.
  15. package session
  16. import (
  17. "database/sql"
  18. "fmt"
  19. "log"
  20. "sync"
  21. "time"
  22. _ "github.com/go-sql-driver/mysql"
  23. "github.com/go-macaron/session"
  24. )
  25. // MysqlStore represents a mysql session store implementation.
  26. type MysqlStore struct {
  27. c *sql.DB
  28. sid string
  29. lock sync.RWMutex
  30. data map[interface{}]interface{}
  31. }
  32. // NewMysqlStore creates and returns a mysql session store.
  33. func NewMysqlStore(c *sql.DB, sid string, kv map[interface{}]interface{}) *MysqlStore {
  34. return &MysqlStore{
  35. c: c,
  36. sid: sid,
  37. data: kv,
  38. }
  39. }
  40. // Set sets value to given key in session.
  41. func (s *MysqlStore) Set(key, val interface{}) error {
  42. s.lock.Lock()
  43. defer s.lock.Unlock()
  44. s.data[key] = val
  45. return nil
  46. }
  47. // Get gets value by given key in session.
  48. func (s *MysqlStore) Get(key interface{}) interface{} {
  49. s.lock.RLock()
  50. defer s.lock.RUnlock()
  51. return s.data[key]
  52. }
  53. // Delete delete a key from session.
  54. func (s *MysqlStore) Delete(key interface{}) error {
  55. s.lock.Lock()
  56. defer s.lock.Unlock()
  57. delete(s.data, key)
  58. return nil
  59. }
  60. // ID returns current session ID.
  61. func (s *MysqlStore) ID() string {
  62. return s.sid
  63. }
  64. // Release releases resource and save data to provider.
  65. func (s *MysqlStore) Release() error {
  66. // Skip encoding if the data is empty
  67. if len(s.data) == 0 {
  68. return nil
  69. }
  70. data, err := session.EncodeGob(s.data)
  71. if err != nil {
  72. return err
  73. }
  74. _, err = s.c.Exec("UPDATE session SET data=?, expiry=? WHERE `key`=?",
  75. data, time.Now().Unix(), s.sid)
  76. return err
  77. }
  78. // Flush deletes all session data.
  79. func (s *MysqlStore) Flush() error {
  80. s.lock.Lock()
  81. defer s.lock.Unlock()
  82. s.data = make(map[interface{}]interface{})
  83. return nil
  84. }
  85. // MysqlProvider represents a mysql session provider implementation.
  86. type MysqlProvider struct {
  87. c *sql.DB
  88. expire int64
  89. }
  90. // Init initializes mysql session provider.
  91. // connStr: username:password@protocol(address)/dbname?param=value
  92. func (p *MysqlProvider) Init(expire int64, connStr string) (err error) {
  93. p.expire = expire
  94. p.c, err = sql.Open("mysql", connStr)
  95. if err != nil {
  96. return err
  97. }
  98. return p.c.Ping()
  99. }
  100. // Read returns raw session store by session ID.
  101. func (p *MysqlProvider) Read(sid string) (session.RawStore, error) {
  102. var data []byte
  103. err := p.c.QueryRow("SELECT data FROM session WHERE `key`=?", sid).Scan(&data)
  104. if err == sql.ErrNoRows {
  105. _, err = p.c.Exec("INSERT INTO session(`key`,data,expiry) VALUES(?,?,?)",
  106. sid, "", time.Now().Unix())
  107. }
  108. if err != nil {
  109. return nil, err
  110. }
  111. var kv map[interface{}]interface{}
  112. if len(data) == 0 {
  113. kv = make(map[interface{}]interface{})
  114. } else {
  115. kv, err = session.DecodeGob(data)
  116. if err != nil {
  117. return nil, err
  118. }
  119. }
  120. return NewMysqlStore(p.c, sid, kv), nil
  121. }
  122. // Exist returns true if session with given ID exists.
  123. func (p *MysqlProvider) Exist(sid string) bool {
  124. var data []byte
  125. err := p.c.QueryRow("SELECT data FROM session WHERE `key`=?", sid).Scan(&data)
  126. if err != nil && err != sql.ErrNoRows {
  127. panic("session/mysql: error checking existence: " + err.Error())
  128. }
  129. return err != sql.ErrNoRows
  130. }
  131. // Destory deletes a session by session ID.
  132. func (p *MysqlProvider) Destory(sid string) error {
  133. _, err := p.c.Exec("DELETE FROM session WHERE `key`=?", sid)
  134. return err
  135. }
  136. // Regenerate regenerates a session store from old session ID to new one.
  137. func (p *MysqlProvider) Regenerate(oldsid, sid string) (_ session.RawStore, err error) {
  138. if p.Exist(sid) {
  139. return nil, fmt.Errorf("new sid '%s' already exists", sid)
  140. }
  141. if !p.Exist(oldsid) {
  142. if _, err = p.c.Exec("INSERT INTO session(`key`,data,expiry) VALUES(?,?,?)",
  143. oldsid, "", time.Now().Unix()); err != nil {
  144. return nil, err
  145. }
  146. }
  147. if _, err = p.c.Exec("UPDATE session SET `key`=? WHERE `key`=?", sid, oldsid); err != nil {
  148. return nil, err
  149. }
  150. return p.Read(sid)
  151. }
  152. // Count counts and returns number of sessions.
  153. func (p *MysqlProvider) Count() (total int) {
  154. if err := p.c.QueryRow("SELECT COUNT(*) AS NUM FROM session").Scan(&total); err != nil {
  155. panic("session/mysql: error counting records: " + err.Error())
  156. }
  157. return total
  158. }
  159. // GC calls GC to clean expired sessions.
  160. func (p *MysqlProvider) GC() {
  161. if _, err := p.c.Exec("DELETE FROM session WHERE expiry + ? <= UNIX_TIMESTAMP(NOW())", p.expire); err != nil {
  162. log.Printf("session/mysql: error garbage collecting: %v", err)
  163. }
  164. }
  165. func init() {
  166. session.Register("mysql", &MysqlProvider{})
  167. }