api_auth_test.go (1635B)
1 package internal 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "net/http" 7 "net/http/cookiejar" 8 "net/http/httptest" 9 "testing" 10 ) 11 12 func TestSignupLoginLogoutSession(t *testing.T) { 13 t.Parallel() 14 db, err := OpenAtPath(t.Context(), t.TempDir()+"/authz.db") 15 if err != nil { 16 t.Fatalf("open: %v", err) 17 } 18 t.Cleanup(func() { _ = db.Close() }) 19 h, _ := NewHandler(db) 20 srv := httptest.NewServer(h) 21 defer srv.Close() 22 23 jar, _ := cookiejar.New(nil) 24 client := &http.Client{Jar: jar} 25 26 // /bookmarks unauth should be 401 27 resp, _ := http.Get(srv.URL + "/bookmarks") 28 if resp.StatusCode != http.StatusUnauthorized { 29 t.Fatalf("/bookmarks unauth got %d", resp.StatusCode) 30 } 31 32 // signup 33 b, _ := json.Marshal(map[string]string{"username": "bob", "password": "pw"}) 34 r, _ := http.NewRequest(http.MethodPost, srv.URL+"/signup", bytes.NewReader(b)) 35 r.Header.Set("Content-Type", "application/json") 36 rs, _ := client.Do(r) 37 if rs.StatusCode != http.StatusOK { 38 t.Fatalf("signup status %d", rs.StatusCode) 39 } 40 rs.Body.Close() 41 42 // /bookmarks auth should be 200 (empty list) 43 r2, _ := client.Get(srv.URL + "/bookmarks") 44 if r2.StatusCode != http.StatusOK { 45 t.Fatalf("/bookmarks auth %d", r2.StatusCode) 46 } 47 r2.Body.Close() 48 49 // logout 50 r3, _ := http.NewRequest(http.MethodPost, srv.URL+"/logout", nil) 51 rs3, _ := client.Do(r3) 52 if rs3.StatusCode != http.StatusNoContent { 53 t.Fatalf("logout %d", rs3.StatusCode) 54 } 55 rs3.Body.Close() 56 57 // /bookmarks after logout should be 401 again 58 r4, _ := client.Get(srv.URL + "/bookmarks") 59 if r4.StatusCode != http.StatusUnauthorized { 60 t.Fatalf("/bookmarks after logout %d", r4.StatusCode) 61 } 62 r4.Body.Close() 63 }