sess_postgresql.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. // Copyright 2014 beego Author. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Package postgres for session provider
  15. //
  16. // depends on github.com/lib/pq:
  17. //
  18. // go install github.com/lib/pq
  19. //
  20. //
  21. // needs this table in your database:
  22. //
  23. // CREATE TABLE session (
  24. // session_key char(64) NOT NULL,
  25. // session_data bytea,
  26. // session_expiry timestamp NOT NULL,
  27. // CONSTRAINT session_key PRIMARY KEY(session_key)
  28. // );
  29. //
  30. // will be activated with these settings in app.conf:
  31. //
  32. // SessionOn = true
  33. // SessionProvider = postgresql
  34. // SessionSavePath = "user=a password=b dbname=c sslmode=disable"
  35. // SessionName = session
  36. //
  37. //
  38. // Usage:
  39. // import(
  40. // _ "github.com/astaxie/beego/session/postgresql"
  41. // "github.com/astaxie/beego/session"
  42. // )
  43. //
  44. // func init() {
  45. // globalSessions, _ = session.NewManager("postgresql", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"user=pqgotest dbname=pqgotest sslmode=verify-full"}``)
  46. // go globalSessions.GC()
  47. // }
  48. //
  49. // more docs: http://beego.me/docs/module/session.md
  50. package postgres
  51. import (
  52. "database/sql"
  53. "net/http"
  54. "sync"
  55. "time"
  56. "github.com/astaxie/beego/session"
  57. // import postgresql Driver
  58. _ "github.com/lib/pq"
  59. )
  60. var postgresqlpder = &Provider{}
  61. // SessionStore postgresql session store
  62. type SessionStore struct {
  63. c *sql.DB
  64. sid string
  65. lock sync.RWMutex
  66. values map[interface{}]interface{}
  67. }
  68. // Set value in postgresql session.
  69. // it is temp value in map.
  70. func (st *SessionStore) Set(key, value interface{}) error {
  71. st.lock.Lock()
  72. defer st.lock.Unlock()
  73. st.values[key] = value
  74. return nil
  75. }
  76. // Get value from postgresql session
  77. func (st *SessionStore) Get(key interface{}) interface{} {
  78. st.lock.RLock()
  79. defer st.lock.RUnlock()
  80. if v, ok := st.values[key]; ok {
  81. return v
  82. }
  83. return nil
  84. }
  85. // Delete value in postgresql session
  86. func (st *SessionStore) Delete(key interface{}) error {
  87. st.lock.Lock()
  88. defer st.lock.Unlock()
  89. delete(st.values, key)
  90. return nil
  91. }
  92. // Flush clear all values in postgresql session
  93. func (st *SessionStore) Flush() error {
  94. st.lock.Lock()
  95. defer st.lock.Unlock()
  96. st.values = make(map[interface{}]interface{})
  97. return nil
  98. }
  99. // SessionID get session id of this postgresql session store
  100. func (st *SessionStore) SessionID() string {
  101. return st.sid
  102. }
  103. // SessionRelease save postgresql session values to database.
  104. // must call this method to save values to database.
  105. func (st *SessionStore) SessionRelease(w http.ResponseWriter) {
  106. defer st.c.Close()
  107. b, err := session.EncodeGob(st.values)
  108. if err != nil {
  109. return
  110. }
  111. st.c.Exec("UPDATE session set session_data=$1, session_expiry=$2 where session_key=$3",
  112. b, time.Now().Format(time.RFC3339), st.sid)
  113. }
  114. // Provider postgresql session provider
  115. type Provider struct {
  116. maxlifetime int64
  117. savePath string
  118. }
  119. // connect to postgresql
  120. func (mp *Provider) connectInit() *sql.DB {
  121. db, e := sql.Open("postgres", mp.savePath)
  122. if e != nil {
  123. return nil
  124. }
  125. return db
  126. }
  127. // SessionInit init postgresql session.
  128. // savepath is the connection string of postgresql.
  129. func (mp *Provider) SessionInit(maxlifetime int64, savePath string) error {
  130. mp.maxlifetime = maxlifetime
  131. mp.savePath = savePath
  132. return nil
  133. }
  134. // SessionRead get postgresql session by sid
  135. func (mp *Provider) SessionRead(sid string) (session.Store, error) {
  136. c := mp.connectInit()
  137. row := c.QueryRow("select session_data from session where session_key=$1", sid)
  138. var sessiondata []byte
  139. err := row.Scan(&sessiondata)
  140. if err == sql.ErrNoRows {
  141. _, err = c.Exec("insert into session(session_key,session_data,session_expiry) values($1,$2,$3)",
  142. sid, "", time.Now().Format(time.RFC3339))
  143. if err != nil {
  144. return nil, err
  145. }
  146. } else if err != nil {
  147. return nil, err
  148. }
  149. var kv map[interface{}]interface{}
  150. if len(sessiondata) == 0 {
  151. kv = make(map[interface{}]interface{})
  152. } else {
  153. kv, err = session.DecodeGob(sessiondata)
  154. if err != nil {
  155. return nil, err
  156. }
  157. }
  158. rs := &SessionStore{c: c, sid: sid, values: kv}
  159. return rs, nil
  160. }
  161. // SessionExist check postgresql session exist
  162. func (mp *Provider) SessionExist(sid string) bool {
  163. c := mp.connectInit()
  164. defer c.Close()
  165. row := c.QueryRow("select session_data from session where session_key=$1", sid)
  166. var sessiondata []byte
  167. err := row.Scan(&sessiondata)
  168. if err == sql.ErrNoRows {
  169. return false
  170. }
  171. return true
  172. }
  173. // SessionRegenerate generate new sid for postgresql session
  174. func (mp *Provider) SessionRegenerate(oldsid, sid string) (session.Store, error) {
  175. c := mp.connectInit()
  176. row := c.QueryRow("select session_data from session where session_key=$1", oldsid)
  177. var sessiondata []byte
  178. err := row.Scan(&sessiondata)
  179. if err == sql.ErrNoRows {
  180. c.Exec("insert into session(session_key,session_data,session_expiry) values($1,$2,$3)",
  181. oldsid, "", time.Now().Format(time.RFC3339))
  182. }
  183. c.Exec("update session set session_key=$1 where session_key=$2", sid, oldsid)
  184. var kv map[interface{}]interface{}
  185. if len(sessiondata) == 0 {
  186. kv = make(map[interface{}]interface{})
  187. } else {
  188. kv, err = session.DecodeGob(sessiondata)
  189. if err != nil {
  190. return nil, err
  191. }
  192. }
  193. rs := &SessionStore{c: c, sid: sid, values: kv}
  194. return rs, nil
  195. }
  196. // SessionDestroy delete postgresql session by sid
  197. func (mp *Provider) SessionDestroy(sid string) error {
  198. c := mp.connectInit()
  199. c.Exec("DELETE FROM session where session_key=$1", sid)
  200. c.Close()
  201. return nil
  202. }
  203. // SessionGC delete expired values in postgresql session
  204. func (mp *Provider) SessionGC() {
  205. c := mp.connectInit()
  206. c.Exec("DELETE from session where EXTRACT(EPOCH FROM (current_timestamp - session_expiry)) > $1", mp.maxlifetime)
  207. c.Close()
  208. return
  209. }
  210. // SessionAll count values in postgresql session
  211. func (mp *Provider) SessionAll() int {
  212. c := mp.connectInit()
  213. defer c.Close()
  214. var total int
  215. err := c.QueryRow("SELECT count(*) as num from session").Scan(&total)
  216. if err != nil {
  217. return 0
  218. }
  219. return total
  220. }
  221. func init() {
  222. session.Register("postgresql", postgresqlpder)
  223. }