session.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. package sessions
  2. import (
  3. "math"
  4. "reflect"
  5. "strconv"
  6. "sync"
  7. "github.com/kataras/iris/core/memstore"
  8. )
  9. type (
  10. // Session should expose the Sessions's end-user API.
  11. // It is the session's storage controller which you can
  12. // save or retrieve values based on a key.
  13. //
  14. // This is what will be returned when sess := sessions.Start().
  15. Session struct {
  16. sid string
  17. isNew bool
  18. flashes map[string]*flashMessage
  19. mu sync.RWMutex // for flashes.
  20. // Lifetime it contains the expiration data, use it for read-only information.
  21. // See `Sessions.UpdateExpiration` too.
  22. Lifetime LifeTime
  23. // Man is the sessions manager that this session created of.
  24. Man *Sessions
  25. provider *provider
  26. }
  27. flashMessage struct {
  28. // if true then this flash message is removed on the flash gc
  29. shouldRemove bool
  30. value interface{}
  31. }
  32. )
  33. // Destroy destroys this session, it removes its session values and any flashes.
  34. // This session entry will be removed from the server,
  35. // the registered session databases will be notified for this deletion as well.
  36. //
  37. // Note that this method does NOT remove the client's cookie, although
  38. // it should be reseted if new session is attached to that (client).
  39. //
  40. // Use the session's manager `Destroy(ctx)` in order to remove the cookie instead.
  41. func (s *Session) Destroy() {
  42. s.provider.deleteSession(s)
  43. }
  44. // ID returns the session's ID.
  45. func (s *Session) ID() string {
  46. return s.sid
  47. }
  48. // IsNew returns true if this session is
  49. // created by the current application's process.
  50. func (s *Session) IsNew() bool {
  51. return s.isNew
  52. }
  53. // Get returns a value based on its "key".
  54. func (s *Session) Get(key string) interface{} {
  55. return s.provider.db.Get(s.sid, key)
  56. }
  57. // when running on the session manager removes any 'old' flash messages.
  58. func (s *Session) runFlashGC() {
  59. s.mu.Lock()
  60. for key, v := range s.flashes {
  61. if v.shouldRemove {
  62. delete(s.flashes, key)
  63. }
  64. }
  65. s.mu.Unlock()
  66. }
  67. // HasFlash returns true if this session has available flash messages.
  68. func (s *Session) HasFlash() bool {
  69. s.mu.RLock()
  70. has := len(s.flashes) > 0
  71. s.mu.RUnlock()
  72. return has
  73. }
  74. // GetFlash returns a stored flash message based on its "key"
  75. // which will be removed on the next request.
  76. //
  77. // To check for flash messages we use the HasFlash() Method
  78. // and to obtain the flash message we use the GetFlash() Method.
  79. // There is also a method GetFlashes() to fetch all the messages.
  80. //
  81. // Fetching a message deletes it from the session.
  82. // This means that a message is meant to be displayed only on the first page served to the user.
  83. func (s *Session) GetFlash(key string) interface{} {
  84. fv, ok := s.peekFlashMessage(key)
  85. if !ok {
  86. return nil
  87. }
  88. fv.shouldRemove = true
  89. return fv.value
  90. }
  91. // PeekFlash returns a stored flash message based on its "key".
  92. // Unlike GetFlash, this will keep the message valid for the next requests,
  93. // until GetFlashes or GetFlash("key").
  94. func (s *Session) PeekFlash(key string) interface{} {
  95. fv, ok := s.peekFlashMessage(key)
  96. if !ok {
  97. return nil
  98. }
  99. return fv.value
  100. }
  101. func (s *Session) peekFlashMessage(key string) (*flashMessage, bool) {
  102. s.mu.RLock()
  103. fv, found := s.flashes[key]
  104. s.mu.RUnlock()
  105. if !found {
  106. return nil, false
  107. }
  108. return fv, true
  109. }
  110. // GetString same as Get but returns its string representation,
  111. // if key doesn't exist then it returns an empty string.
  112. func (s *Session) GetString(key string) string {
  113. if value := s.Get(key); value != nil {
  114. if v, ok := value.(string); ok {
  115. return v
  116. }
  117. if v, ok := value.(int); ok {
  118. return strconv.Itoa(v)
  119. }
  120. if v, ok := value.(int64); ok {
  121. return strconv.FormatInt(v, 10)
  122. }
  123. }
  124. return ""
  125. }
  126. // GetStringDefault same as Get but returns its string representation,
  127. // if key doesn't exist then it returns the "defaultValue".
  128. func (s *Session) GetStringDefault(key string, defaultValue string) string {
  129. if v := s.GetString(key); v != "" {
  130. return v
  131. }
  132. return defaultValue
  133. }
  134. // GetFlashString same as `GetFlash` but returns its string representation,
  135. // if key doesn't exist then it returns an empty string.
  136. func (s *Session) GetFlashString(key string) string {
  137. return s.GetFlashStringDefault(key, "")
  138. }
  139. // GetFlashStringDefault same as `GetFlash` but returns its string representation,
  140. // if key doesn't exist then it returns the "defaultValue".
  141. func (s *Session) GetFlashStringDefault(key string, defaultValue string) string {
  142. if value := s.GetFlash(key); value != nil {
  143. if v, ok := value.(string); ok {
  144. return v
  145. }
  146. }
  147. return defaultValue
  148. }
  149. // ErrEntryNotFound similar to core/memstore#ErrEntryNotFound but adds
  150. // the value (if found) matched to the requested key-value pair of the session's memory storage.
  151. type ErrEntryNotFound struct {
  152. Err *memstore.ErrEntryNotFound
  153. Value interface{}
  154. }
  155. func (e *ErrEntryNotFound) Error() string {
  156. return e.Err.Error()
  157. }
  158. // Unwrap method implements the dynamic Unwrap interface of the std errors package.
  159. func (e *ErrEntryNotFound) Unwrap() error {
  160. return e.Err
  161. }
  162. // As method implements the dynamic As interface of the std errors package.
  163. // As should be NOT used directly, use `errors.As` instead.
  164. func (e *ErrEntryNotFound) As(target interface{}) bool {
  165. if v, ok := target.(*memstore.ErrEntryNotFound); ok && e.Err != nil {
  166. return e.Err.As(v)
  167. }
  168. v, ok := target.(*ErrEntryNotFound)
  169. if !ok {
  170. return false
  171. }
  172. if v.Value != nil {
  173. if v.Value != e.Value {
  174. return false
  175. }
  176. }
  177. if v.Err != nil {
  178. if e.Err != nil {
  179. return e.Err.As(v.Err)
  180. }
  181. return false
  182. }
  183. return true
  184. }
  185. func newErrEntryNotFound(key string, kind reflect.Kind, value interface{}) *ErrEntryNotFound {
  186. return &ErrEntryNotFound{Err: &memstore.ErrEntryNotFound{Key: key, Kind: kind}, Value: value}
  187. }
  188. // GetInt same as `Get` but returns its int representation,
  189. // if key doesn't exist then it returns -1 and a non-nil error.
  190. func (s *Session) GetInt(key string) (int, error) {
  191. v := s.Get(key)
  192. if v != nil {
  193. if vint, ok := v.(int); ok {
  194. return vint, nil
  195. }
  196. if vfloat64, ok := v.(float64); ok {
  197. return int(vfloat64), nil
  198. }
  199. if vint64, ok := v.(int64); ok {
  200. return int(vint64), nil
  201. }
  202. if vstring, sok := v.(string); sok {
  203. return strconv.Atoi(vstring)
  204. }
  205. }
  206. return -1, newErrEntryNotFound(key, reflect.Int, v)
  207. }
  208. // GetIntDefault same as `Get` but returns its int representation,
  209. // if key doesn't exist then it returns the "defaultValue".
  210. func (s *Session) GetIntDefault(key string, defaultValue int) int {
  211. if v, err := s.GetInt(key); err == nil {
  212. return v
  213. }
  214. return defaultValue
  215. }
  216. // Increment increments the stored int value saved as "key" by +"n".
  217. // If value doesn't exist on that "key" then it creates one with the "n" as its value.
  218. // It returns the new, incremented, value.
  219. func (s *Session) Increment(key string, n int) (newValue int) {
  220. newValue = s.GetIntDefault(key, 0)
  221. newValue += n
  222. s.Set(key, newValue)
  223. return
  224. }
  225. // Decrement decrements the stored int value saved as "key" by -"n".
  226. // If value doesn't exist on that "key" then it creates one with the "n" as its value.
  227. // It returns the new, decremented, value even if it's less than zero.
  228. func (s *Session) Decrement(key string, n int) (newValue int) {
  229. newValue = s.GetIntDefault(key, 0)
  230. newValue -= n
  231. s.Set(key, newValue)
  232. return
  233. }
  234. // GetInt64 same as `Get` but returns its int64 representation,
  235. // if key doesn't exist then it returns -1 and a non-nil error.
  236. func (s *Session) GetInt64(key string) (int64, error) {
  237. v := s.Get(key)
  238. if v != nil {
  239. if vint64, ok := v.(int64); ok {
  240. return vint64, nil
  241. }
  242. if vfloat64, ok := v.(float64); ok {
  243. return int64(vfloat64), nil
  244. }
  245. if vint, ok := v.(int); ok {
  246. return int64(vint), nil
  247. }
  248. if vstring, sok := v.(string); sok {
  249. return strconv.ParseInt(vstring, 10, 64)
  250. }
  251. }
  252. return -1, newErrEntryNotFound(key, reflect.Int64, v)
  253. }
  254. // GetInt64Default same as `Get` but returns its int64 representation,
  255. // if key doesn't exist it returns the "defaultValue".
  256. func (s *Session) GetInt64Default(key string, defaultValue int64) int64 {
  257. if v, err := s.GetInt64(key); err == nil {
  258. return v
  259. }
  260. return defaultValue
  261. }
  262. // GetUint64 same as `Get` but returns as uint64,
  263. // if key doesn't exist then it returns 0 and a non-nil error.
  264. func (s *Session) GetUint64(key string) (uint64, error) {
  265. v := s.Get(key)
  266. if v != nil {
  267. switch vv := v.(type) {
  268. case string:
  269. val, err := strconv.ParseUint(vv, 10, 64)
  270. if err != nil {
  271. return 0, err
  272. }
  273. if val > math.MaxUint64 {
  274. break
  275. }
  276. return uint64(val), nil
  277. case uint8:
  278. return uint64(vv), nil
  279. case uint16:
  280. return uint64(vv), nil
  281. case uint32:
  282. return uint64(vv), nil
  283. case uint64:
  284. return vv, nil
  285. case int64:
  286. return uint64(vv), nil
  287. case int:
  288. return uint64(vv), nil
  289. }
  290. }
  291. return 0, newErrEntryNotFound(key, reflect.Uint64, v)
  292. }
  293. // GetUint64Default same as `Get` but returns as uint64,
  294. // if key doesn't exist it returns the "defaultValue".
  295. func (s *Session) GetUint64Default(key string, defaultValue uint64) uint64 {
  296. if v, err := s.GetUint64(key); err == nil {
  297. return v
  298. }
  299. return defaultValue
  300. }
  301. // GetFloat32 same as `Get` but returns its float32 representation,
  302. // if key doesn't exist then it returns -1 and a non-nil error.
  303. func (s *Session) GetFloat32(key string) (float32, error) {
  304. v := s.Get(key)
  305. if vfloat32, ok := v.(float32); ok {
  306. return vfloat32, nil
  307. }
  308. if vfloat64, ok := v.(float64); ok {
  309. return float32(vfloat64), nil
  310. }
  311. if vint, ok := v.(int); ok {
  312. return float32(vint), nil
  313. }
  314. if vint64, ok := v.(int64); ok {
  315. return float32(vint64), nil
  316. }
  317. if vstring, sok := v.(string); sok {
  318. vfloat64, err := strconv.ParseFloat(vstring, 32)
  319. if err != nil {
  320. return -1, err
  321. }
  322. return float32(vfloat64), nil
  323. }
  324. return -1, newErrEntryNotFound(key, reflect.Float32, v)
  325. }
  326. // GetFloat32Default same as `Get` but returns its float32 representation,
  327. // if key doesn't exist then it returns the "defaultValue".
  328. func (s *Session) GetFloat32Default(key string, defaultValue float32) float32 {
  329. if v, err := s.GetFloat32(key); err == nil {
  330. return v
  331. }
  332. return defaultValue
  333. }
  334. // GetFloat64 same as `Get` but returns its float64 representation,
  335. // if key doesn't exist then it returns -1 and a non-nil error.
  336. func (s *Session) GetFloat64(key string) (float64, error) {
  337. v := s.Get(key)
  338. if vfloat32, ok := v.(float32); ok {
  339. return float64(vfloat32), nil
  340. }
  341. if vfloat64, ok := v.(float64); ok {
  342. return vfloat64, nil
  343. }
  344. if vint, ok := v.(int); ok {
  345. return float64(vint), nil
  346. }
  347. if vint64, ok := v.(int64); ok {
  348. return float64(vint64), nil
  349. }
  350. if vstring, sok := v.(string); sok {
  351. return strconv.ParseFloat(vstring, 32)
  352. }
  353. return -1, newErrEntryNotFound(key, reflect.Float64, v)
  354. }
  355. // GetFloat64Default same as `Get` but returns its float64 representation,
  356. // if key doesn't exist then it returns the "defaultValue".
  357. func (s *Session) GetFloat64Default(key string, defaultValue float64) float64 {
  358. if v, err := s.GetFloat64(key); err == nil {
  359. return v
  360. }
  361. return defaultValue
  362. }
  363. // GetBoolean same as `Get` but returns its boolean representation,
  364. // if key doesn't exist then it returns false and a non-nil error.
  365. func (s *Session) GetBoolean(key string) (bool, error) {
  366. v := s.Get(key)
  367. if v == nil {
  368. return false, newErrEntryNotFound(key, reflect.Bool, nil)
  369. }
  370. // here we could check for "true", "false" and 0 for false and 1 for true
  371. // but this may cause unexpected behavior from the developer if they expecting an error
  372. // so we just check if bool, if yes then return that bool, otherwise return false and an error.
  373. if vb, ok := v.(bool); ok {
  374. return vb, nil
  375. }
  376. if vstring, ok := v.(string); ok {
  377. return strconv.ParseBool(vstring)
  378. }
  379. return false, newErrEntryNotFound(key, reflect.Bool, v)
  380. }
  381. // GetBooleanDefault same as `Get` but returns its boolean representation,
  382. // if key doesn't exist then it returns the "defaultValue".
  383. func (s *Session) GetBooleanDefault(key string, defaultValue bool) bool {
  384. /*
  385. Note that here we can't do more than duplicate the GetBoolean's code, because of the "false".
  386. */
  387. v := s.Get(key)
  388. if v == nil {
  389. return defaultValue
  390. }
  391. // here we could check for "true", "false" and 0 for false and 1 for true
  392. // but this may cause unexpected behavior from the developer if they expecting an error
  393. // so we just check if bool, if yes then return that bool, otherwise return false and an error.
  394. if vb, ok := v.(bool); ok {
  395. return vb
  396. }
  397. if vstring, ok := v.(string); ok {
  398. if b, err := strconv.ParseBool(vstring); err == nil {
  399. return b
  400. }
  401. }
  402. return defaultValue
  403. }
  404. // GetAll returns a copy of all session's values.
  405. func (s *Session) GetAll() map[string]interface{} {
  406. items := make(map[string]interface{}, s.provider.db.Len(s.sid))
  407. s.mu.RLock()
  408. s.provider.db.Visit(s.sid, func(key string, value interface{}) {
  409. items[key] = value
  410. })
  411. s.mu.RUnlock()
  412. return items
  413. }
  414. // GetFlashes returns all flash messages as map[string](key) and interface{} value
  415. // NOTE: this will cause at remove all current flash messages on the next request of the same user.
  416. func (s *Session) GetFlashes() map[string]interface{} {
  417. flashes := make(map[string]interface{}, len(s.flashes))
  418. s.mu.Lock()
  419. for key, v := range s.flashes {
  420. flashes[key] = v.value
  421. v.shouldRemove = true
  422. }
  423. s.mu.Unlock()
  424. return flashes
  425. }
  426. // Visit loops each of the entries and calls the callback function func(key, value).
  427. func (s *Session) Visit(cb func(k string, v interface{})) {
  428. s.provider.db.Visit(s.sid, cb)
  429. }
  430. // Len returns the total number of stored values in this session.
  431. func (s *Session) Len() int {
  432. return s.provider.db.Len(s.sid)
  433. }
  434. func (s *Session) set(key string, value interface{}, immutable bool) {
  435. s.provider.db.Set(s.sid, s.Lifetime, key, value, immutable)
  436. s.mu.Lock()
  437. s.isNew = false
  438. s.mu.Unlock()
  439. }
  440. // Set fills the session with an entry "value", based on its "key".
  441. func (s *Session) Set(key string, value interface{}) {
  442. s.set(key, value, false)
  443. }
  444. // SetImmutable fills the session with an entry "value", based on its "key".
  445. // Unlike `Set`, the output value cannot be changed by the caller later on (when .Get)
  446. // An Immutable entry should be only changed with a `SetImmutable`, simple `Set` will not work
  447. // if the entry was immutable, for your own safety.
  448. // Use it consistently, it's far slower than `Set`.
  449. // Read more about muttable and immutable go types: https://stackoverflow.com/a/8021081
  450. func (s *Session) SetImmutable(key string, value interface{}) {
  451. s.set(key, value, true)
  452. }
  453. // SetFlash sets a flash message by its key.
  454. //
  455. // A flash message is used in order to keep a message in session through one or several requests of the same user.
  456. // It is removed from session after it has been displayed to the user.
  457. // Flash messages are usually used in combination with HTTP redirections,
  458. // because in this case there is no view, so messages can only be displayed in the request that follows redirection.
  459. //
  460. // A flash message has a name and a content (AKA key and value).
  461. // It is an entry of an associative array. The name is a string: often "notice", "success", or "error", but it can be anything.
  462. // The content is usually a string. You can put HTML tags in your message if you display it raw.
  463. // You can also set the message value to a number or an array: it will be serialized and kept in session like a string.
  464. //
  465. // Flash messages can be set using the SetFlash() Method
  466. // For example, if you would like to inform the user that his changes were successfully saved,
  467. // you could add the following line to your Handler:
  468. //
  469. // SetFlash("success", "Data saved!");
  470. //
  471. // In this example we used the key 'success'.
  472. // If you want to define more than one flash messages, you will have to use different keys.
  473. func (s *Session) SetFlash(key string, value interface{}) {
  474. s.mu.Lock()
  475. s.flashes[key] = &flashMessage{value: value}
  476. s.mu.Unlock()
  477. }
  478. // Delete removes an entry by its key,
  479. // returns true if actually something was removed.
  480. func (s *Session) Delete(key string) bool {
  481. removed := s.provider.db.Delete(s.sid, key)
  482. if removed {
  483. s.mu.Lock()
  484. s.isNew = false
  485. s.mu.Unlock()
  486. }
  487. return removed
  488. }
  489. // DeleteFlash removes a flash message by its key.
  490. func (s *Session) DeleteFlash(key string) {
  491. s.mu.Lock()
  492. delete(s.flashes, key)
  493. s.mu.Unlock()
  494. }
  495. // Clear removes all entries.
  496. func (s *Session) Clear() {
  497. s.mu.Lock()
  498. s.provider.db.Clear(s.sid)
  499. s.isNew = false
  500. s.mu.Unlock()
  501. }
  502. // ClearFlashes removes all flash messages.
  503. func (s *Session) ClearFlashes() {
  504. s.mu.Lock()
  505. for key := range s.flashes {
  506. delete(s.flashes, key)
  507. }
  508. s.mu.Unlock()
  509. }