carlos / todomvc-bakeoff Public

Clone
git clone https://amadan.net/carlos/todomvc-bakeoff

Plain git — no account needed to clone.

Download

Download this file

1package todo
2
3import (
4 "net/http"
5 "strconv"
6 "time"
7
8 "amadan.net/rastrillo/rastrillo/sessions"
9)
10
11// visitorMethod is the session method recorded for an anonymous list:
12// nothing was verified, the browser was simply given a list.
13const visitorMethod = "anonymous"
14
15// visitor gives every request a list. A live session cookie names its
16// visitor; anything else (no cookie, an expired one, a value the store
17// has never seen, garbled or not) gets a fresh visitor row and a new
18// session, through the same sessions.SignIn an identity plugin calls.
19// After it, sessions.UserID(r) is always the visitor's id, so the
20// handlers' owned(r) seam works exactly as it does behind sess.Require.
21func (a *app) visitor(next http.Handler) http.Handler {
22 return a.sess.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
23 if _, ok := sessions.UserID(r); !ok {
24 v := Visitor{}
25 if err := a.db.WithContext(r.Context()).Create(&v).Error; err != nil {
26 a.fail(w, r, err)
27 return
28 }
29 now := time.Now()
30 s := sessions.Session{Subject: strconv.FormatInt(v.ID, 10), Method: visitorMethod, At: now}
31 if err := a.sess.SignIn(w, r, s); err != nil {
32 a.fail(w, r, err)
33 return
34 }
35 r = sessions.WithSession(r, s)
36 }
37 next.ServeHTTP(w, r)
38 }))
39}
40