session.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. package sessions
  2. import (
  3. "reflect"
  4. "strconv"
  5. "sync"
  6. "github.com/kataras/iris/v12/core/memstore"
  7. )
  8. type (
  9. // Session should expose the Sessions's end-user API.
  10. // It is the session's storage controller which you can
  11. // save or retrieve values based on a key.
  12. //
  13. // This is what will be returned when sess := sessions.Start().
  14. Session struct {
  15. sid string
  16. isNew bool
  17. flashes map[string]*flashMessage
  18. mu sync.RWMutex // for flashes.
  19. // Lifetime it contains the expiration data, use it for read-only information.
  20. // See `Sessions.UpdateExpiration` too.
  21. Lifetime *memstore.LifeTime
  22. // Man is the sessions manager that this session created of.
  23. Man *Sessions
  24. provider *provider
  25. }
  26. flashMessage struct {
  27. // if true then this flash message is removed on the flash gc
  28. shouldRemove bool
  29. value interface{}
  30. }
  31. )
  32. // Destroy destroys this session, it removes its session values and any flashes.
  33. // This session entry will be removed from the server,
  34. // the registered session databases will be notified for this deletion as well.
  35. //
  36. // Note that this method does NOT remove the client's cookie, although
  37. // it should be reseted if new session is attached to that (client).
  38. //
  39. // Use the session's manager `Destroy(ctx)` in order to remove the cookie instead.
  40. func (s *Session) Destroy() {
  41. s.provider.Destroy(s.sid)
  42. }
  43. // ID returns the session's ID.
  44. func (s *Session) ID() string {
  45. return s.sid
  46. }
  47. // IsNew returns true if this session is just
  48. // created by the current application's process.
  49. func (s *Session) IsNew() bool {
  50. return s.isNew
  51. }
  52. // Get returns a value based on its "key".
  53. func (s *Session) Get(key string) interface{} {
  54. return s.provider.db.Get(s.sid, key)
  55. }
  56. // Decode binds the given "outPtr" to the value associated to the provided "key".
  57. func (s *Session) Decode(key string, outPtr interface{}) error {
  58. return s.provider.db.Decode(s.sid, key, outPtr)
  59. }
  60. // when running on the session manager removes any 'old' flash messages.
  61. func (s *Session) runFlashGC() {
  62. s.mu.Lock()
  63. for key, v := range s.flashes {
  64. if v.shouldRemove {
  65. delete(s.flashes, key)
  66. }
  67. }
  68. s.mu.Unlock()
  69. }
  70. // HasFlash returns true if this session has available flash messages.
  71. func (s *Session) HasFlash() bool {
  72. s.mu.RLock()
  73. has := len(s.flashes) > 0
  74. s.mu.RUnlock()
  75. return has
  76. }
  77. // GetFlash returns a stored flash message based on its "key"
  78. // which will be removed on the next request.
  79. //
  80. // To check for flash messages we use the HasFlash() Method
  81. // and to obtain the flash message we use the GetFlash() Method.
  82. // There is also a method GetFlashes() to fetch all the messages.
  83. //
  84. // Fetching a message deletes it from the session.
  85. // This means that a message is meant to be displayed only on the first page served to the user.
  86. func (s *Session) GetFlash(key string) interface{} {
  87. fv, ok := s.peekFlashMessage(key)
  88. if !ok {
  89. return nil
  90. }
  91. fv.shouldRemove = true
  92. return fv.value
  93. }
  94. // PeekFlash returns a stored flash message based on its "key".
  95. // Unlike GetFlash, this will keep the message valid for the next requests,
  96. // until GetFlashes or GetFlash("key").
  97. func (s *Session) PeekFlash(key string) interface{} {
  98. fv, ok := s.peekFlashMessage(key)
  99. if !ok {
  100. return nil
  101. }
  102. return fv.value
  103. }
  104. func (s *Session) peekFlashMessage(key string) (*flashMessage, bool) {
  105. s.mu.RLock()
  106. fv, found := s.flashes[key]
  107. s.mu.RUnlock()
  108. if !found {
  109. return nil, false
  110. }
  111. return fv, true
  112. }
  113. // GetString same as Get but returns its string representation,
  114. // if key doesn't exist then it returns an empty string.
  115. func (s *Session) GetString(key string) string {
  116. if value := s.Get(key); value != nil {
  117. if v, ok := value.(string); ok {
  118. return v
  119. }
  120. if v, ok := value.(int); ok {
  121. return strconv.Itoa(v)
  122. }
  123. if v, ok := value.(int64); ok {
  124. return strconv.FormatInt(v, 10)
  125. }
  126. }
  127. return ""
  128. }
  129. // GetStringDefault same as Get but returns its string representation,
  130. // if key doesn't exist then it returns the "defaultValue".
  131. func (s *Session) GetStringDefault(key string, defaultValue string) string {
  132. if v := s.GetString(key); v != "" {
  133. return v
  134. }
  135. return defaultValue
  136. }
  137. // GetFlashString same as `GetFlash` but returns its string representation,
  138. // if key doesn't exist then it returns an empty string.
  139. func (s *Session) GetFlashString(key string) string {
  140. return s.GetFlashStringDefault(key, "")
  141. }
  142. // GetFlashStringDefault same as `GetFlash` but returns its string representation,
  143. // if key doesn't exist then it returns the "defaultValue".
  144. func (s *Session) GetFlashStringDefault(key string, defaultValue string) string {
  145. if value := s.GetFlash(key); value != nil {
  146. if v, ok := value.(string); ok {
  147. return v
  148. }
  149. }
  150. return defaultValue
  151. }
  152. // ErrEntryNotFound similar to core/memstore#ErrEntryNotFound but adds
  153. // the value (if found) matched to the requested key-value pair of the session's memory storage.
  154. type ErrEntryNotFound struct {
  155. Err *memstore.ErrEntryNotFound
  156. Value interface{}
  157. }
  158. func (e *ErrEntryNotFound) Error() string {
  159. return e.Err.Error()
  160. }
  161. // Unwrap method implements the dynamic Unwrap interface of the std errors package.
  162. func (e *ErrEntryNotFound) Unwrap() error {
  163. return e.Err
  164. }
  165. // As method implements the dynamic As interface of the std errors package.
  166. // As should be NOT used directly, use `errors.As` instead.
  167. func (e *ErrEntryNotFound) As(target interface{}) bool {
  168. if v, ok := target.(*memstore.ErrEntryNotFound); ok && e.Err != nil {
  169. return e.Err.As(v)
  170. }
  171. v, ok := target.(*ErrEntryNotFound)
  172. if !ok {
  173. return false
  174. }
  175. if v.Value != nil {
  176. if v.Value != e.Value {
  177. return false
  178. }
  179. }
  180. if v.Err != nil {
  181. if e.Err != nil {
  182. return e.Err.As(v.Err)
  183. }
  184. return false
  185. }
  186. return true
  187. }
  188. func newErrEntryNotFound(key string, kind reflect.Kind, value interface{}) *ErrEntryNotFound {
  189. return &ErrEntryNotFound{Err: &memstore.ErrEntryNotFound{Key: key, Kind: kind}, Value: value}
  190. }
  191. // GetInt same as `Get` but returns its int representation,
  192. // if key doesn't exist then it returns -1 and a non-nil error.
  193. func (s *Session) GetInt(key string) (int, error) {
  194. v := s.Get(key)
  195. if v != nil {
  196. if vint, ok := v.(int); ok {
  197. return vint, nil
  198. }
  199. if vfloat64, ok := v.(float64); ok {
  200. return int(vfloat64), nil
  201. }
  202. if vint64, ok := v.(int64); ok {
  203. return int(vint64), nil
  204. }
  205. if vstring, sok := v.(string); sok {
  206. return strconv.Atoi(vstring)
  207. }
  208. }
  209. return -1, newErrEntryNotFound(key, reflect.Int, v)
  210. }
  211. // GetIntDefault same as `Get` but returns its int representation,
  212. // if key doesn't exist then it returns the "defaultValue".
  213. func (s *Session) GetIntDefault(key string, defaultValue int) int {
  214. if v, err := s.GetInt(key); err == nil {
  215. return v
  216. }
  217. return defaultValue
  218. }
  219. // Increment increments the stored int value saved as "key" by +"n".
  220. // If value doesn't exist on that "key" then it creates one with the "n" as its value.
  221. // It returns the new, incremented, value.
  222. func (s *Session) Increment(key string, n int) (newValue int) {
  223. newValue = s.GetIntDefault(key, 0)
  224. newValue += n
  225. s.Set(key, newValue)
  226. return
  227. }
  228. // Decrement decrements the stored int value saved as "key" by -"n".
  229. // If value doesn't exist on that "key" then it creates one with the "n" as its value.
  230. // It returns the new, decremented, value even if it's less than zero.
  231. func (s *Session) Decrement(key string, n int) (newValue int) {
  232. newValue = s.GetIntDefault(key, 0)
  233. newValue -= n
  234. s.Set(key, newValue)
  235. return
  236. }
  237. // GetInt64 same as `Get` but returns its int64 representation,
  238. // if key doesn't exist then it returns -1 and a non-nil error.
  239. func (s *Session) GetInt64(key string) (int64, error) {
  240. v := s.Get(key)
  241. if v != nil {
  242. if vint64, ok := v.(int64); ok {
  243. return vint64, nil
  244. }
  245. if vfloat64, ok := v.(float64); ok {
  246. return int64(vfloat64), nil
  247. }
  248. if vint, ok := v.(int); ok {
  249. return int64(vint), nil
  250. }
  251. if vstring, sok := v.(string); sok {
  252. return strconv.ParseInt(vstring, 10, 64)
  253. }
  254. }
  255. return -1, newErrEntryNotFound(key, reflect.Int64, v)
  256. }
  257. // GetInt64Default same as `Get` but returns its int64 representation,
  258. // if key doesn't exist it returns the "defaultValue".
  259. func (s *Session) GetInt64Default(key string, defaultValue int64) int64 {
  260. if v, err := s.GetInt64(key); err == nil {
  261. return v
  262. }
  263. return defaultValue
  264. }
  265. // GetUint64 same as `Get` but returns as uint64,
  266. // if key doesn't exist then it returns 0 and a non-nil error.
  267. func (s *Session) GetUint64(key string) (uint64, error) {
  268. v := s.Get(key)
  269. if v != nil {
  270. switch vv := v.(type) {
  271. case string:
  272. val, err := strconv.ParseUint(vv, 10, 64)
  273. if err != nil {
  274. return 0, err
  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, key, value, s.Lifetime.DurationUntilExpiration(), immutable)
  436. }
  437. // Set fills the session with an entry "value", based on its "key".
  438. func (s *Session) Set(key string, value interface{}) {
  439. s.set(key, value, false)
  440. }
  441. // SetImmutable fills the session with an entry "value", based on its "key".
  442. // Unlike `Set`, the output value cannot be changed by the caller later on (when .Get)
  443. // An Immutable entry should be only changed with a `SetImmutable`, simple `Set` will not work
  444. // if the entry was immutable, for your own safety.
  445. // Use it consistently, it's far slower than `Set`.
  446. // Read more about muttable and immutable go types: https://stackoverflow.com/a/8021081
  447. func (s *Session) SetImmutable(key string, value interface{}) {
  448. s.set(key, value, true)
  449. }
  450. // SetFlash sets a flash message by its key.
  451. //
  452. // A flash message is used in order to keep a message in session through one or several requests of the same user.
  453. // It is removed from session after it has been displayed to the user.
  454. // Flash messages are usually used in combination with HTTP redirections,
  455. // because in this case there is no view, so messages can only be displayed in the request that follows redirection.
  456. //
  457. // A flash message has a name and a content (AKA key and value).
  458. // It is an entry of an associative array. The name is a string: often "notice", "success", or "error", but it can be anything.
  459. // The content is usually a string. You can put HTML tags in your message if you display it raw.
  460. // You can also set the message value to a number or an array: it will be serialized and kept in session like a string.
  461. //
  462. // Flash messages can be set using the SetFlash() Method
  463. // For example, if you would like to inform the user that his changes were successfully saved,
  464. // you could add the following line to your Handler:
  465. //
  466. // SetFlash("success", "Data saved!");
  467. //
  468. // In this example we used the key 'success'.
  469. // If you want to define more than one flash messages, you will have to use different keys.
  470. func (s *Session) SetFlash(key string, value interface{}) {
  471. s.mu.Lock()
  472. if s.flashes == nil {
  473. s.flashes = make(map[string]*flashMessage)
  474. }
  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. return removed
  483. }
  484. // DeleteFlash removes a flash message by its key.
  485. func (s *Session) DeleteFlash(key string) {
  486. s.mu.Lock()
  487. delete(s.flashes, key)
  488. s.mu.Unlock()
  489. }
  490. // Clear removes all entries.
  491. func (s *Session) Clear() {
  492. s.provider.db.Clear(s.sid)
  493. }
  494. // ClearFlashes removes all flash messages.
  495. func (s *Session) ClearFlashes() {
  496. s.mu.Lock()
  497. for key := range s.flashes {
  498. delete(s.flashes, key)
  499. }
  500. s.mu.Unlock()
  501. }