| 1 | package auth |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "io" |
| 6 | "net/http" |
| 7 | "net/http/httptest" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | ) |
| 11 | |
| 12 | func TestExchangeUsesAuthorizationCode(t *testing.T) { |
| 13 | var gotBody, gotAgent, gotAccept string |
| 14 | srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 15 | gotAgent = r.Header.Get("User-Agent") |
| 16 | gotAccept = r.Header.Get("Accept") |
| 17 | w.Header().Set("Content-Type", "application/json") |
| 18 | switch r.URL.Path { |
| 19 | case "/oauth/token": |
| 20 | b, _ := io.ReadAll(r.Body) |
| 21 | gotBody = string(b) |
| 22 | _, _ = w.Write([]byte(`{"access_token":"tok","token_type":"Bearer","expires_in":86400,"user":{"id":7,"username":"Tim","avatar_url":"https://auth.timfalken.com/avatar/7?v=1"}}`)) |
| 23 | case "/api/me": |
| 24 | if r.Header.Get("Authorization") != "Bearer tok" { |
| 25 | t.Errorf("bearer %s", r.Header.Get("Authorization")) |
| 26 | } |
| 27 | _, _ = w.Write([]byte(`{"user":{"id":7,"username":"tim","is_admin":false,"email_verified":true,"avatar_url":"https://auth.timfalken.com/avatar/7?v=1"}}`)) |
| 28 | default: |
| 29 | http.NotFound(w, r) |
| 30 | } |
| 31 | })) |
| 32 | defer srv.Close() |
| 33 | client := NewTimFalken(srv.URL, "git.timfalken.com", "geheim", "BlueGitAccountClient/0.1") |
| 34 | id, err := client.Exchange(context.Background(), "code-1", "https://git.timfalken.com/auth/callback", "") |
| 35 | if err != nil { |
| 36 | t.Fatal(err) |
| 37 | } |
| 38 | if id.AuthID != 7 || id.Username != "tim" || id.AccessToken != "tok" || !id.EmailVerified { |
| 39 | t.Fatalf("%+v", id) |
| 40 | } |
| 41 | if !strings.Contains(gotBody, "grant_type=authorization_code") || !strings.Contains(gotBody, "client_id=git.timfalken.com") || !strings.Contains(gotBody, "code=code-1") { |
| 42 | t.Fatalf("body %s", gotBody) |
| 43 | } |
| 44 | if gotAgent != "BlueGitAccountClient/0.1" || gotAccept != "application/json" { |
| 45 | t.Fatalf("headers %s %s", gotAgent, gotAccept) |
| 46 | } |
| 47 | url := client.AuthorizeURL("state-1", "nonce-1", "https://git.timfalken.com/auth/callback") |
| 48 | if !strings.Contains(url, "/oauth/authorize?") || !strings.Contains(url, "state=state-1") { |
| 49 | t.Fatal(url) |
| 50 | } |
| 51 | } |