本站源代码
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.

201 lines
5.0KB

  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. "gitea.com/macaron/session"
  23. _ "github.com/lib/pq"
  24. )
  25. // PostgresStore represents a postgres session store implementation.
  26. type PostgresStore struct {
  27. c *sql.DB
  28. sid string
  29. lock sync.RWMutex
  30. data map[interface{}]interface{}
  31. }
  32. // NewPostgresStore creates and returns a postgres session store.
  33. func NewPostgresStore(c *sql.DB, sid string, kv map[interface{}]interface{}) *PostgresStore {
  34. return &PostgresStore{
  35. c: c,
  36. sid: sid,
  37. data: kv,
  38. }
  39. }
  40. // Set sets value to given key in session.
  41. func (s *PostgresStore) Set(key, value interface{}) error {
  42. s.lock.Lock()
  43. defer s.lock.Unlock()
  44. s.data[key] = value
  45. return nil
  46. }
  47. // Get gets value by given key in session.
  48. func (s *PostgresStore) 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 *PostgresStore) 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 *PostgresStore) ID() string {
  62. return s.sid
  63. }
  64. // save postgres session values to database.
  65. // must call this method to save values to database.
  66. func (s *PostgresStore) Release() error {
  67. // Skip encoding if the data is empty
  68. if len(s.data) == 0 {
  69. return nil
  70. }
  71. data, err := session.EncodeGob(s.data)
  72. if err != nil {
  73. return err
  74. }
  75. _, err = s.c.Exec("UPDATE session SET data=$1, expiry=$2 WHERE key=$3",
  76. data, time.Now().Unix(), s.sid)
  77. return err
  78. }
  79. // Flush deletes all session data.
  80. func (s *PostgresStore) Flush() error {
  81. s.lock.Lock()
  82. defer s.lock.Unlock()
  83. s.data = make(map[interface{}]interface{})
  84. return nil
  85. }
  86. // PostgresProvider represents a postgres session provider implementation.
  87. type PostgresProvider struct {
  88. c *sql.DB
  89. maxlifetime int64
  90. }
  91. // Init initializes postgres session provider.
  92. // connStr: user=a password=b host=localhost port=5432 dbname=c sslmode=disable
  93. func (p *PostgresProvider) Init(maxlifetime int64, connStr string) (err error) {
  94. p.maxlifetime = maxlifetime
  95. p.c, err = sql.Open("postgres", connStr)
  96. if err != nil {
  97. return err
  98. }
  99. return p.c.Ping()
  100. }
  101. // Read returns raw session store by session ID.
  102. func (p *PostgresProvider) Read(sid string) (session.RawStore, error) {
  103. var data []byte
  104. err := p.c.QueryRow("SELECT data FROM session WHERE key=$1", sid).Scan(&data)
  105. if err == sql.ErrNoRows {
  106. _, err = p.c.Exec("INSERT INTO session(key,data,expiry) VALUES($1,$2,$3)",
  107. sid, "", time.Now().Unix())
  108. }
  109. if err != nil {
  110. return nil, err
  111. }
  112. var kv map[interface{}]interface{}
  113. if len(data) == 0 {
  114. kv = make(map[interface{}]interface{})
  115. } else {
  116. kv, err = session.DecodeGob(data)
  117. if err != nil {
  118. return nil, err
  119. }
  120. }
  121. return NewPostgresStore(p.c, sid, kv), nil
  122. }
  123. // Exist returns true if session with given ID exists.
  124. func (p *PostgresProvider) Exist(sid string) bool {
  125. var data []byte
  126. err := p.c.QueryRow("SELECT data FROM session WHERE key=$1", sid).Scan(&data)
  127. if err != nil && err != sql.ErrNoRows {
  128. panic("session/postgres: error checking existence: " + err.Error())
  129. }
  130. return err != sql.ErrNoRows
  131. }
  132. // Destroy deletes a session by session ID.
  133. func (p *PostgresProvider) Destroy(sid string) error {
  134. _, err := p.c.Exec("DELETE FROM session WHERE key=$1", sid)
  135. return err
  136. }
  137. // Regenerate regenerates a session store from old session ID to new one.
  138. func (p *PostgresProvider) Regenerate(oldsid, sid string) (_ session.RawStore, err error) {
  139. if p.Exist(sid) {
  140. return nil, fmt.Errorf("new sid '%s' already exists", sid)
  141. }
  142. if !p.Exist(oldsid) {
  143. if _, err = p.c.Exec("INSERT INTO session(key,data,expiry) VALUES($1,$2,$3)",
  144. oldsid, "", time.Now().Unix()); err != nil {
  145. return nil, err
  146. }
  147. }
  148. if _, err = p.c.Exec("UPDATE session SET key=$1 WHERE key=$2", sid, oldsid); err != nil {
  149. return nil, err
  150. }
  151. return p.Read(sid)
  152. }
  153. // Count counts and returns number of sessions.
  154. func (p *PostgresProvider) Count() (total int) {
  155. if err := p.c.QueryRow("SELECT COUNT(*) AS NUM FROM session").Scan(&total); err != nil {
  156. panic("session/postgres: error counting records: " + err.Error())
  157. }
  158. return total
  159. }
  160. // GC calls GC to clean expired sessions.
  161. func (p *PostgresProvider) GC() {
  162. if _, err := p.c.Exec("DELETE FROM session WHERE EXTRACT(EPOCH FROM NOW()) - expiry > $1", p.maxlifetime); err != nil {
  163. log.Printf("session/postgres: error garbage collecting: %v", err)
  164. }
  165. }
  166. func init() {
  167. session.Register("postgres", &PostgresProvider{})
  168. }
上海开阖软件有限公司 沪ICP备12045867号-1