-
Notifications
You must be signed in to change notification settings - Fork 597
/
wecom.go
217 lines (186 loc) · 5.54 KB
/
wecom.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
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
}