session.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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 session provider
  15. //
  16. // Usage:
  17. // import(
  18. // "github.com/astaxie/beego/session"
  19. // )
  20. //
  21. // func init() {
  22. // globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid", "enableSetCookie,omitempty": true, "gclifetime":3600, "maxLifetime": 3600, "secure": false, "cookieLifeTime": 3600, "providerConfig": ""}`)
  23. // go globalSessions.GC()
  24. // }
  25. //
  26. // more docs: http://beego.me/docs/module/session.md
  27. package session
  28. import (
  29. "crypto/rand"
  30. "encoding/hex"
  31. "errors"
  32. "fmt"
  33. "io"
  34. "log"
  35. "net/http"
  36. "net/textproto"
  37. "net/url"
  38. "os"
  39. "time"
  40. )
  41. // Store contains all data for one session process with specific id.
  42. type Store interface {
  43. Set(key, value interface{}) error //set session value
  44. Get(key interface{}) interface{} //get session value
  45. Delete(key interface{}) error //delete session value
  46. SessionID() string //back current sessionID
  47. SessionRelease(w http.ResponseWriter) // release the resource & save data to provider & return the data
  48. Flush() error //delete all data
  49. }
  50. // Provider contains global session methods and saved SessionStores.
  51. // it can operate a SessionStore by its id.
  52. type Provider interface {
  53. SessionInit(gclifetime int64, config string) error
  54. SessionRead(sid string) (Store, error)
  55. SessionExist(sid string) bool
  56. SessionRegenerate(oldsid, sid string) (Store, error)
  57. SessionDestroy(sid string) error
  58. SessionAll() int //get all active session
  59. SessionGC()
  60. }
  61. var provides = make(map[string]Provider)
  62. // SLogger a helpful variable to log information about session
  63. var SLogger = NewSessionLog(os.Stderr)
  64. // Register makes a session provide available by the provided name.
  65. // If Register is called twice with the same name or if driver is nil,
  66. // it panics.
  67. func Register(name string, provide Provider) {
  68. if provide == nil {
  69. panic("session: Register provide is nil")
  70. }
  71. if _, dup := provides[name]; dup {
  72. panic("session: Register called twice for provider " + name)
  73. }
  74. provides[name] = provide
  75. }
  76. type ManagerConfig struct {
  77. CookieName string `json:"cookieName"`
  78. EnableSetCookie bool `json:"enableSetCookie,omitempty"`
  79. Gclifetime int64 `json:"gclifetime"`
  80. Maxlifetime int64 `json:"maxLifetime"`
  81. DisableHTTPOnly bool `json:"disableHTTPOnly"`
  82. Secure bool `json:"secure"`
  83. CookieLifeTime int `json:"cookieLifeTime"`
  84. ProviderConfig string `json:"providerConfig"`
  85. Domain string `json:"domain"`
  86. SessionIDLength int64 `json:"sessionIDLength"`
  87. EnableSidInHttpHeader bool `json:"enableSidInHttpHeader"`
  88. SessionNameInHttpHeader string `json:"sessionNameInHttpHeader"`
  89. EnableSidInUrlQuery bool `json:"enableSidInUrlQuery"`
  90. }
  91. // Manager contains Provider and its configuration.
  92. type Manager struct {
  93. provider Provider
  94. config *ManagerConfig
  95. }
  96. // NewManager Create new Manager with provider name and json config string.
  97. // provider name:
  98. // 1. cookie
  99. // 2. file
  100. // 3. memory
  101. // 4. redis
  102. // 5. mysql
  103. // json config:
  104. // 1. is https default false
  105. // 2. hashfunc default sha1
  106. // 3. hashkey default beegosessionkey
  107. // 4. maxage default is none
  108. func NewManager(provideName string, cf *ManagerConfig) (*Manager, error) {
  109. provider, ok := provides[provideName]
  110. if !ok {
  111. return nil, fmt.Errorf("session: unknown provide %q (forgotten import?)", provideName)
  112. }
  113. if cf.Maxlifetime == 0 {
  114. cf.Maxlifetime = cf.Gclifetime
  115. }
  116. if cf.EnableSidInHttpHeader {
  117. if cf.SessionNameInHttpHeader == "" {
  118. panic(errors.New("SessionNameInHttpHeader is empty"))
  119. }
  120. strMimeHeader := textproto.CanonicalMIMEHeaderKey(cf.SessionNameInHttpHeader)
  121. if cf.SessionNameInHttpHeader != strMimeHeader {
  122. strErrMsg := "SessionNameInHttpHeader (" + cf.SessionNameInHttpHeader + ") has the wrong format, it should be like this : " + strMimeHeader
  123. panic(errors.New(strErrMsg))
  124. }
  125. }
  126. err := provider.SessionInit(cf.Maxlifetime, cf.ProviderConfig)
  127. if err != nil {
  128. return nil, err
  129. }
  130. if cf.SessionIDLength == 0 {
  131. cf.SessionIDLength = 16
  132. }
  133. return &Manager{
  134. provider,
  135. cf,
  136. }, nil
  137. }
  138. // getSid retrieves session identifier from HTTP Request.
  139. // First try to retrieve id by reading from cookie, session cookie name is configurable,
  140. // if not exist, then retrieve id from querying parameters.
  141. //
  142. // error is not nil when there is anything wrong.
  143. // sid is empty when need to generate a new session id
  144. // otherwise return an valid session id.
  145. func (manager *Manager) getSid(r *http.Request) (string, error) {
  146. cookie, errs := r.Cookie(manager.config.CookieName)
  147. if errs != nil || cookie.Value == "" {
  148. var sid string
  149. if manager.config.EnableSidInUrlQuery {
  150. errs := r.ParseForm()
  151. if errs != nil {
  152. return "", errs
  153. }
  154. sid = r.FormValue(manager.config.CookieName)
  155. }
  156. // if not found in Cookie / param, then read it from request headers
  157. if manager.config.EnableSidInHttpHeader && sid == "" {
  158. sids, isFound := r.Header[manager.config.SessionNameInHttpHeader]
  159. if isFound && len(sids) != 0 {
  160. return sids[0], nil
  161. }
  162. }
  163. return sid, nil
  164. }
  165. // HTTP Request contains cookie for sessionid info.
  166. return url.QueryUnescape(cookie.Value)
  167. }
  168. // SessionStart generate or read the session id from http request.
  169. // if session id exists, return SessionStore with this id.
  170. func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (session Store, err error) {
  171. sid, errs := manager.getSid(r)
  172. if errs != nil {
  173. return nil, errs
  174. }
  175. if sid != "" && manager.provider.SessionExist(sid) {
  176. return manager.provider.SessionRead(sid)
  177. }
  178. // Generate a new session
  179. sid, errs = manager.sessionID()
  180. if errs != nil {
  181. return nil, errs
  182. }
  183. session, err = manager.provider.SessionRead(sid)
  184. if err != nil {
  185. return nil, err
  186. }
  187. cookie := &http.Cookie{
  188. Name: manager.config.CookieName,
  189. Value: url.QueryEscape(sid),
  190. Path: "/",
  191. HttpOnly: !manager.config.DisableHTTPOnly,
  192. Secure: manager.isSecure(r),
  193. Domain: manager.config.Domain,
  194. }
  195. if manager.config.CookieLifeTime > 0 {
  196. cookie.MaxAge = manager.config.CookieLifeTime
  197. cookie.Expires = time.Now().Add(time.Duration(manager.config.CookieLifeTime) * time.Second)
  198. }
  199. if manager.config.EnableSetCookie {
  200. http.SetCookie(w, cookie)
  201. }
  202. r.AddCookie(cookie)
  203. if manager.config.EnableSidInHttpHeader {
  204. r.Header.Set(manager.config.SessionNameInHttpHeader, sid)
  205. w.Header().Set(manager.config.SessionNameInHttpHeader, sid)
  206. }
  207. return
  208. }
  209. // SessionDestroy Destroy session by its id in http request cookie.
  210. func (manager *Manager) SessionDestroy(w http.ResponseWriter, r *http.Request) {
  211. if manager.config.EnableSidInHttpHeader {
  212. r.Header.Del(manager.config.SessionNameInHttpHeader)
  213. w.Header().Del(manager.config.SessionNameInHttpHeader)
  214. }
  215. cookie, err := r.Cookie(manager.config.CookieName)
  216. if err != nil || cookie.Value == "" {
  217. return
  218. }
  219. sid, _ := url.QueryUnescape(cookie.Value)
  220. manager.provider.SessionDestroy(sid)
  221. if manager.config.EnableSetCookie {
  222. expiration := time.Now()
  223. cookie = &http.Cookie{Name: manager.config.CookieName,
  224. Path: "/",
  225. HttpOnly: !manager.config.DisableHTTPOnly,
  226. Expires: expiration,
  227. MaxAge: -1}
  228. http.SetCookie(w, cookie)
  229. }
  230. }
  231. // GetSessionStore Get SessionStore by its id.
  232. func (manager *Manager) GetSessionStore(sid string) (sessions Store, err error) {
  233. sessions, err = manager.provider.SessionRead(sid)
  234. return
  235. }
  236. // GC Start session gc process.
  237. // it can do gc in times after gc lifetime.
  238. func (manager *Manager) GC() {
  239. manager.provider.SessionGC()
  240. time.AfterFunc(time.Duration(manager.config.Gclifetime)*time.Second, func() { manager.GC() })
  241. }
  242. // SessionRegenerateID Regenerate a session id for this SessionStore who's id is saving in http request.
  243. func (manager *Manager) SessionRegenerateID(w http.ResponseWriter, r *http.Request) (session Store) {
  244. sid, err := manager.sessionID()
  245. if err != nil {
  246. return
  247. }
  248. cookie, err := r.Cookie(manager.config.CookieName)
  249. if err != nil || cookie.Value == "" {
  250. //delete old cookie
  251. session, _ = manager.provider.SessionRead(sid)
  252. cookie = &http.Cookie{Name: manager.config.CookieName,
  253. Value: url.QueryEscape(sid),
  254. Path: "/",
  255. HttpOnly: !manager.config.DisableHTTPOnly,
  256. Secure: manager.isSecure(r),
  257. Domain: manager.config.Domain,
  258. }
  259. } else {
  260. oldsid, _ := url.QueryUnescape(cookie.Value)
  261. session, _ = manager.provider.SessionRegenerate(oldsid, sid)
  262. cookie.Value = url.QueryEscape(sid)
  263. cookie.HttpOnly = true
  264. cookie.Path = "/"
  265. }
  266. if manager.config.CookieLifeTime > 0 {
  267. cookie.MaxAge = manager.config.CookieLifeTime
  268. cookie.Expires = time.Now().Add(time.Duration(manager.config.CookieLifeTime) * time.Second)
  269. }
  270. if manager.config.EnableSetCookie {
  271. http.SetCookie(w, cookie)
  272. }
  273. r.AddCookie(cookie)
  274. if manager.config.EnableSidInHttpHeader {
  275. r.Header.Set(manager.config.SessionNameInHttpHeader, sid)
  276. w.Header().Set(manager.config.SessionNameInHttpHeader, sid)
  277. }
  278. return
  279. }
  280. // GetActiveSession Get all active sessions count number.
  281. func (manager *Manager) GetActiveSession() int {
  282. return manager.provider.SessionAll()
  283. }
  284. // SetSecure Set cookie with https.
  285. func (manager *Manager) SetSecure(secure bool) {
  286. manager.config.Secure = secure
  287. }
  288. func (manager *Manager) sessionID() (string, error) {
  289. b := make([]byte, manager.config.SessionIDLength)
  290. n, err := rand.Read(b)
  291. if n != len(b) || err != nil {
  292. return "", fmt.Errorf("Could not successfully read from the system CSPRNG.")
  293. }
  294. return hex.EncodeToString(b), nil
  295. }
  296. // Set cookie with https.
  297. func (manager *Manager) isSecure(req *http.Request) bool {
  298. if !manager.config.Secure {
  299. return false
  300. }
  301. if req.URL.Scheme != "" {
  302. return req.URL.Scheme == "https"
  303. }
  304. if req.TLS == nil {
  305. return false
  306. }
  307. return true
  308. }
  309. // Log implement the log.Logger
  310. type Log struct {
  311. *log.Logger
  312. }
  313. // NewSessionLog set io.Writer to create a Logger for session.
  314. func NewSessionLog(out io.Writer) *Log {
  315. sl := new(Log)
  316. sl.Logger = log.New(out, "[SESSION]", 1e9)
  317. return sl
  318. }