Skip to content

Commit

Permalink
Add server tests
Browse files Browse the repository at this point in the history
  • Loading branch information
LyricTian committed Jul 19, 2016
1 parent 794afb1 commit 5c03098
Show file tree
Hide file tree
Showing 12 changed files with 348 additions and 91 deletions.
90 changes: 29 additions & 61 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,110 +1,78 @@
基于Golang的OAuth2服务实现
=======================

> 完全模块化、支持http/fasthttp的服务端处理、令牌存储支持redis/mongodb
OAuth 2.0
=========
> [OAuth 2.0](http://oauth.net/2/) is the next evolution of the OAuth protocol which was originally created in late 2006.
[![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)

获取
----
Quick Start
-----------

### Download and install

``` bash
$ go get -u gopkg.in/oauth2.v3/...
```

HTTP服务端
--------
### Create file `server.go`

``` go
package main

import (
"log"
"net/http"

"gopkg.in/oauth2.v3/manage"
"gopkg.in/oauth2.v3/server"
"gopkg.in/oauth2.v3/store/client"
"gopkg.in/oauth2.v3/store/token"
)

func main() {
manager := manage.NewRedisManager(
&token.RedisConfig{Addr: "192.168.33.70:6379"},
)
manager.MapClientStorage(client.NewTempStore())
srv := server.NewServer(server.NewConfig(), manager)

srv.SetUserAuthorizationHandler(func(w http.ResponseWriter, r *http.Request) (userID string, err error) {
// validation and to get the user id
userID = "000000"
return
})
http.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) {
authReq, err := srv.GetAuthorizeRequest(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// TODO: 登录验证、授权处理
authReq.UserID = "000000"

err = srv.HandleAuthorizeRequest(w, authReq)
err := srv.HandleAuthorizeRequest(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
})

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)
}
})

log.Fatal(http.ListenAndServe(":9096", nil))
http.ListenAndServe(":9096", nil)
}

```

FastHTTP服务端
-------------

``` go
srv := server.NewFastServer(server.NewConfig(), manager)

fasthttp.ListenAndServe(":9096", func(ctx *fasthttp.RequestCtx) {
switch string(ctx.Request.URI().Path()) {
case "/authorize":
authReq, err := srv.GetAuthorizeRequest(ctx)
if err != nil {
ctx.Error(err.Error(), 400)
return
}
authReq.UserID = "000000"
// TODO: 登录验证、授权处理
err = srv.HandleAuthorizeRequest(ctx, authReq)
if err != nil {
ctx.Error(err.Error(), 400)
}
case "/token":
err := srv.HandleTokenRequest(ctx)
if err != nil {
ctx.Error(err.Error(), 400)
}
}
})
```

测试
----
> [goconvey](https://github.com/smartystreets/goconvey)
### Build and run

``` bash
$ goconvey -port=9092
$ go build server.go
$ ./server
```

范例
----
Features
--------

* Based on the [RFC 6749](https://tools.ietf.org/html/rfc6749) implementation
* Easy to use
* Modularity
* Flexible
* Elegant

模拟授权码模式的测试范例,请查看[example](/example)
Example
-------

Simulation examples of authorization code model, please check [example](/example)

License
-------
Expand Down
3 changes: 1 addition & 2 deletions example/server/main.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
package main

import (
"fmt"
"log"
"net/http"

"fmt"

"gopkg.in/oauth2.v3"
"gopkg.in/oauth2.v3/manage"
"gopkg.in/oauth2.v3/models"
Expand Down
5 changes: 3 additions & 2 deletions generates/access_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package generates
package generates_test

import (
"testing"
"time"

"gopkg.in/oauth2.v3"
"gopkg.in/oauth2.v3/generates"
"gopkg.in/oauth2.v3/models"

. "github.com/smartystreets/goconvey/convey"
Expand All @@ -20,7 +21,7 @@ func TestAccess(t *testing.T) {
UserID: "000000",
CreateAt: time.Now(),
}
gen := NewAccessGenerate()
gen := generates.NewAccessGenerate()
access, refresh, err := gen.Token(data, true)
So(err, ShouldBeNil)
So(access, ShouldNotBeEmpty)
Expand Down
5 changes: 3 additions & 2 deletions generates/authorize_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package generates
package generates_test

import (
"testing"
"time"

"gopkg.in/oauth2.v3"
"gopkg.in/oauth2.v3/generates"
"gopkg.in/oauth2.v3/models"

. "github.com/smartystreets/goconvey/convey"
Expand All @@ -20,7 +21,7 @@ func TestAuthorize(t *testing.T) {
UserID: "000000",
CreateAt: time.Now(),
}
gen := NewAuthorizeGenerate()
gen := generates.NewAuthorizeGenerate()
code, err := gen.Token(data)
So(err, ShouldBeNil)
So(code, ShouldNotBeEmpty)
Expand Down
14 changes: 7 additions & 7 deletions manage/manage_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package manage
package manage_test

import (
"testing"

"gopkg.in/oauth2.v3"
"gopkg.in/oauth2.v3/generates"
"gopkg.in/oauth2.v3/manage"
"gopkg.in/oauth2.v3/models"
"gopkg.in/oauth2.v3/store/client"
"gopkg.in/oauth2.v3/store/token"
Expand All @@ -14,7 +15,7 @@ import (

func TestManager(t *testing.T) {
Convey("Manager test", t, func() {
manager := NewManager()
manager := manage.NewManager()

manager.MapClientModel(models.NewClient())
manager.MapTokenModel(models.NewToken())
Expand Down Expand Up @@ -51,11 +52,10 @@ func testManager(manager oauth2.Manager) {
So(code, ShouldNotBeEmpty)

atParams := &oauth2.TokenGenerateRequest{
ClientID: reqParams.ClientID,
ClientSecret: "11",
RedirectURI: reqParams.RedirectURI,
Code: code,
IsGenerateRefresh: true,
ClientID: reqParams.ClientID,
ClientSecret: "11",
RedirectURI: reqParams.RedirectURI,
Code: code,
}
ati, err := manager.GenerateAccessToken(oauth2.AuthorizationCode, atParams)
So(err, ShouldBeNil)
Expand Down
4 changes: 4 additions & 0 deletions manage/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,10 @@ func (m *Manager) GenerateAccessToken(gt oauth2.GrantType, tgr *oauth2.TokenGene
if gt == oauth2.AuthorizationCode {
ti, terr := m.LoadAccessToken(tgr.Code)
if terr != nil {
if terr == errors.ErrInvalidAccessToken {
err = errors.ErrInvalidAuthorizeCode
return
}
err = terr
return
} else if ti.GetRedirectURI() != tgr.RedirectURI || ti.GetClientID() != tgr.ClientID {
Expand Down
6 changes: 4 additions & 2 deletions manage/util_test.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
package manage
package manage_test

import (
"testing"

"gopkg.in/oauth2.v3/manage"

. "github.com/smartystreets/goconvey/convey"
)

func TestUtil(t *testing.T) {
Convey("Util Test", t, func() {
Convey("ValidateURI Test", func() {
err := ValidateURI("http://www.example.com", "http://www.example.com/cb?code=xxx")
err := manage.ValidateURI("http://www.example.com", "http://www.example.com/cb?code=xxx")
So(err, ShouldBeNil)
})
})
Expand Down
16 changes: 13 additions & 3 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,10 @@ func (s *Server) HandleAuthorizeRequest(w http.ResponseWriter, r *http.Request)
ierr error
)
defer func() {
if verr := recover(); verr != nil {
err = fmt.Errorf("%v", verr)
return
}
data := s.GetErrorData(rerr, ierr)
if data != nil {
if req == nil {
Expand Down Expand Up @@ -303,8 +307,10 @@ func (s *Server) ValidationTokenRequest(r *http.Request) (gt oauth2.GrantType, t
ierr = err
return
}
tgr.ClientID = clientID
tgr.ClientSecret = clientSecret
tgr = &oauth2.TokenGenerateRequest{
ClientID: clientID,
ClientSecret: clientSecret,
}
switch gt {
case oauth2.AuthorizationCode:
tgr.RedirectURI = r.Form.Get("redirect_uri")
Expand Down Expand Up @@ -425,7 +431,7 @@ func (s *Server) GetTokenData(ti oauth2.TokenInfo) (data map[string]interface{})
data = map[string]interface{}{
"access_token": ti.GetAccess(),
"token_type": s.Config.TokenType,
"expires_in": ti.GetAccessExpiresIn() / time.Second,
"expires_in": int64(ti.GetAccessExpiresIn() / time.Second),
}
if scope := ti.GetScope(); scope != "" {
data["scope"] = scope
Expand All @@ -444,6 +450,10 @@ func (s *Server) HandleTokenRequest(w http.ResponseWriter, r *http.Request) (err
ierr error
)
defer func() {
if verr := recover(); verr != nil {
err = fmt.Errorf("%v", verr)
return
}
data := s.GetErrorData(rerr, ierr)
if data == nil {
data = s.GetTokenData(ti)
Expand Down
Loading

0 comments on commit 5c03098

Please sign in to comment.