122 lines
4.7 KiB
Go
122 lines
4.7 KiB
Go
package directory
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type DingTalkLookupConfig struct {
|
|
TokenURL string
|
|
APIBaseURL string
|
|
ClientID string
|
|
ClientSecret string
|
|
Timeout time.Duration
|
|
}
|
|
|
|
type DingTalkLookup struct {
|
|
tokenURL string
|
|
apiBaseURL string
|
|
clientID string
|
|
clientSecret string
|
|
httpClient *http.Client
|
|
mu sync.Mutex
|
|
token string
|
|
tokenExpiry time.Time
|
|
now func() time.Time
|
|
}
|
|
|
|
func NewDingTalkLookup(cfg DingTalkLookupConfig) (*DingTalkLookup, error) {
|
|
cfg.TokenURL = strings.TrimSpace(cfg.TokenURL)
|
|
cfg.APIBaseURL = strings.TrimRight(strings.TrimSpace(cfg.APIBaseURL), "/")
|
|
if cfg.TokenURL == "" || cfg.APIBaseURL == "" || strings.TrimSpace(cfg.ClientID) == "" || strings.TrimSpace(cfg.ClientSecret) == "" {
|
|
return nil, errors.New("dingtalk lookup endpoints and credentials are required")
|
|
}
|
|
if _, err := url.ParseRequestURI(cfg.TokenURL); err != nil { return nil, errors.New("invalid dingtalk token endpoint") }
|
|
if _, err := url.ParseRequestURI(cfg.APIBaseURL); err != nil { return nil, errors.New("invalid dingtalk API endpoint") }
|
|
if cfg.Timeout <= 0 { cfg.Timeout = 10 * time.Second }
|
|
return &DingTalkLookup{
|
|
tokenURL: cfg.TokenURL, apiBaseURL: cfg.APIBaseURL,
|
|
clientID: cfg.ClientID, clientSecret: cfg.ClientSecret,
|
|
httpClient: &http.Client{Timeout: cfg.Timeout}, now: time.Now,
|
|
}, nil
|
|
}
|
|
|
|
func (c *DingTalkLookup) LookupUser(ctx context.Context, staffID string) (Profile, error) {
|
|
staffID = strings.TrimSpace(staffID)
|
|
if staffID == "" { return Profile{}, errors.New("dingtalk user id is required") }
|
|
token, err := c.accessToken(ctx)
|
|
if err != nil { return Profile{}, err }
|
|
payload, _ := json.Marshal(map[string]string{"userid": staffID})
|
|
endpoint := c.apiBaseURL + "/topapi/v2/user/get?access_token=" + url.QueryEscape(token)
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(payload))
|
|
if err != nil { return Profile{}, errors.New("dingtalk user request failed") }
|
|
req.Header.Set("Content-Type", "application/json")
|
|
resp, err := c.httpClient.Do(req)
|
|
if err != nil { return Profile{}, errors.New("dingtalk user request failed") }
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 { return Profile{}, errors.New("dingtalk user HTTP failure") }
|
|
var decoded struct {
|
|
ErrCode int `json:"errcode"`
|
|
Result struct {
|
|
UserID string `json:"userid"`
|
|
UnionID string `json:"unionid"`
|
|
Name string `json:"name"`
|
|
Nickname string `json:"nickname"`
|
|
Title string `json:"title"`
|
|
DepartmentIDs []int64 `json:"dept_id_list"`
|
|
Status int `json:"status"`
|
|
} `json:"result"`
|
|
}
|
|
if err := json.NewDecoder(resp.Body).Decode(&decoded); err != nil || decoded.ErrCode != 0 {
|
|
return Profile{}, errors.New("dingtalk user response invalid")
|
|
}
|
|
ids := make([]string, 0, len(decoded.Result.DepartmentIDs))
|
|
for _, id := range decoded.Result.DepartmentIDs { ids = append(ids, strconv.FormatInt(id, 10)) }
|
|
return Profile{
|
|
StaffID: staffID, UnionID: decoded.Result.UnionID, Name: strings.TrimSpace(decoded.Result.Name),
|
|
Nickname: decoded.Result.Nickname, JobTitle: decoded.Result.Title, DepartmentIDs: ids,
|
|
EmploymentStatus: strconv.Itoa(decoded.Result.Status), Source: SourceOnDemand, SyncedAt: c.now().UTC(),
|
|
}, nil
|
|
}
|
|
|
|
func (c *DingTalkLookup) accessToken(ctx context.Context) (string, error) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
if c.token != "" && c.now().Before(c.tokenExpiry) { return c.token, nil }
|
|
parsed, err := url.Parse(c.tokenURL)
|
|
if err != nil { return "", errors.New("dingtalk token request failed") }
|
|
query := parsed.Query()
|
|
query.Set("appkey", c.clientID)
|
|
query.Set("appsecret", c.clientSecret)
|
|
parsed.RawQuery = query.Encode()
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil)
|
|
if err != nil { return "", errors.New("dingtalk token request failed") }
|
|
resp, err := c.httpClient.Do(req)
|
|
if err != nil { return "", errors.New("dingtalk token request failed") }
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 { return "", errors.New("dingtalk token HTTP failure") }
|
|
var decoded struct {
|
|
ErrCode int `json:"errcode"`
|
|
AccessToken string `json:"access_token"`
|
|
ExpiresIn int `json:"expires_in"`
|
|
}
|
|
if err := json.NewDecoder(resp.Body).Decode(&decoded); err != nil || decoded.ErrCode != 0 || decoded.AccessToken == "" {
|
|
return "", errors.New("dingtalk token response invalid")
|
|
}
|
|
ttl := time.Duration(decoded.ExpiresIn) * time.Second
|
|
if ttl <= 0 { ttl = time.Hour }
|
|
refreshMargin := 5 * time.Minute
|
|
if ttl <= refreshMargin { refreshMargin = ttl / 2 }
|
|
c.token = decoded.AccessToken
|
|
c.tokenExpiry = c.now().Add(ttl - refreshMargin)
|
|
return c.token, nil
|
|
}
|