github.com/zooyer/miskit@v1.0.71/oauth2/oauth2_test.go (about)

     1  package oauth2
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"net/url"
     7  	"testing"
     8  	"time"
     9  
    10  	"github.com/zooyer/miskit/log"
    11  	"github.com/zooyer/miskit/zrpc"
    12  )
    13  
    14  type GithubError struct {
    15  	ErrorName        string `json:"error,omitempty"`
    16  	ErrorDescription string `json:"error_description,omitempty"`
    17  	ErrorURI         string `json:"error_uri,omitempty"`
    18  }
    19  
    20  func (e GithubError) Error() string {
    21  	return e.ErrorDescription
    22  }
    23  
    24  type GithubToken struct {
    25  	*GithubError
    26  	AccessToken string          `json:"access_token"`
    27  	TokenType   string          `json:"token_type"`
    28  	Scope       string          `json:"scope,omitempty"`
    29  	Raw         json.RawMessage `json:"raw,omitempty"`
    30  }
    31  
    32  func (t *GithubToken) Parse(data []byte) (token *Token, err error) {
    33  	//values, err := url.ParseQuery(string(data))
    34  	//if err != nil {
    35  	//	return
    36  	//}
    37  	//
    38  	//t.AccessToken = values.Get("access_token")
    39  	//t.TokenType = values.Get("token_type")
    40  	//t.Scope = values.Get("scope")
    41  	//t.Raw = data
    42  
    43  	t.Raw = data
    44  	if err = json.Unmarshal(data, t); err != nil {
    45  		return
    46  	}
    47  
    48  	if t.ErrorName != "" {
    49  		return nil, t.GithubError
    50  	}
    51  
    52  	token = new(Token)
    53  	token.AccessToken = t.AccessToken
    54  	token.TokenType = t.TokenType
    55  	token.Scope = t.Scope
    56  	token.Raw = t
    57  
    58  	return
    59  }
    60  
    61  type wechat struct{}
    62  
    63  func (wechat) AuthCodeParams(ctx context.Context, config Config, state string) string {
    64  	var values = url.Values{
    65  		"appid":         {config.ClientID},
    66  		"response_type": {"code"},
    67  	}
    68  
    69  	if config.RedirectURI != "" {
    70  		values.Set("redirect_uri", config.RedirectURI)
    71  	}
    72  
    73  	if config.Scope != "" {
    74  		values.Set("scope", config.Scope)
    75  	}
    76  
    77  	if state != "" {
    78  		values.Set("state", state)
    79  	}
    80  
    81  	return values.Encode() + "#wechat_redirect"
    82  }
    83  
    84  func (wechat) AuthCodeTokenParams(ctx context.Context, config Config, code string) map[string]string {
    85  	var values = map[string]string{
    86  		"grant_type": "authorization_code",
    87  		"code":       code,
    88  		"appid":      config.ClientID,
    89  		"secret":     config.ClientSecret,
    90  	}
    91  
    92  	return values
    93  }
    94  
    95  func (wechat) PasswordTokenParams(ctx context.Context, config Config, username, password string) map[string]string {
    96  	panic("implement")
    97  }
    98  
    99  func (wechat) RefreshTokenParams(ctx context.Context, config Config, refreshToken string) map[string]string {
   100  	var values = map[string]string{
   101  		"grant_type":    "refresh_token",
   102  		"refresh_token": refreshToken,
   103  		"appid":         config.ClientID,
   104  	}
   105  
   106  	return values
   107  }
   108  
   109  func (wechat) ClientCredentialsParams(ctx context.Context, config Config) map[string]string {
   110  	panic("implement")
   111  }
   112  
   113  type WechatError struct {
   114  	Errcode int    `json:"errcode"`
   115  	Errmsg  string `json:"errmsg"`
   116  }
   117  
   118  func (e WechatError) Error() string {
   119  	return e.Errmsg
   120  }
   121  
   122  type WechatToken struct {
   123  	*WechatError
   124  	AccessToken  string `json:"access_token"`
   125  	RefreshToken string `json:"refresh_token"`
   126  	ExpiresIn    int64  `json:"expires_in"`
   127  	Openid       string `json:"openid"`
   128  	Scope        string `json:"scope"`
   129  }
   130  
   131  func (wt *WechatToken) Parse(data []byte) (token *Token, err error) {
   132  	if err = json.Unmarshal(data, wt); err != nil {
   133  		return
   134  	}
   135  
   136  	if wt.WechatError != nil {
   137  		return nil, wt.WechatError
   138  	}
   139  
   140  	token = &Token{
   141  		AccessToken:  wt.AccessToken,
   142  		TokenType:    "",
   143  		RefreshToken: wt.RefreshToken,
   144  		ExpiresIn:    wt.ExpiresIn,
   145  		Scope:        wt.Scope,
   146  		Raw:          data,
   147  	}
   148  
   149  	return
   150  }
   151  
   152  func TestGithub(t *testing.T) {
   153  	var step = 1
   154  	var config = Config{
   155  		ClientID:     "42c54212574100f363a25b3",
   156  		ClientSecret: "24755362f634b63e30c09412b4d99e20bf6d2593",
   157  		Endpoint: Endpoint{
   158  			AuthorizeURL:    "https://github.com/login/oauth/authorize",
   159  			AccessTokenURL:  "https://github.com/login/oauth/access_token",
   160  			RefreshTokenURL: "https://github.com/login/oauth/access_token",
   161  		},
   162  		RedirectURI: "http://i.genkitol.com:8000/oauth/callback",
   163  		Scope:       "user",
   164  	}
   165  
   166  	var (
   167  		ctx = context.Background()
   168  		cfg = log.Config{
   169  			Output: "stdout",
   170  			Level:  "DEBUG",
   171  		}
   172  		logger, _ = log.New(cfg, log.TextFormatter(true))
   173  		rpc       = zrpc.New("test", 2, time.Second*5, logger, func(ctx context.Context, req *zrpc.Request) {
   174  			req.Header.Set("Accept", "application/json")
   175  		})
   176  	)
   177  
   178  	var client = NewClient(rpc, config)
   179  
   180  	if step == 1 {
   181  		t.Log(client.AuthCodeURL(ctx))
   182  	}
   183  
   184  	if step == 2 {
   185  		var code = "7fd9f85398f7fe6955fe"
   186  
   187  		var tk GithubToken
   188  
   189  		token, err := client.AuthorizationCodeToken(ctx, code, &tk)
   190  		if err != nil {
   191  			t.Logf("%#v", err)
   192  			t.Fatal(err)
   193  		}
   194  
   195  		var data []byte
   196  
   197  		if data, err = json.Marshal(token); err != nil {
   198  			t.Fatal(err)
   199  		}
   200  		t.Log(string(data))
   201  
   202  		if data, err = json.Marshal(tk); err != nil {
   203  			t.Fatal(err)
   204  		}
   205  		t.Log(string(data))
   206  	}
   207  }
   208  
   209  func TestWechat(t *testing.T) {
   210  	var step = 3
   211  	var config = Config{
   212  		ClientID:     "wxd14f8452d626921567",
   213  		ClientSecret: "0a44a854115b0e635124afd24183e7",
   214  		Endpoint: Endpoint{
   215  			AuthorizeURL:    "https://open.weixin.qq.com/connect/oauth2/authorize",
   216  			AccessTokenURL:  "https://api.weixin.qq.com/sns/oauth2/access_token",
   217  			RefreshTokenURL: "https://api.weixin.qq.com/sns/oauth2/refresh_token",
   218  			// 验证token https://api.weixin.qq.com/sns/auth
   219  		},
   220  		RedirectURI: "http://i.genkitol.com/oauth/callback",
   221  		Scope:       "snsapi_userinfo",
   222  		Formatter:   QueryFormatter,
   223  		Parameter:   wechat{},
   224  	}
   225  
   226  	var (
   227  		ctx = context.Background()
   228  		cfg = log.Config{
   229  			Output: "stdout",
   230  			Level:  "DEBUG",
   231  		}
   232  		logger, _ = log.New(cfg, log.TextFormatter(true))
   233  		rpc       = zrpc.New("test", 2, time.Second*5, logger, func(ctx context.Context, req *zrpc.Request) {
   234  			req.Header.Set("Accept", "application/json")
   235  		})
   236  	)
   237  
   238  	var client = NewClient(rpc, config)
   239  	if step == 1 {
   240  		t.Log(client.AuthCodeURL(ctx))
   241  	}
   242  
   243  	if step == 2 {
   244  		var code = "nzC9D1a051a8f80q6uFrjFa1xo4arjFq"
   245  
   246  		var tk WechatToken
   247  
   248  		token, err := client.AuthorizationCodeToken(ctx, code, &tk)
   249  		if err != nil {
   250  			t.Logf("%#v", err)
   251  			t.Fatal(err)
   252  		}
   253  
   254  		var data []byte
   255  
   256  		if data, err = json.Marshal(token); err != nil {
   257  			t.Fatal(err)
   258  		}
   259  		t.Log(string(data))
   260  
   261  		if data, err = json.Marshal(tk); err != nil {
   262  			t.Fatal(err)
   263  		}
   264  		t.Log(string(data))
   265  	}
   266  
   267  	if step == 3 {
   268  		const refreshToken = "56fpXAlVQUbrZcleT0IjnJcHtbcXPLQ_E71lsfHSfdtupKSFJS28HH_TnFDhda_lV8T6e6wPf6AAtTgeA"
   269  
   270  		var tk WechatToken
   271  		token, err := client.RefreshToken(ctx, refreshToken, &tk)
   272  		if err != nil {
   273  			t.Logf("%#v", err)
   274  			t.Fatal(err)
   275  		}
   276  
   277  		var data []byte
   278  
   279  		if data, err = json.Marshal(token); err != nil {
   280  			t.Fatal(err)
   281  		}
   282  		t.Log(string(data))
   283  
   284  		if data, err = json.Marshal(tk); err != nil {
   285  			t.Fatal(err)
   286  		}
   287  		t.Log(string(data))
   288  	}
   289  }