package todo import ( "net/http" "strconv" "time" "amadan.net/rastrillo/rastrillo/sessions" ) // visitorMethod is the session method recorded for an anonymous list: // nothing was verified, the browser was simply given a list. const visitorMethod = "anonymous" // visitor gives every request a list. A live session cookie names its // visitor; anything else (no cookie, an expired one, a value the store // has never seen, garbled or not) gets a fresh visitor row and a new // session, through the same sessions.SignIn an identity plugin calls. // After it, sessions.UserID(r) is always the visitor's id, so the // handlers' owned(r) seam works exactly as it does behind sess.Require. func (a *app) visitor(next http.Handler) http.Handler { return a.sess.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if _, ok := sessions.UserID(r); !ok { v := Visitor{} if err := a.db.WithContext(r.Context()).Create(&v).Error; err != nil { a.fail(w, r, err) return } now := time.Now() s := sessions.Session{Subject: strconv.FormatInt(v.ID, 10), Method: visitorMethod, At: now} if err := a.sess.SignIn(w, r, s); err != nil { a.fail(w, r, err) return } r = sessions.WithSession(r, s) } next.ServeHTTP(w, r) })) }