Repository: markbates/goth
Pull request #418 (2021-08-11 06:39:21)

Add WeCom provider
[WeCom](https://work.weixin.qq.com/) is a popular business communication app in China.

This PR added support for WeCom's [QR Login](https://work.weixin.qq.com/api/doc/90000/90135/90988) support as a provider


Patch:
diff --git a/README.md b/README.md
index d3f1088..0131d9c 100644
--- a/README.md
+++ b/README.md
@@ -70,6 +70,7 @@ $ go get github.com/markbates/goth
 * Uber
 * VK
 * Wepay
+* WeCom
 * Xero
 * Yahoo
 * Yammer
diff --git a/examples/main.go b/examples/main.go
index c56119c..4bcac5b 100644
--- a/examples/main.go
+++ b/examples/main.go
@@ -3,13 +3,11 @@ package main
 import (
 	"fmt"
 	"html/template"
+	"log"
 	"net/http"
 	"os"
-
 	"sort"
 
-	"log"
-
 	"github.com/gorilla/pat"
 	"github.com/markbates/goth"
 	"github.com/markbates/goth/gothic"
@@ -63,6 +61,7 @@ import (
 	"github.com/markbates/goth/providers/typetalk"
 	"github.com/markbates/goth/providers/uber"
 	"github.com/markbates/goth/providers/vk"
+	"github.com/markbates/goth/providers/wecom"
 	"github.com/markbates/goth/providers/wepay"
 	"github.com/markbates/goth/providers/xero"
 	"github.com/markbates/goth/providers/yahoo"
@@ -136,6 +135,7 @@ func main() {
 		strava.New(os.Getenv("STRAVA_KEY"), os.Getenv("STRAVA_SECRET"), "http://localhost:3000/auth/strava/callback"),
 		okta.New(os.Getenv("OKTA_ID"), os.Getenv("OKTA_SECRET"), os.Getenv("OKTA_ORG_URL"), "http://localhost:3000/auth/okta/callback", "openid", "profile", "email"),
 		mastodon.New(os.Getenv("MASTODON_KEY"), os.Getenv("MASTODON_SECRET"), "http://localhost:3000/auth/mastodon/callback", "read:accounts"),
+		wecom.New(os.Getenv("WECOM_CORP_ID"), os.Getenv("WECOM_SECRET"), os.Getenv("WECOM_AGENT_ID"), "http://localhost:3000/auth/wecom/callback"),
 	)
 
 	// OpenID Connect is based on OpenID Connect Auto Discovery URL (https://openid.net/specs/openid-connect-discovery-1_0-17.html)
@@ -202,6 +202,7 @@ func main() {
 	m["strava"] = "Strava"
 	m["okta"] = "Okta"
 	m["mastodon"] = "Mastodon"
+	m["wecom"] = "WeCom"
 
 	var keys []string
 	for k := range m {
diff --git a/providers/wecom/session.go b/providers/wecom/session.go
new file mode 100644
index 0000000..49ae5ba
--- /dev/null
+++ b/providers/wecom/session.go
@@ -0,0 +1,55 @@
+package wecom
+
+import (
+	"encoding/json"
+	"errors"
+	"strings"
+
+	"github.com/markbates/goth"
+)
+
+// Session stores data during the auth process with WeCom.
+type Session struct {
+	AuthURL     string
+	AccessToken string
+	UserID      string
+}
+
+// GetAuthURL will return the URL set by calling the `BeginAuth` function on the WeCom provider.
+func (s Session) GetAuthURL() (string, error) {
+	if s.AuthURL == "" {
+		return "", errors.New(goth.NoAuthUrlErrorMessage)
+	}
+	return s.AuthURL, nil
+}
+
+// Authorize the session with WeCom and return the access token to be stored for future use.
+func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {
+	p := provider.(*Provider)
+	token, err := p.fetchToken()
+	if err != nil {
+		return "", err
+	}
+	s.AccessToken = token.AccessToken
+
+	userID, err := p.fetchUserID(s, params.Get("code"))
+	if err != nil {
+		return "", err
+	}
+	s.UserID = userID
+
+	return s.AccessToken, nil
+}
+
+// Marshal the session into a string
+func (s Session) Marshal() string {
+	b, _ := json.Marshal(s)
+	return string(b)
+}
+
+// UnmarshalSession will unmarshal a JSON string into a session.
+func (p *Provider) UnmarshalSession(data string) (goth.Session, error) {
+	sess := &Session{}
+	err := json.NewDecoder(strings.NewReader(data)).Decode(sess)
+	return sess, err
+}
diff --git a/providers/wecom/wecom.go b/providers/wecom/wecom.go
new file mode 100644
index 0000000..5d7e0f2
--- /dev/null
+++ b/providers/wecom/wecom.go
@@ -0,0 +1,217 @@
+// Package wecom implements the qrConnect protocol for authenticating users through WeCom.
+// Reference: https://work.weixin.qq.com/api/doc/90000/90135/90988
+package wecom
+
+import (
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"net/http"
+	"net/url"
+	"time"
+
+	"github.com/markbates/goth"
+	"golang.org/x/oauth2"
+)
+
+var (
+	AuthURL = "https://open.work.weixin.qq.com/wwopen/sso/qrConnect"
+	BaseURL = "https://qyapi.weixin.qq.com/cgi-bin"
+)
+
+// New creates a new WeCom provider, and sets up important connection details.
+func New(corpID, secret, agentID, callbackURL string) *Provider {
+	return &Provider{
+		ClientKey:    corpID,
+		Secret:       secret,
+		AgentID:      agentID,
+		CallbackURL:  callbackURL,
+		providerName: "wecom",
+		authURL:      AuthURL,
+		baseURL:      BaseURL,
+	}
+}
+
+// Provider is the implementation of `goth.Provider` for accessing WeCom.
+type Provider struct {
+	ClientKey    string
+	Secret       string
+	AgentID      string
+	CallbackURL  string
+	HTTPClient   *http.Client
+	providerName string
+
+	// token caches the access_token
+	token *oauth2.Token
+
+	authURL string
+	baseURL string
+}
+
+// Name is the name used to retrieve this provider later.
+func (p *Provider) Name() string {
+	return p.providerName
+}
+
+// SetName is to update the name of the provider (needed in case of multiple providers of 1 type)
+func (p *Provider) SetName(name string) {
+	p.providerName = name
+}
+
+func (p *Provider) Client() *http.Client {
+	return goth.HTTPClientWithFallBack(p.HTTPClient)
+}
+
+// Debug is a no-op for the wecom package.
+func (p *Provider) Debug(debug bool) {}
+
+// BeginAuth asks WeCom for an authentication end-point.
+func (p *Provider) BeginAuth(state string) (goth.Session, error) {
+	params := url.Values{}
+	params.Add("appid", p.ClientKey)
+	params.Add("agentid", p.AgentID)
+	params.Add("state", state)
+	params.Add("redirect_uri", p.CallbackURL)
+	session := &Session{
+		AuthURL: fmt.Sprintf("%s?%s", p.authURL, params.Encode()),
+	}
+	return session, nil
+}
+
+// FetchUser will go to WeCom and access basic information about the user.
+func (p *Provider) FetchUser(session goth.Session) (goth.User, error) {
+	sess := session.(*Session)
+	user := goth.User{
+		AccessToken: sess.AccessToken,
+		Provider:    p.Name(),
+	}
+
+	if user.AccessToken == "" {
+		return user, fmt.Errorf("%s cannot get user information without accessToken", p.providerName)
+	}
+
+	params := url.Values{}
+	params.Add("access_token", user.AccessToken)
+	params.Add("userid", sess.UserID)
+	resp, err := p.Client().Get(fmt.Sprintf("%s/user/get?%s", p.baseURL, params.Encode()))
+	if err != nil {
+		return user, err
+	}
+	defer resp.Body.Close()
+	if resp.StatusCode != http.StatusOK {
+		return user, fmt.Errorf("wecom /user/get returns code: %d", resp.StatusCode)
+	}
+
+	if err := userFromReader(resp.Body, &user); err != nil {
+		return user, err
+	}
+
+	return user, nil
+}
+
+// RefreshToken refresh token is not provided by WeCom
+func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) {
+	return nil, errors.New("refresh token is not provided by wecom")
+}
+
+// RefreshTokenAvailable refresh token is not provided by WeCom
+func (p *Provider) RefreshTokenAvailable() bool {
+	return false
+}
+
+func (p *Provider) fetchToken() (*oauth2.Token, error) {
+	if p.token != nil && p.token.Valid() {
+		return p.token, nil
+	}
+
+	params := url.Values{}
+	params.Add("corpid", p.ClientKey)
+	params.Add("corpsecret", p.Secret)
+	resp, err := p.Client().Get(fmt.Sprintf("%s/gettoken?%s", p.baseURL, params.Encode()))
+	if err != nil {
+		return nil, err
+	}
+	defer resp.Body.Close()
+	if resp.StatusCode != http.StatusOK {
+		return nil, fmt.Errorf("wecom /gettoken returns code: %d", resp.StatusCode)
+	}
+
+	obj := struct {
+		AccessToken string        `json:"access_token"`
+		ExpiresIn   time.Duration `json:"expires_in"`
+		Code        int           `json:"errcode"`
+		Msg         string        `json:"errmsg"`
+	}{}
+	if err = json.NewDecoder(resp.Body).Decode(&obj); err != nil {
+		return nil, err
+	}
+	if obj.Code != 0 {
+		return nil, fmt.Errorf("CODE: %d, MSG: %s", obj.Code, obj.Msg)
+	}
+
+	p.token = &oauth2.Token{
+		AccessToken: obj.AccessToken,
+		Expiry: time.Now().Add(obj.ExpiresIn * time.Second),
+	}
+
+	return p.token, nil
+}
+
+func (p *Provider) fetchUserID(session goth.Session, code string) (string, error) {
+	sess := session.(*Session)
+	params := url.Values{}
+	params.Add("access_token", sess.AccessToken)
+	params.Add("code", code)
+	resp, err := p.Client().Get(fmt.Sprintf("%s/user/getuserinfo?%s", p.baseURL, params.Encode()))
+	if err != nil {
+		return "", err
+	}
+	defer resp.Body.Close()
+	if resp.StatusCode != http.StatusOK {
+		return "", fmt.Errorf("wecom /getuserinfo returns code: %d", resp.StatusCode)
+	}
+
+	obj := struct {
+		UserId string `json:"UserId"`
+		Code   int    `json:"errcode"`
+		Msg    string `json:"errmsg"`
+	}{}
+	if err = json.NewDecoder(resp.Body).Decode(&obj); err != nil {
+		return "", err
+	}
+	if obj.Code != 0 {
+		return "", fmt.Errorf("CODE: %d, MSG: %s", obj.Code, obj.Msg)
+	}
+
+	return obj.UserId, nil
+}
+
+func userFromReader(reader io.Reader, user *goth.User) error {
+	obj := struct {
+		UserId  string `json:"userid"`
+		Name    string `json:"name"`
+		Email   string `json:"email"`
+		Alias   string `json:"alias"`
+		Avatar  string `json:"avatar"`
+		Address string `json:"address"`
+		Code    int    `json:"errcode"`
+		Msg     string `json:"errmsg"`
+	}{}
+
+	if err := json.NewDecoder(reader).Decode(&obj); err != nil {
+		return err
+	}
+	if obj.Code != 0 {
+		return fmt.Errorf("CODE: %d, MSG: %s", obj.Code, obj.Msg)
+	}
+
+	user.Name = obj.Name
+	user.NickName = obj.Alias
+	user.Email = obj.Email
+	user.UserID = obj.UserId
+	user.AvatarURL = obj.Avatar
+	user.Location = obj.Address
+
+	return nil
+}


Test patch:
diff --git a/providers/wecom/session_test.go b/providers/wecom/session_test.go
new file mode 100644
index 0000000..2ba260a
--- /dev/null
+++ b/providers/wecom/session_test.go
@@ -0,0 +1,40 @@
+package wecom_test
+
+import (
+	"testing"
+
+	"github.com/markbates/goth"
+	"github.com/markbates/goth/providers/wecom"
+	"github.com/stretchr/testify/assert"
+)
+
+func Test_Implements_Session(t *testing.T) {
+	t.Parallel()
+	a := assert.New(t)
+	s := &wecom.Session{}
+
+	a.Implements((*goth.Session)(nil), s)
+}
+
+func Test_GetAuthURL(t *testing.T) {
+	t.Parallel()
+	a := assert.New(t)
+	s := &wecom.Session{}
+
+	_, err := s.GetAuthURL()
+	a.Error(err)
+
+	s.AuthURL = "/foo"
+
+	url, _ := s.GetAuthURL()
+	a.Equal(url, "/foo")
+}
+
+func Test_Marshal(t *testing.T) {
+	t.Parallel()
+	a := assert.New(t)
+	s := &wecom.Session{}
+
+	data := s.Marshal()
+	a.Equal(data, `{"AuthURL":"","AccessToken":"","UserID":""}`)
+}
diff --git a/providers/wecom/wecom_test.go b/providers/wecom/wecom_test.go
new file mode 100644
index 0000000..2e44575
--- /dev/null
+++ b/providers/wecom/wecom_test.go
@@ -0,0 +1,61 @@
+package wecom_test
+
+import (
+	"fmt"
+	"os"
+	"testing"
+
+	"github.com/markbates/goth"
+	"github.com/markbates/goth/providers/wecom"
+	"github.com/stretchr/testify/assert"
+)
+
+func Test_Implements_Provider(t *testing.T) {
+	t.Parallel()
+	a := assert.New(t)
+
+	a.Implements((*goth.Provider)(nil), wecomProvider())
+}
+
+func Test_New(t *testing.T) {
+	t.Parallel()
+	a := assert.New(t)
+
+	provider := wecomProvider()
+	a.Equal(provider.ClientKey, os.Getenv("WECOM_CORP_ID"))
+	a.Equal(provider.Secret, os.Getenv("WECOM_SECRET"))
+	a.Equal(provider.AgentID, os.Getenv("WECOM_AGENT_ID"))
+	a.Equal(provider.CallbackURL, "/foo")
+}
+
+func TestBeginAuth(t *testing.T) {
+	t.Parallel()
+	a := assert.New(t)
+
+	provider := wecomProvider()
+	session, err := provider.BeginAuth("test_state")
+	s := session.(*wecom.Session)
+	a.NoError(err)
+	a.Contains(s.AuthURL, "https://open.work.weixin.qq.com/wwopen/sso/qrConnect")
+	a.Contains(s.AuthURL, fmt.Sprintf("appid=%s", os.Getenv("WECOM_CORP_ID")))
+	a.Contains(s.AuthURL, fmt.Sprintf("agentid=%s", os.Getenv("WECOM_AGENT_ID")))
+	a.Contains(s.AuthURL, "state=test_state")
+}
+
+func Test_SessionFromJSON(t *testing.T) {
+	t.Parallel()
+	a := assert.New(t)
+
+	provider := wecomProvider()
+
+	s, err := provider.UnmarshalSession(`{"AuthURL":"http://wecom/auth_url","AccessToken":"1234567890","UserID":"1122334455"}`)
+	a.NoError(err)
+	session := s.(*wecom.Session)
+	a.Equal(session.AuthURL, "http://wecom/auth_url")
+	a.Equal(session.AccessToken, "1234567890")
+	a.Equal(session.UserID, "1122334455")
+}
+
+func wecomProvider() *wecom.Provider {
+	return wecom.New(os.Getenv("WECOM_CORP_ID"), os.Getenv("WECOM_SECRET"), os.Getenv("WECOM_AGENT_ID"), "/foo")
+}