1
0
mirror of https://github.com/volatiletech/authboss.git synced 2025-01-22 05:09:42 +02:00
authboss/expire/expire.go

82 lines
2.1 KiB
Go
Raw Normal View History

// Package expire implements user session timeouts.
// To take advantage of this the expire.Middleware must be installed
// into your http stack.
2015-01-25 18:13:32 -08:00
package expire
import (
"net/http"
"time"
"gopkg.in/authboss.v0"
)
const (
// SessionLastAction is the session key to retrieve the last action of a user.
SessionLastAction = "last_action"
2015-01-25 18:13:32 -08:00
)
// E is the singleton instance of the expire module which will have been
// configured and ready to use after authboss.Init()
var E *Expire
func init() {
E = &Expire{}
authboss.RegisterModule("expire", E)
}
type Expire struct{}
2015-01-25 18:13:32 -08:00
func (e *Expire) Initialize() error {
2015-02-22 00:24:57 -08:00
authboss.Cfg.Callbacks.Before(authboss.EventGet, e.BeforeGet)
2015-01-25 18:13:32 -08:00
return nil
}
func (_ *Expire) Routes() authboss.RouteTable { return nil }
func (_ *Expire) Storage() authboss.StorageOptions { return nil }
2015-02-22 00:24:57 -08:00
// BeforeGet ensures the account is not expired.
func (e *Expire) BeforeGet(ctx *authboss.Context) (authboss.Interrupt, error) {
2015-01-25 18:13:32 -08:00
if _, ok := ctx.SessionStorer.Get(authboss.SessionKey); !ok {
2015-02-22 00:24:57 -08:00
return authboss.InterruptNone, nil
2015-01-25 18:13:32 -08:00
}
dateStr, ok := ctx.SessionStorer.Get(SessionLastAction)
2015-01-25 18:13:32 -08:00
if ok {
if date, err := time.Parse(time.RFC3339, dateStr); err != nil {
Touch(ctx.SessionStorer)
} else if time.Now().UTC().After(date.Add(authboss.Cfg.ExpireAfter)) {
2015-01-25 18:13:32 -08:00
ctx.SessionStorer.Del(authboss.SessionKey)
2015-02-22 00:24:57 -08:00
return authboss.InterruptSessionExpired, nil
2015-01-25 18:13:32 -08:00
}
}
2015-02-22 00:24:57 -08:00
return authboss.InterruptNone, nil
2015-01-25 18:13:32 -08:00
}
// Touch updates the last action for the user, so he doesn't become expired.
func Touch(session authboss.ClientStorer) {
session.Put(SessionLastAction, time.Now().UTC().Format(time.RFC3339))
2015-01-25 18:13:32 -08:00
}
type middleware struct {
sessionMaker authboss.SessionStoreMaker
next http.Handler
}
// Middleware ensures that the user's expiry information is kept up-to-date
2015-01-25 18:13:32 -08:00
// on each request.
func Middleware(sessionMaker authboss.SessionStoreMaker, next http.Handler) http.Handler {
2015-01-25 18:13:32 -08:00
return middleware{sessionMaker, next}
}
func (m middleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
session := m.sessionMaker(w, r)
if _, ok := session.Get(authboss.SessionKey); ok {
Touch(session)
}
m.next.ServeHTTP(w, r)
}