70 lines
1.5 KiB
Go
70 lines
1.5 KiB
Go
package dingtalkconfig
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type Result struct {
|
|
OK bool
|
|
Code string
|
|
CheckedAt time.Time
|
|
}
|
|
type Verifier struct {
|
|
endpoint string
|
|
client *http.Client
|
|
}
|
|
|
|
func NewVerifier(endpoint string, client *http.Client) *Verifier {
|
|
if client == nil {
|
|
client = &http.Client{Timeout: 10 * time.Second}
|
|
}
|
|
return &Verifier{endpoint: strings.TrimSpace(endpoint), client: client}
|
|
}
|
|
func (v *Verifier) Verify(ctx context.Context, id, secret string) Result {
|
|
r := Result{Code: "verification_failed", CheckedAt: time.Now().UTC()}
|
|
if strings.TrimSpace(id) == "" || strings.TrimSpace(secret) == "" {
|
|
r.Code = "credential_incomplete"
|
|
return r
|
|
}
|
|
u, err := url.Parse(v.endpoint)
|
|
if err != nil {
|
|
r.Code = "endpoint_invalid"
|
|
return r
|
|
}
|
|
q := u.Query()
|
|
q.Set("appkey", id)
|
|
q.Set("appsecret", secret)
|
|
u.RawQuery = q.Encode()
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
|
|
if err != nil {
|
|
return r
|
|
}
|
|
resp, err := v.client.Do(req)
|
|
if err != nil {
|
|
r.Code = "network_error"
|
|
return r
|
|
}
|
|
defer resp.Body.Close()
|
|
var body struct {
|
|
ErrCode int `json:"errcode"`
|
|
AccessToken string `json:"access_token"`
|
|
}
|
|
if json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&body) != nil {
|
|
r.Code = "invalid_response"
|
|
return r
|
|
}
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 || body.ErrCode != 0 || strings.TrimSpace(body.AccessToken) == "" {
|
|
r.Code = "credential_rejected"
|
|
return r
|
|
}
|
|
r.OK = true
|
|
r.Code = "ok"
|
|
return r
|
|
}
|