Skip to content

Commit

Permalink
Merge pull request #13 from portward/server-http-handler
Browse files Browse the repository at this point in the history
feat: AuthorizationServer implements http.Handler
  • Loading branch information
sagikazarmark authored Sep 25, 2023
2 parents 214c2e5 + ca7a865 commit 39bf0e0
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 17 deletions.
19 changes: 19 additions & 0 deletions auth/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,3 +175,22 @@ type rawOAuth2Request struct {
Password string `schema:"password"`
RefreshToken string `schema:"refresh_token"`
}

// ServeHTTP implements the [http.Handler] interface.
//
// Use it to register the AuthorizationServer directly as an HTTP handler.
// Otherwise, register the handler in an HTTP router directly:
// - GET / -> [AuthorizationServer.TokenHandler]
// - POST / -> [AuthorizationServer.OAuth2Handler]
func (s AuthorizationServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
s.TokenHandler(w, r)

case http.MethodPost:
s.OAuth2Handler(w, r)

default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
}
20 changes: 3 additions & 17 deletions auth/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,26 +109,12 @@ func TestAuthorizationServer(t *testing.T) {
Service: service,
}

router := http.NewServeMux()
router.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
server.TokenHandler(w, r)

case http.MethodPost:
server.OAuth2Handler(w, r)

default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
})

httpServer := httptest.NewServer(router)
httpServer := httptest.NewServer(server)

t.Run("TokenHandler", func(t *testing.T) {
t.Parallel()

request, err := http.NewRequest(http.MethodGet, httpServer.URL+"/token", nil)
request, err := http.NewRequest(http.MethodGet, httpServer.URL, nil)
require.NoError(t, err)

request.SetBasicAuth("user", "password")
Expand Down Expand Up @@ -275,7 +261,7 @@ func TestAuthorizationServer(t *testing.T) {
t.Run("Oauth2Handler", func(t *testing.T) {
t.Parallel()

request, err := http.NewRequest(http.MethodPost, httpServer.URL+"/token", nil)
request, err := http.NewRequest(http.MethodPost, httpServer.URL, nil)
require.NoError(t, err)

request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
Expand Down

0 comments on commit 39bf0e0

Please sign in to comment.