// Package casdoor talks to the Casdoor Admin API server-side. It backs the // 「同步 Casdoor 成员」 flow (POST /tenants/:id/members/sync-casdoor): the // backend exchanges its OIDC client_id/client_secret for an access token via // the client_credentials grant, then pages through /api/get-users to pull the // IdP-side user directory. // // Prerequisites on the Casdoor side (one-time, admin console): // - the application's grantTypes must include "Client Credentials" // - the client credentials must belong to an admin-capable user/org so // the issued token may call the admin endpoints // // Department extraction: Casdoor keeps department info in deployment-specific // fields (groups tree / affiliation / title / properties map). AdminDeptField // / AdminDeptCodeField pin exact fields; when empty the client probes the // built-in candidate lists and reports which field it used, so the sync // result can surface the mapping to the operator. package casdoor import ( "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "strings" "time" "academy/internal/config" "academy/internal/logger" ) const ( // tokenEndpointPath is Casdoor's OAuth2 token endpoint (standard // /api/login/oauth/access_token; NOT /api/login, which is the SSO page // entry and rejects credential bodies with JSON parse errors). tokenEndpointPath = "/api/login/oauth/access_token" // listUsersPath is the admin directory endpoint. listUsersPath = "/api/get-users" // listPageSize mirrors Casdoor's default page cap for get-users. listPageSize = 200 // listMaxPages safety cap: 200 * 100 = 20k users before giving up. listMaxPages = 100 // requestTimeout bounds each outbound call. requestTimeout = 20 * time.Second ) // ErrGrantNotSupported wraps Casdoor's response when the application has not // enabled the client_credentials grant — the operator fix is a console toggle, // so callers match on this sentinel to surface actionable copy. var ErrGrantNotSupported = errors.New("casdoor: grant_type client_credentials is not supported in this application") // ErrAdminDenied wraps 401/403 admin API responses: the token was issued but // lacks the privileges for /api/get-users. var ErrAdminDenied = errors.New("casdoor: admin api access denied") // Config carries everything the admin client needs. It is a plain struct (not // the whole app config) so tests can construct it directly. type Config struct { BaseURL string // e.g. https://autht.well-trust.com (no trailing slash) ClientID string ClientSecret string Organization string // get-users owner param; defaults to "built-in" DeptField string // exact field for 部门名称; empty = auto-probe DeptCodeField string // exact field for 部门编号; empty = auto-probe // Username/Password 服务账号密码模式(000156):部分 Casdoor 部署的 API 鉴权 // (casbin) 会拒绝 client_credentials 应用令牌调 /api/get-users,此时用具备 // 目标组织管理权限的服务账号走 password grant 换用户令牌。两者非空时优先。 Username string Password string } // NewConfigFromOIDC builds the admin client config from the OIDC section. // The base URL is derived from the explicit AdminBaseURL, else the token // endpoint's scheme+host, else the issuer URL. func NewConfigFromOIDC(oidc *config.OIDCAuthConfig) Config { cfg := Config{ ClientID: oidc.ClientID, ClientSecret: oidc.ClientSecret, Organization: oidc.AdminOrganization, DeptField: oidc.AdminDeptField, DeptCodeField: oidc.AdminDeptCodeField, Username: oidc.AdminUsername, Password: oidc.AdminPassword, } switch { case strings.TrimSpace(oidc.AdminBaseURL) != "": cfg.BaseURL = strings.TrimRight(strings.TrimSpace(oidc.AdminBaseURL), "/") case strings.TrimSpace(oidc.TokenEndpoint) != "": cfg.BaseURL = baseURLFromEndpoint(oidc.TokenEndpoint) case strings.TrimSpace(oidc.IssuerURL) != "": cfg.BaseURL = strings.TrimRight(strings.TrimSpace(oidc.IssuerURL), "/") } if cfg.Organization == "" { cfg.Organization = "built-in" } return cfg } // baseURLFromEndpoint extracts scheme://host[:port] from an endpoint URL. func baseURLFromEndpoint(endpoint string) string { u, err := url.Parse(strings.TrimSpace(endpoint)) if err != nil || u.Scheme == "" || u.Host == "" { return "" } return u.Scheme + "://" + u.Host } // Client is a thin Casdoor Admin API client. The zero value is disabled. type Client struct { cfg Config http *http.Client token string expiry time.Time } // NewClient constructs the admin client from the resolved config. func NewClient(cfg Config) *Client { return &Client{ cfg: cfg, http: &http.Client{ Timeout: requestTimeout, }, } } // NewClientFromOIDC builds a client from the app OIDC config; nil-safe. func NewClientFromOIDC(oidc *config.OIDCAuthConfig) *Client { if oidc == nil { return nil } return NewClient(NewConfigFromOIDC(oidc)) } // Enabled reports whether sync is configured at all. func (c *Client) Enabled() bool { return c != nil && c.cfg.BaseURL != "" && c.cfg.ClientID != "" && c.cfg.ClientSecret != "" } // PasswordMode reports whether the service-account password grant is active. func (c *Client) PasswordMode() bool { return c != nil && c.cfg.Username != "" && c.cfg.Password != "" } // Org reports the organization (get-users owner) this client queries. func (c *Client) Org() string { return c.cfg.Organization } // User is the trimmed Casdoor user projection the sync consumes. type User struct { Owner string // Casdoor organization Name string // 工号(Casdoor name,登录名口径) DisplayName string // 姓名 Email string Phone string IsAdmin bool IsForbidden bool IsDeleted bool DeptName string // 部门名称(按配置/探测字段提取) DeptCode string // 部门编号(按配置/探测字段提取) // DeptSource 记录部门名称取自哪个字段,便于同步结果回显与排障。 DeptSource string // Raw preserves the full IdP record for diagnostics and custom mapping. Raw map[string]interface{} } // ListUsers pages through every user of the configured organization. // Returns (users, deptFieldUsed, err); deptFieldUsed is empty when no // department value was found on any user. func (c *Client) ListUsers(ctx context.Context) ([]*User, string, error) { if !c.Enabled() { return nil, "", errors.New("casdoor: admin api disabled (set OIDC_AUTH_ADMIN_API_ENABLE and credentials)") } if err := c.ensureToken(ctx); err != nil { return nil, "", err } users := make([]*User, 0, listPageSize) deptSource := "" for page := 1; page <= listMaxPages; page++ { batch, err := c.listUsersPage(ctx, page) if err != nil { return nil, "", err } users = append(users, batch...) if len(batch) < listPageSize { break } } for _, u := range users { c.extractDept(u) if deptSource == "" && u.DeptName != "" { deptSource = u.DeptSource } } return users, deptSource, nil } // listUsersPage fetches one page of the directory. func (c *Client) listUsersPage(ctx context.Context, page int) ([]*User, error) { q := url.Values{} q.Set("owner", c.cfg.Organization) q.Set("pageSize", fmt.Sprint(listPageSize)) q.Set("p", fmt.Sprint(page)) q.Set("accessToken", c.token) // Casdoor's canonical admin-API auth param body, err := c.adminGet(ctx, listUsersPath+"?"+q.Encode()) if err != nil { return nil, err } // Casdoor 版本差异:部分构建返回裸数组,部分返回 {"status":..,"data":[..]} // 信封(实测 organization_HX 部署即信封形态)——两种都接受。 var wrapped struct { Status string `json:"status"` Msg string `json:"msg"` Data []map[string]interface{} `json:"data"` } var rawUsers []map[string]interface{} if err := json.Unmarshal(body, &wrapped); err == nil && wrapped.Data != nil { if wrapped.Status == "error" { return nil, fmt.Errorf("casdoor: get-users failed: %s", wrapped.Msg) } rawUsers = wrapped.Data } else if err := json.Unmarshal(body, &rawUsers); err != nil { // 两种形态都不是 → 尝试按错误对象解读 var errObj struct { Status string `json:"status"` Msg string `json:"msg"` } if json.Unmarshal(body, &errObj) == nil && errObj.Status == "error" { return nil, fmt.Errorf("casdoor: get-users failed: %s", errObj.Msg) } return nil, fmt.Errorf("casdoor: unexpected get-users payload: %w", err) } out := make([]*User, 0, len(rawUsers)) for _, raw := range rawUsers { // 缺工号的记录同样保留:由同步服务层记录跳过原因并回显, // 客户端静默丢弃会让操作者无从发现脏数据。 out = append(out, userFromRaw(raw)) } return out, nil } // adminGet performs an authenticated GET against the admin API, refreshing // the token once on 401 and mapping auth failures to typed errors. func (c *Client) adminGet(ctx context.Context, pathAndQuery string) ([]byte, error) { call := func() (*http.Response, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.cfg.BaseURL+pathAndQuery, nil) if err != nil { return nil, err } req.Header.Set("Accept", "application/json") req.Header.Set("Authorization", "Bearer "+c.token) return c.http.Do(req) } resp, err := call() if err != nil { return nil, fmt.Errorf("casdoor: request failed: %w", err) } if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden { _ = resp.Body.Close() // Token might have just expired server-side; refresh once and retry. if refreshErr := c.refreshToken(ctx); refreshErr == nil { if retryResp, retryErr := call(); retryErr == nil { resp = retryResp } else { return nil, ErrAdminDenied } } else { return nil, ErrAdminDenied } } defer func() { _ = resp.Body.Close() }() if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden { return nil, ErrAdminDenied } body, err := io.ReadAll(io.LimitReader(resp.Body, 32<<20)) // 32MB cap: pages are KB-sized if err != nil { return nil, fmt.Errorf("casdoor: read response failed: %w", err) } return body, nil } // ensureToken lazily acquires an access token via client_credentials. func (c *Client) ensureToken(ctx context.Context) error { if c.token != "" && time.Now().Before(c.expiry) { return nil } return c.refreshToken(ctx) } // refreshToken exchanges credentials for a fresh access token. Two grant // modes: password grant (service account, preferred when configured — its // user identity passes casdoor's API authz where app tokens get denied) and // client_credentials fallback. Casdoor answers JSON // {"access_token":...,"expires_in":...}; some builds return the bare JWT // with a text content-type — both are accepted. func (c *Client) refreshToken(ctx context.Context) error { form := url.Values{} form.Set("client_id", c.cfg.ClientID) form.Set("client_secret", c.cfg.ClientSecret) if c.cfg.Username != "" && c.cfg.Password != "" { form.Set("grant_type", "password") form.Set("username", c.cfg.Username) form.Set("password", c.cfg.Password) } else { form.Set("grant_type", "client_credentials") } endpoint := strings.TrimRight(c.cfg.BaseURL, "/") + tokenEndpointPath req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode())) if err != nil { return err } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Accept", "application/json") resp, err := c.http.Do(req) if err != nil { return fmt.Errorf("casdoor: token request failed: %w", err) } defer func() { _ = resp.Body.Close() }() body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) if err != nil { return fmt.Errorf("casdoor: read token response failed: %w", err) } token, expiresIn := parseTokenResponse(body) if token == "" { if resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusUnauthorized { // Casdoor replies {"error":"unsupported_grant_type",...} when the // application has not enabled the requested grant. if strings.Contains(string(body), "not supported") { return ErrGrantNotSupported } if strings.Contains(string(body), "invalid_grant") && c.cfg.Username != "" { return fmt.Errorf("casdoor: service account login failed: %s", strings.TrimSpace(firstN(string(body), 200))) } return fmt.Errorf("casdoor: token rejected: %s", strings.TrimSpace(firstN(string(body), 200))) } return fmt.Errorf("casdoor: no access_token in response (http %d): %s", resp.StatusCode, firstN(string(body), 200)) } ttl := time.Duration(expiresIn) * time.Second if ttl <= 0 { ttl = 10 * time.Minute // Casdoor default when expires_in is absent } // Refresh 60s early to avoid mid-page expiry races. c.token = token c.expiry = time.Now().Add(ttl - minDuration(ttl, time.Minute)) return nil } // parseTokenResponse extracts (access_token, expires_in) tolerating JSON or // bare-JWT bodies. func parseTokenResponse(body []byte) (string, int64) { trimmed := strings.TrimSpace(string(body)) if strings.HasPrefix(trimmed, "{") { var parsed struct { AccessToken string `json:"access_token"` ExpiresIn int64 `json:"expires_in"` } if err := json.Unmarshal([]byte(trimmed), &parsed); err == nil { return parsed.AccessToken, parsed.ExpiresIn } } // Bare JWT (eyJ...) — usable directly as a bearer token. if strings.Contains(trimmed, ".") && !strings.ContainsAny(trimmed, " \n{}") { return trimmed, 0 } return "", 0 } // --------------------------------------------------------------------------- // 字段提取 // --------------------------------------------------------------------------- // deptNameCandidates 部门名称的内置探测顺序:Casdoor 部署差异较大(分组树 / // affiliation / title / properties),探测到第一个非空值即用并在结果里回显 // 字段名;部署方可通过 OIDC_AUTH_ADMIN_DEPT_FIELD 固定。 var deptNameCandidates = []string{ "department", "dept", "deptName", "affiliation", "title", "organization", } // deptCodeCandidates 部门编号的内置探测顺序。 var deptCodeCandidates = []string{ "departmentCode", "deptCode", "dept_code", "department_code", "deptNo", } // groupCandidates 分组树字段(值可为 []string 或以 / 分隔的字符串); // 分组路径取末段作为部门名(如 "公司/财务部" → "财务部")。 var groupCandidates = []string{"groups", "groupPath", "group_paths"} // extractDept fills DeptName/DeptCode/DeptSource for one user. func (c *Client) extractDept(u *User) { if u == nil || u.Raw == nil { return } if c.cfg.DeptField != "" { if v := stringField(u.Raw, c.cfg.DeptField); v != "" { u.DeptName = v u.DeptSource = c.cfg.DeptField } } else { for _, key := range deptNameCandidates { if v := stringField(u.Raw, key); v != "" { u.DeptName = v u.DeptSource = key break } } if u.DeptName == "" { for _, key := range groupCandidates { if v := firstGroupLeaf(u.Raw, key); v != "" { u.DeptName = v u.DeptSource = key break } } } } if c.cfg.DeptCodeField != "" { u.DeptCode = stringField(u.Raw, c.cfg.DeptCodeField) } else { for _, key := range deptCodeCandidates { if v := stringField(u.Raw, key); v != "" { u.DeptCode = v break } } } } // stringField reads a string field from the raw user record. Dotted keys // (e.g. "properties.department") drill into nested maps. func stringField(raw map[string]interface{}, key string) string { parts := strings.Split(key, ".") var cur interface{} = raw for _, p := range parts { m, ok := cur.(map[string]interface{}) if !ok { return "" } cur, ok = m[p] if !ok { return "" } } switch v := cur.(type) { case string: return strings.TrimSpace(v) case float64: // JSON numbers decode as float64 return strings.TrimSpace(fmt.Sprint(v)) default: return "" } } // firstGroupLeaf extracts the leaf segment of the first non-empty group path. // Accepts []string / []interface{} / "a/b/c" string forms. func firstGroupLeaf(raw map[string]interface{}, key string) string { v, ok := raw[key] if !ok { return "" } switch val := v.(type) { case []interface{}: for _, item := range val { if s, ok := item.(string); ok && strings.TrimSpace(s) != "" { return groupLeaf(s) } } case []string: for _, s := range val { if strings.TrimSpace(s) != "" { return groupLeaf(s) } } case string: if strings.TrimSpace(val) != "" { return groupLeaf(val) } } return "" } // groupLeaf takes the last path segment of a group reference // ("公司/财务部" → "财务部"; "财务部" → "财务部"). func groupLeaf(path string) string { path = strings.TrimSpace(path) if idx := strings.LastIndex(path, "/"); idx >= 0 && idx < len(path)-1 { path = path[idx+1:] } return strings.TrimSpace(path) } // userFromRaw projects a raw Casdoor user record. func userFromRaw(raw map[string]interface{}) *User { u := &User{Raw: raw} u.Owner = stringField(raw, "owner") u.Name = stringField(raw, "name") u.DisplayName = stringField(raw, "displayName") if u.DisplayName == "" { u.DisplayName = stringField(raw, "nickname") } u.Email = strings.ToLower(stringField(raw, "email")) u.Phone = stringField(raw, "phone") u.IsAdmin = boolField(raw, "isAdmin") || boolField(raw, "isGlobalAdmin") u.IsForbidden = boolField(raw, "isForbidden") u.IsDeleted = boolField(raw, "isDeleted") return u } func boolField(raw map[string]interface{}, key string) bool { if v, ok := raw[key].(bool); ok { return v } return false } // LogSyncDisabled 帮助 handler 在未配置时输出明确日志(客户端为 nil 安全)。 func LogSyncDisabled(ctx context.Context) { logger.Warnf(ctx, "casdoor member sync is disabled: set OIDC_AUTH_ADMIN_API_ENABLE=true plus admin API env overrides") } // firstN returns the first n bytes of s (rune-safe truncation is unnecessary // here: the content is a JSON error line). func firstN(s string, n int) string { if len(s) <= n { return s } return s[:n] } func minDuration(a, b time.Duration) time.Duration { if a < b { return a } return b }