Skip to content

Commit

Permalink
optimization of error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
LyricTian committed Aug 18, 2016
1 parent 51174a8 commit 0a49c2d
Show file tree
Hide file tree
Showing 6 changed files with 97 additions and 73 deletions.
36 changes: 17 additions & 19 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
Copyright (c) 2016, OAuth 2.0
All rights reserved.
MIT License

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Copyright (c) 2016 Lyric

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
35 changes: 26 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@

> An open protocol to allow secure authorization in a simple and standard method from web, mobile and desktop applications.
[![GoDoc](https://godoc.org/gopkg.in/oauth2.v3?status.svg)](https://godoc.org/gopkg.in/oauth2.v3)
[![Go Report Card](https://goreportcard.com/badge/gopkg.in/oauth2.v3)](https://goreportcard.com/report/gopkg.in/oauth2.v3)
[![Build Status](https://travis-ci.org/go-oauth2/oauth2.svg?branch=master)](https://travis-ci.org/go-oauth2/oauth2)
[![License][License-Image]][License-Url]
[![ReportCard][ReportCard-Image]][ReportCard-Url]
[![Build][Build-Status-Image]][Build-Status-Url]
[![GoDoc][GoDoc-Image]][GoDoc-Url]
[![Release][Release-Image]][Release-Url]

## Protocol Flow

Expand Down Expand Up @@ -42,6 +44,7 @@ $ go get -u gopkg.in/oauth2.v3/...
package main

import (
"fmt"
"net/http"

"gopkg.in/oauth2.v3/manage"
Expand All @@ -59,6 +62,10 @@ func main() {
srv := server.NewDefaultServer(manager)
srv.SetAllowGetAccessRequest(true)

srv.SetInternalErrorHandler(func(err error) {
fmt.Println("OAuth2 Error:",err.Error())
})

http.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) {
err := srv.HandleAuthorizeRequest(w, r)
if err != nil {
Expand All @@ -69,7 +76,7 @@ func main() {
http.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
err := srv.HandleTokenRequest(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})

Expand Down Expand Up @@ -114,15 +121,25 @@ http://localhost:9096/token?grant_type=clientcredentials&client_id=1&client_secr
Simulation examples of authorization code model, please check [example](/example)

## Storage implements
## Storage Implements

* [BuntDB](https://github.com/tidwall/buntdb)(The default storage)
* [Redis](https://github.com/go-oauth2/redis)
* [MongoDB](https://github.com/go-oauth2/mongo)

## License
## MIT License

```
Copyright (c) 2016, OAuth 2.0
All rights reserved.
```
Copyright (c) 2016 Lyric
```

[License-Url]: http://opensource.org/licenses/MIT
[License-Image]: https://img.shields.io/npm/l/express.svg
[Build-Status-Url]: https://travis-ci.org/go-oauth2/oauth2
[Build-Status-Image]: https://travis-ci.org/go-oauth2/oauth2.svg?branch=master
[Release-Url]: https://github.com/go-oauth2/oauth2/releases/tag/v3.4.8
[Release-image]: http://img.shields.io/badge/release-v3.4.8-1eb0fc.svg
[ReportCard-Url]: https://goreportcard.com/report/gopkg.in/oauth2.v3
[ReportCard-Image]: https://goreportcard.com/badge/gopkg.in/oauth2.v3
[GoDoc-Url]: https://godoc.org/gopkg.in/oauth2.v3
[GoDoc-Image]: https://godoc.org/gopkg.in/oauth2.v3?status.svg
16 changes: 12 additions & 4 deletions errors/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import "errors"

// Response error response
type Response struct {
Error error `json:"error"`
Description string `json:"error_description,omitempty"`
URI string `json:"error_uri,omitempty"`
StatusCode int `json:"-"`
Error error
ErrorCode int
Description string
URI string
StatusCode int
}

// https://tools.ietf.org/html/rfc6749#section-5.2
Expand Down Expand Up @@ -37,3 +38,10 @@ var Descriptions = map[error]string{
ErrInvalidGrant: "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client",
ErrUnsupportedGrantType: "The authorization grant type is not supported by the authorization server",
}

// StatusCodes response error HTTP status code
var StatusCodes = map[error]int{
ErrInvalidClient: 401,
ErrServerError: 500,
ErrTemporarilyUnavailable: 503,
}
2 changes: 1 addition & 1 deletion example/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func main() {
http.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
err := srv.HandleTokenRequest(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})

Expand Down
1 change: 0 additions & 1 deletion manage/manage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ func testManager(manager oauth2.Manager) {
}
cti, err := manager.GenerateAuthToken(oauth2.Code, reqParams)
So(err, ShouldBeNil)
Println(cti.GetCode())

code := cti.GetCode()
So(code, ShouldNotBeEmpty)
Expand Down
80 changes: 41 additions & 39 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,37 +55,33 @@ type Server struct {
AuthorizeScopeHandler AuthorizeScopeHandler
}

// response redirect error
func (s *Server) resRedirectError(w http.ResponseWriter, req *AuthorizeRequest, err error) (uerr error) {
func (s *Server) redirectError(w http.ResponseWriter, req *AuthorizeRequest, err error) (uerr error) {
if req == nil {
uerr = err
return
}
data, _ := s.GetErrorData(err)
err = s.resRedirect(w, req, data)
err = s.redirect(w, req, data)
return
}

func (s *Server) resRedirect(w http.ResponseWriter, req *AuthorizeRequest, data map[string]interface{}) (err error) {
uri, verr := s.GetRedirectURI(req, data)
if verr != nil {
err = verr
func (s *Server) redirect(w http.ResponseWriter, req *AuthorizeRequest, data map[string]interface{}) (err error) {
uri, err := s.GetRedirectURI(req, data)
if err != nil {
return
}
w.Header().Set("Location", uri)
w.WriteHeader(302)
return
}

// response token error
func (s *Server) resTokenError(w http.ResponseWriter, err error) (uerr error) {
func (s *Server) tokenError(w http.ResponseWriter, err error) (uerr error) {
data, statusCode := s.GetErrorData(err)
uerr = s.resToken(w, data, statusCode)
uerr = s.token(w, data, statusCode)
return
}

// response token
func (s *Server) resToken(w http.ResponseWriter, data map[string]interface{}, statusCode ...int) (err error) {
func (s *Server) token(w http.ResponseWriter, data map[string]interface{}, statusCode ...int) (err error) {
w.Header().Set("Content-Type", "application/json;charset=UTF-8")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Pragma", "no-cache")
Expand Down Expand Up @@ -157,18 +153,19 @@ func (s *Server) CheckResponseType(rt oauth2.ResponseType) bool {

// GetAuthorizeToken get authorization token(code)
func (s *Server) GetAuthorizeToken(req *AuthorizeRequest) (ti oauth2.TokenInfo, err error) {
if req.RedirectURI == "" ||
if req.ResponseType == "" {
err = errors.ErrUnsupportedResponseType
return
} else if req.RedirectURI == "" ||
req.ClientID == "" {
err = errors.ErrInvalidRequest
return
} else if req.ResponseType == "" {
err = errors.ErrUnsupportedResponseType
return
}
if allowed := s.CheckResponseType(req.ResponseType); !allowed {
err = errors.ErrUnauthorizedClient
return
}
// check the client allows the grant type
if fn := s.ClientAuthorizedHandler; fn != nil {
gt := oauth2.AuthorizationCode
if req.ResponseType == oauth2.Token {
Expand All @@ -183,6 +180,7 @@ func (s *Server) GetAuthorizeToken(req *AuthorizeRequest) (ti oauth2.TokenInfo,
return
}
}
// check the client allows the authorized scope
if fn := s.ClientScopeHandler; fn != nil {
allowed, verr := fn(req.ClientID, req.Scope)
if verr != nil {
Expand All @@ -194,13 +192,11 @@ func (s *Server) GetAuthorizeToken(req *AuthorizeRequest) (ti oauth2.TokenInfo,
}
}
tgr := &oauth2.TokenGenerateRequest{
ClientID: req.ClientID,
UserID: req.UserID,
RedirectURI: req.RedirectURI,
Scope: req.Scope,
}
if exp := req.AccessTokenExp; exp > 0 {
tgr.AccessTokenExp = exp
ClientID: req.ClientID,
UserID: req.UserID,
RedirectURI: req.RedirectURI,
Scope: req.Scope,
AccessTokenExp: req.AccessTokenExp,
}
ti, err = s.Manager.GenerateAuthToken(req.ResponseType, tgr)
return
Expand All @@ -222,13 +218,13 @@ func (s *Server) GetAuthorizeData(rt oauth2.ResponseType, ti oauth2.TokenInfo) (
func (s *Server) HandleAuthorizeRequest(w http.ResponseWriter, r *http.Request) (err error) {
req, verr := s.ValidationAuthorizeRequest(r)
if verr != nil {
err = s.resRedirectError(w, req, verr)
err = s.redirectError(w, req, verr)
return
}
// user authorization
userID, verr := s.UserAuthorizationHandler(w, r)
if verr != nil {
err = s.resRedirectError(w, req, verr)
err = s.redirectError(w, req, verr)
return
} else if userID == "" {
return
Expand All @@ -250,16 +246,15 @@ func (s *Server) HandleAuthorizeRequest(w http.ResponseWriter, r *http.Request)
if verr != nil {
err = verr
return
} else if exp > 0 {
req.AccessTokenExp = exp
}
req.AccessTokenExp = exp
}
ti, verr := s.GetAuthorizeToken(req)
if verr != nil {
err = s.resRedirectError(w, req, verr)
err = s.redirectError(w, req, verr)
return
}
err = s.resRedirect(w, req, s.GetAuthorizeData(req.ResponseType, ti))
err = s.redirect(w, req, s.GetAuthorizeData(req.ResponseType, ti))
return
}

Expand Down Expand Up @@ -433,15 +428,15 @@ func (s *Server) GetTokenData(ti oauth2.TokenInfo) (data map[string]interface{})
func (s *Server) HandleTokenRequest(w http.ResponseWriter, r *http.Request) (err error) {
gt, tgr, verr := s.ValidationTokenRequest(r)
if verr != nil {
err = s.resTokenError(w, verr)
err = s.tokenError(w, verr)
return
}
ti, verr := s.GetAccessToken(gt, tgr)
if verr != nil {
err = s.resTokenError(w, verr)
err = s.tokenError(w, verr)
return
}
err = s.resToken(w, s.GetTokenData(ti))
err = s.token(w, s.GetTokenData(ti))
return
}

Expand All @@ -453,24 +448,31 @@ func (s *Server) GetErrorData(err error) (data map[string]interface{}, statusCod
}
err = errors.ErrServerError
}
var re *errors.Response
re := &errors.Response{
Error: err,
Description: errors.Descriptions[err],
StatusCode: errors.StatusCodes[err],
}
if fn := s.ResponseErrorHandler; fn != nil {
re = fn(err)
} else {
re = &errors.Response{
Error: err,
Description: errors.Descriptions[err],
if vre := fn(err); vre != nil {
re = vre
}
}
data = map[string]interface{}{
"error": re.Error.Error(),
}
if v := re.ErrorCode; v != 0 {
data["error_code"] = v
}
if v := re.Description; v != "" {
data["error_description"] = v
}
if v := re.URI; v != "" {
data["error_uri"] = v
}
statusCode = re.StatusCode
statusCode = 400
if v := re.StatusCode; v > 0 {
statusCode = v
}
return
}

0 comments on commit 0a49c2d

Please sign in to comment.