|
| 1 | +package tokenauth |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "net/http/httptest" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "github.com/octavore/nagax/users" |
| 9 | +) |
| 10 | + |
| 11 | +type dummyTokenSource map[string]string |
| 12 | + |
| 13 | +func (d *dummyTokenSource) Get(k string) *string { |
| 14 | + v, ok := (*d)[k] |
| 15 | + if !ok { |
| 16 | + return nil |
| 17 | + } |
| 18 | + return &v |
| 19 | +} |
| 20 | + |
| 21 | +func setup() (*Module, *httptest.ResponseRecorder, *http.Request) { |
| 22 | + m := &Module{ |
| 23 | + tokenSource: &dummyTokenSource{"goodToken": "1234"}, |
| 24 | + header: defaultHTTPHeader, |
| 25 | + prefix: defaultTokenPrefix, |
| 26 | + } |
| 27 | + return m, httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil) |
| 28 | +} |
| 29 | + |
| 30 | +func TestAuthenticateGoodToken(t *testing.T) { |
| 31 | + m, rw, req := setup() |
| 32 | + req.Header.Set(defaultHTTPHeader, "Token goodToken") |
| 33 | + b, s, err := m.Authenticate(rw, req) |
| 34 | + if err != nil { |
| 35 | + t.Fatal("unexpected error", err) |
| 36 | + } |
| 37 | + if !b { |
| 38 | + t.Error("unexpected value", b) |
| 39 | + } |
| 40 | + if s == nil { |
| 41 | + t.Error("unexpected value", s) |
| 42 | + } else if *s != "1234" { |
| 43 | + t.Error("unexpected value", *s) |
| 44 | + } |
| 45 | + |
| 46 | + // different capitalization for prefix |
| 47 | + m, rw, req = setup() |
| 48 | + req.Header.Set(defaultHTTPHeader, "tOkEn goodToken") |
| 49 | + b, s, err = m.Authenticate(rw, req) |
| 50 | + if err != nil { |
| 51 | + t.Fatal("unexpected error", err) |
| 52 | + } |
| 53 | + if !b { |
| 54 | + t.Error("unexpected value", b) |
| 55 | + } |
| 56 | + if s == nil { |
| 57 | + t.Error("unexpected value", s) |
| 58 | + } else if *s != "1234" { |
| 59 | + t.Error("unexpected value", *s) |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +func TestAuthenticateBadPrefix(t *testing.T) { |
| 64 | + m, rw, req := setup() |
| 65 | + req.Header.Set(defaultHTTPHeader, "Basic badToken") |
| 66 | + |
| 67 | + // returns false (not authenticated) but without an error |
| 68 | + b, s, err := m.Authenticate(rw, req) |
| 69 | + if err != nil { |
| 70 | + t.Fatal("unexpected error", nil) |
| 71 | + } |
| 72 | + if b { |
| 73 | + t.Error("unexpected value", b) |
| 74 | + } |
| 75 | + if s != nil { |
| 76 | + t.Error("unexpected value", *s) |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +func TestAuthenticateBadToken(t *testing.T) { |
| 81 | + m, rw, req := setup() |
| 82 | + req.Header.Set(defaultHTTPHeader, "Token badToken") |
| 83 | + // returns false (not authenticated) with an error |
| 84 | + b, s, err := m.Authenticate(rw, req) |
| 85 | + if err != users.ErrNotAuthorized { |
| 86 | + t.Fatal("unexpected error", err) |
| 87 | + } |
| 88 | + if b { |
| 89 | + t.Error("unexpected value", b) |
| 90 | + } |
| 91 | + if s != nil { |
| 92 | + t.Error("unexpected value", *s) |
| 93 | + } |
| 94 | +} |
0 commit comments