sessions.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. package sessions
  2. import (
  3. "net/http"
  4. "time"
  5. "github.com/kataras/iris/context"
  6. )
  7. // A Sessions manager should be responsible to Start a sesion, based
  8. // on a Context, which should return
  9. // a compatible Session interface, type. If the external session manager
  10. // doesn't qualifies, then the user should code the rest of the functions with empty implementation.
  11. //
  12. // Sessions should be responsible to Destroy a session based
  13. // on the Context.
  14. type Sessions struct {
  15. config Config
  16. provider *provider
  17. }
  18. // New returns a new fast, feature-rich sessions manager
  19. // it can be adapted to an iris station
  20. func New(cfg Config) *Sessions {
  21. return &Sessions{
  22. config: cfg.Validate(),
  23. provider: newProvider(),
  24. }
  25. }
  26. // UseDatabase adds a session database to the manager's provider,
  27. // a session db doesn't have write access
  28. func (s *Sessions) UseDatabase(db Database) {
  29. s.provider.RegisterDatabase(db)
  30. }
  31. // updateCookie gains the ability of updating the session browser cookie to any method which wants to update it
  32. func (s *Sessions) updateCookie(ctx context.Context, sid string, expires time.Duration) {
  33. cookie := &http.Cookie{}
  34. // The RFC makes no mention of encoding url value, so here I think to encode both sessionid key and the value using the safe(to put and to use as cookie) url-encoding
  35. cookie.Name = s.config.Cookie
  36. cookie.Value = sid
  37. cookie.Path = "/"
  38. cookie.Domain = formatCookieDomain(ctx, s.config.DisableSubdomainPersistence)
  39. cookie.HttpOnly = true
  40. // MaxAge=0 means no 'Max-Age' attribute specified.
  41. // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
  42. // MaxAge>0 means Max-Age attribute present and given in seconds
  43. if expires >= 0 {
  44. if expires == 0 { // unlimited life
  45. cookie.Expires = CookieExpireUnlimited
  46. } else { // > 0
  47. cookie.Expires = time.Now().Add(expires)
  48. }
  49. cookie.MaxAge = int(cookie.Expires.Sub(time.Now()).Seconds())
  50. }
  51. // set the cookie to secure if this is a tls wrapped request
  52. // and the configuration allows it.
  53. if ctx.Request().TLS != nil && s.config.CookieSecureTLS {
  54. cookie.Secure = true
  55. }
  56. // encode the session id cookie client value right before send it.
  57. cookie.Value = s.encodeCookieValue(cookie.Value)
  58. AddCookie(ctx, cookie, s.config.AllowReclaim)
  59. }
  60. // Start should start the session for the particular request.
  61. func (s *Sessions) Start(ctx context.Context) *Session {
  62. cookieValue := s.decodeCookieValue(GetCookie(ctx, s.config.Cookie))
  63. if cookieValue == "" { // cookie doesn't exists, let's generate a session and add set a cookie
  64. sid := s.config.SessionIDGenerator()
  65. sess := s.provider.Init(sid, s.config.Expires)
  66. sess.isNew = s.provider.db.Len(sid) == 0
  67. s.updateCookie(ctx, sid, s.config.Expires)
  68. return sess
  69. }
  70. sess := s.provider.Read(cookieValue, s.config.Expires)
  71. return sess
  72. }
  73. // ShiftExpiration move the expire date of a session to a new date
  74. // by using session default timeout configuration.
  75. // It will return `ErrNotImplemented` if a database is used and it does not support this feature, yet.
  76. func (s *Sessions) ShiftExpiration(ctx context.Context) error {
  77. return s.UpdateExpiration(ctx, s.config.Expires)
  78. }
  79. // UpdateExpiration change expire date of a session to a new date
  80. // by using timeout value passed by `expires` receiver.
  81. // It will return `ErrNotFound` when trying to update expiration on a non-existence or not valid session entry.
  82. // It will return `ErrNotImplemented` if a database is used and it does not support this feature, yet.
  83. func (s *Sessions) UpdateExpiration(ctx context.Context, expires time.Duration) error {
  84. cookieValue := s.decodeCookieValue(GetCookie(ctx, s.config.Cookie))
  85. if cookieValue == "" {
  86. return ErrNotFound
  87. }
  88. // we should also allow it to expire when the browser closed
  89. err := s.provider.UpdateExpiration(cookieValue, expires)
  90. if err == nil || expires == -1 {
  91. s.updateCookie(ctx, cookieValue, expires)
  92. }
  93. return err
  94. }
  95. // DestroyListener is the form of a destroy listener.
  96. // Look `OnDestroy` for more.
  97. type DestroyListener func(sid string)
  98. // OnDestroy registers one or more destroy listeners.
  99. // A destroy listener is fired when a session has been removed entirely from the server (the entry) and client-side (the cookie).
  100. // Note that if a destroy listener is blocking, then the session manager will delay respectfully,
  101. // use a goroutine inside the listener to avoid that behavior.
  102. func (s *Sessions) OnDestroy(listeners ...DestroyListener) {
  103. for _, ln := range listeners {
  104. s.provider.registerDestroyListener(ln)
  105. }
  106. }
  107. // Destroy remove the session data and remove the associated cookie.
  108. func (s *Sessions) Destroy(ctx context.Context) {
  109. cookieValue := GetCookie(ctx, s.config.Cookie)
  110. // decode the client's cookie value in order to find the server's session id
  111. // to destroy the session data.
  112. cookieValue = s.decodeCookieValue(cookieValue)
  113. if cookieValue == "" { // nothing to destroy
  114. return
  115. }
  116. RemoveCookie(ctx, s.config)
  117. s.provider.Destroy(cookieValue)
  118. }
  119. // DestroyByID removes the session entry
  120. // from the server-side memory (and database if registered).
  121. // Client's session cookie will still exist but it will be reseted on the next request.
  122. //
  123. // It's safe to use it even if you are not sure if a session with that id exists.
  124. //
  125. // Note: the sid should be the original one (i.e: fetched by a store )
  126. // it's not decoded.
  127. func (s *Sessions) DestroyByID(sid string) {
  128. s.provider.Destroy(sid)
  129. }
  130. // DestroyAll removes all sessions
  131. // from the server-side memory (and database if registered).
  132. // Client's session cookie will still exist but it will be reseted on the next request.
  133. func (s *Sessions) DestroyAll() {
  134. s.provider.DestroyAll()
  135. }
  136. // let's keep these funcs simple, we can do it with two lines but we may add more things in the future.
  137. func (s *Sessions) decodeCookieValue(cookieValue string) string {
  138. if cookieValue == "" {
  139. return ""
  140. }
  141. var cookieValueDecoded *string
  142. if decode := s.config.Decode; decode != nil {
  143. err := decode(s.config.Cookie, cookieValue, &cookieValueDecoded)
  144. if err == nil {
  145. cookieValue = *cookieValueDecoded
  146. } else {
  147. cookieValue = ""
  148. }
  149. }
  150. return cookieValue
  151. }
  152. func (s *Sessions) encodeCookieValue(cookieValue string) string {
  153. if encode := s.config.Encode; encode != nil {
  154. newVal, err := encode(s.config.Cookie, cookieValue)
  155. if err == nil {
  156. cookieValue = newVal
  157. } else {
  158. cookieValue = ""
  159. }
  160. }
  161. return cookieValue
  162. }