users_test.go50 lines, 1.4 KB
| 1 | package users |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "net/http" |
| 7 | "net/http/httptest" |
| 8 | "testing" |
| 9 | "time" |
| 10 | |
| 11 | "github.com/fiston-user/murmur/internal/platform/testdb" |
| 12 | ) |
| 13 | |
| 14 | // A token that was looked up is believed for a while, and then Postgres is asked again. |
| 15 | // The price is in the middle step: a user who is gone can still get in, until that while is over. |
| 16 | func TestAuthRemembers(t *testing.T) { |
| 17 | db := testdb.New(t) |
| 18 | ctx := context.Background() |
| 19 | hash := sha256.Sum256([]byte("secret")) |
| 20 | _, err := db.Exec(ctx, `insert into users (handle, token_hash) values ('alice', $1)`, hash[:]) |
| 21 | if err != nil { |
| 22 | t.Fatal(err) |
| 23 | } |
| 24 | h := New(db, nil) |
| 25 | h.Remember = time.Minute |
| 26 | clock := time.Now() |
| 27 | h.now = func() time.Time { return clock } |
| 28 | inside := h.Auth(func(w http.ResponseWriter, r *http.Request) {}) |
| 29 | ask := func() int { |
| 30 | rec := httptest.NewRecorder() |
| 31 | req := httptest.NewRequest("GET", "/feed", nil) |
| 32 | req.Header.Set("Authorization", "Bearer secret") |
| 33 | inside(rec, req) |
| 34 | return rec.Code |
| 35 | } |
| 36 | for _, step := range []struct { |
| 37 | name string |
| 38 | do func() |
| 39 | want int |
| 40 | }{ |
| 41 | {"the first request asks postgres", func() {}, 200}, |
| 42 | {"the user is deleted, and still remembered", func() { db.Exec(ctx, `delete from users`) }, 200}, |
| 43 | {"a minute later, postgres is asked again", func() { clock = clock.Add(61 * time.Second) }, 401}, |
| 44 | } { |
| 45 | step.do() |
| 46 | if got := ask(); got != step.want { |
| 47 | t.Errorf("%s: got %d, want %d", step.name, got, step.want) |
| 48 | } |
| 49 | } |
| 50 | } |