1
0
mirror of https://github.com/volatiletech/authboss.git synced 2025-01-10 04:17:59 +02:00
authboss/expire.go

70 lines
1.8 KiB
Go
Raw Normal View History

2015-03-02 18:04:31 +02:00
package authboss
import (
"net/http"
"time"
)
var nowTime = time.Now
// TimeToExpiry returns zero if the user session is expired else the time until expiry.
func (a *Authboss) TimeToExpiry(w http.ResponseWriter, r *http.Request) time.Duration {
return a.timeToExpiry(a.SessionStoreMaker(w, r))
2015-03-02 18:04:31 +02:00
}
func (a *Authboss) timeToExpiry(session ClientStorer) time.Duration {
2015-03-02 18:04:31 +02:00
dateStr, ok := session.Get(SessionLastAction)
if !ok {
return a.ExpireAfter
2015-03-02 18:04:31 +02:00
}
date, err := time.Parse(time.RFC3339, dateStr)
if err != nil {
panic("last_action is not a valid RFC3339 date")
}
remaining := date.Add(a.ExpireAfter).Sub(nowTime().UTC())
2015-03-02 18:04:31 +02:00
if remaining > 0 {
return remaining
}
return 0
}
// RefreshExpiry updates the last action for the user, so he doesn't become expired.
func (a *Authboss) RefreshExpiry(w http.ResponseWriter, r *http.Request) {
session := a.SessionStoreMaker(w, r)
a.refreshExpiry(session)
2015-03-02 18:04:31 +02:00
}
func (a *Authboss) refreshExpiry(session ClientStorer) {
2015-03-02 18:04:31 +02:00
session.Put(SessionLastAction, nowTime().UTC().Format(time.RFC3339))
}
type expireMiddleware struct {
ab *Authboss
2015-03-02 18:04:31 +02:00
next http.Handler
}
// ExpireMiddleware ensures that the user's expiry information is kept up-to-date
// on each request. Deletes the SessionKey from the session if the user is
// expired (a.ExpireAfter duration since SessionLastAction).
func (a *Authboss) ExpireMiddleware(next http.Handler) http.Handler {
return expireMiddleware{a, next}
2015-03-02 18:04:31 +02:00
}
func (m expireMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
session := m.ab.SessionStoreMaker(w, r)
2015-03-02 18:04:31 +02:00
if _, ok := session.Get(SessionKey); ok {
ttl := m.ab.timeToExpiry(session)
if ttl == 0 {
2015-03-02 18:04:31 +02:00
session.Del(SessionKey)
session.Del(SessionLastAction)
} else {
m.ab.refreshExpiry(session)
2015-03-02 18:04:31 +02:00
}
}
m.next.ServeHTTP(w, r)
}