session.go 14 KB

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