oauth

package
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 23, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ProtocolOIDC   = "oidc"
	ProtocolFeishu = "feishu"
)

支持的 OAuth/OIDC protocol 取值,OAuthProvider.Protocol 字段与 create.go 校验、IDPRouter 分发均以此为准。

View Source
const (
	ErrUnknownProvider       = "unknown_provider"
	ErrProviderMisconfigured = "provider_misconfigured"
	ErrInvalidState          = "invalid_state"
	ErrIdPError              = "idp_error"
	ErrTokenExchangeFailed   = "token_exchange_failed"
	ErrUserinfoFailed        = "userinfo_failed"
	ErrMissingSub            = "missing_sub"
	ErrIDTokenInvalid        = "id_token_invalid"
	ErrMappingFailed         = "mapping_failed"
	ErrAlreadyLinked         = "already_linked"
	ErrMissingTicket         = "missing_ticket"
	ErrUntrustedOrigin       = "untrusted_origin"
)

Variables

This section is empty.

Functions

func ResolveUsername

func ResolveUsername(info UserinfoPayload, exists func(string) (bool, error)) (string, error)

ResolveUsername 选一个唯一可用的本地 username。 exists(name) 应返回 (是否已被占用, 查询错误)。

func SignBindTicket

func SignBindTicket(secret string, c BindTicketClaims) (string, error)

func SignLinkTicket

func SignLinkTicket(secret string, c LinkTicketClaims) (string, error)

Types

type Allowlist

type Allowlist struct {
	// contains filtered or unexported fields
}

Allowlist 持有规范化后的对外 origin 集合。 empty=true 时进入开发模式:所有 origin 都视作合法,原样回传。

func NewAllowlist

func NewAllowlist(rawURLs []string) (*Allowlist, error)

NewAllowlist 解析输入列表,规范化 + 查重。空切片 / nil 合法。

func (*Allowlist) Match

func (a *Allowlist) Match(origin string) (string, bool)

Match 判定 origin 是否被允许,返回最终用于拼 redirect_uri 的字符串。

  • 列表为空:开发模式,直接放行
  • 列表非空:严格匹配,命中返回 (origin, true),否则 ("", false)

type BindRequest

type BindRequest struct {
	Ticket   string `json:"ticket" binding:"required"`
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

type BindResponse

type BindResponse struct {
	Token string `json:"token"`
}

type BindTicketClaims

type BindTicketClaims struct {
	ProviderID        uint
	Subject           string
	Email             string
	DisplayName       string
	Picture           string
	SuggestedUsername string
	ExpiresAt         int64
}

func ParseBindTicket

func ParseBindTicket(secret, raw string) (BindTicketClaims, error)

type DeleteIdentityRequest

type DeleteIdentityRequest = api.IDPathRequest

type FeishuAdapter

type FeishuAdapter struct {
	HTTP *http.Client
}

FeishuAdapter 实现飞书 v2 OAuth: - token endpoint 接受 JSON body,响应顶层除 access_token 外还有 code/error - userinfo 响应被包装为 {code, msg, data:{...}},无标准 sub 字段 我们用 union_id 作为 oauth_identities.subject(跨应用稳定,飞书官方推荐)。

func NewFeishuAdapter

func NewFeishuAdapter(client *http.Client) *FeishuAdapter

func (*FeishuAdapter) ExchangeCode

func (c *FeishuAdapter) ExchangeCode(ctx context.Context, p *models.OAuthProvider, code, redirectURI string) (*TokenResponse, error)

func (*FeishuAdapter) FetchUserinfo

func (c *FeishuAdapter) FetchUserinfo(ctx context.Context, p *models.OAuthProvider, accessToken string) (*UserinfoPayload, error)

type Handler

type Handler struct {
	Bus        app.EventBus
	App        app.Application
	JWTSecret  string
	Allowlist  *Allowlist
	StateStore *StateStore
	IDP        *IDPRouter
	Verifier   *IDTokenVerifier
}

func NewHandler

func NewHandler(application app.Application, bus app.EventBus, jwtSecret string, allowlist *Allowlist) *Handler

func (*Handler) Bind

func (h *Handler) Bind(c *app.Context, req BindRequest) (BindResponse, error)

func (*Handler) DeleteIdentity

func (h *Handler) DeleteIdentity(c *app.Context, req DeleteIdentityRequest) (api.StatusResponse, error)

func (*Handler) HandleAuthorize

func (h *Handler) HandleAuthorize(c *gin.Context)

func (*Handler) HandleCallback

func (h *Handler) HandleCallback(c *gin.Context)
func (h *Handler) HandleLink(c *gin.Context)

func (*Handler) IssueLinkTicket

func (h *Handler) IssueLinkTicket(c *app.Context, _ api.EmptyRequest) (LinkTicketResponse, error)

func (*Handler) ListMyIdentities

func (h *Handler) ListMyIdentities(c *app.Context, _ api.EmptyRequest) ([]IdentityItem, error)

func (*Handler) ListPublicProviders

func (h *Handler) ListPublicProviders(_ *app.Context, _ api.EmptyRequest) ([]PublicProvider, error)

func (*Handler) Register

func (h *Handler) Register(c *app.Context, req RegisterRequest) (RegisterResponse, error)

type IDPAdapter

type IDPAdapter interface {
	ExchangeCode(ctx context.Context, p *models.OAuthProvider, code, redirectURI string) (*TokenResponse, error)
	FetchUserinfo(ctx context.Context, p *models.OAuthProvider, accessToken string) (*UserinfoPayload, error)
}

IDPAdapter 抽象不同 OAuth/OIDC IdP 的两次出站调用。 实现需要从 *models.OAuthProvider 取所需 endpoint / client 凭据, 并把响应规范化为通用 TokenResponse / UserinfoPayload。

type IDPRouter

type IDPRouter struct {
	OIDC   IDPAdapter
	Feishu IDPAdapter
}

IDPRouter 按 p.Protocol 分发到具体适配器。未知 / 空值回落到 OIDC; 对应分支的 adapter 为 nil(中间状态:Task 2 接 Feishu 前)也回落到 OIDC, 避免 callback 在调用 nil.ExchangeCode 时 panic。

func (*IDPRouter) For

type IDTokenVerifier

type IDTokenVerifier struct {
	// contains filtered or unexported fields
}

IDTokenVerifier 校验 OIDC id_token 签名、过期、issuer 和 audience。 内部维护一个按 jwksURI 索引的 TTL 缓存,避免每次登录都请求 IdP。

func NewIDTokenVerifier

func NewIDTokenVerifier() *IDTokenVerifier

func (*IDTokenVerifier) Verify

func (v *IDTokenVerifier) Verify(ctx context.Context, raw, jwksURI, issuer, clientID string) error

Verify 校验 id_token。

  • jwksURI 必填:用于获取 IdP 公钥集合。
  • issuer 非空时强制比对 iss claim。
  • clientID 必须出现在 aud claim 中。

type IdentityItem

type IdentityItem struct {
	ID                  uint   `json:"id"`
	ProviderID          uint   `json:"provider_id"`
	ProviderName        string `json:"provider_name"`
	ProviderDisplayName string `json:"provider_display_name"`
	Subject             string `json:"subject"`
	Email               string `json:"email"`
	DisplayName         string `json:"display_name"`
	CreatedAt           int64  `json:"created_at"`
}

type LinkTicketClaims

type LinkTicketClaims struct {
	UserID    uint
	ExpiresAt int64
}

func ParseLinkTicket

func ParseLinkTicket(secret, raw string) (LinkTicketClaims, error)

type LinkTicketResponse

type LinkTicketResponse struct {
	Ticket string `json:"ticket"`
}

type OIDCAdapter

type OIDCAdapter struct {
	HTTP *http.Client
}

func NewOIDCAdapter

func NewOIDCAdapter(client *http.Client) *OIDCAdapter

func (*OIDCAdapter) ExchangeCode

func (c *OIDCAdapter) ExchangeCode(ctx context.Context, p *models.OAuthProvider, code, redirectURI string) (*TokenResponse, error)

func (*OIDCAdapter) FetchUserinfo

func (c *OIDCAdapter) FetchUserinfo(ctx context.Context, p *models.OAuthProvider, accessToken string) (*UserinfoPayload, error)

type PublicProvider

type PublicProvider struct {
	Name        string `json:"name"`
	DisplayName string `json:"display_name"`
	IconURL     string `json:"icon_url"`
}

PublicProvider 是 GET /api/oauth/providers 返回给登录页用的轻量 DTO。

type RegisterRequest

type RegisterRequest struct {
	Ticket string `json:"ticket" binding:"required"`
}

type RegisterResponse

type RegisterResponse struct {
	Token string `json:"token"`
}

type StateEntry

type StateEntry struct {
	ProviderID uint
	Kind       string // "login" | "link"
	UserID     uint   // link 模式的发起者,login 模式为 0
	ReturnTo   string
	ExpiresAt  int64
}

type StateStore

type StateStore struct {
	// contains filtered or unexported fields
}

func NewStateStore

func NewStateStore() *StateStore

func (*StateStore) Put

func (s *StateStore) Put(state string, e *StateEntry)

func (*StateStore) Sweep

func (s *StateStore) Sweep()

Sweep 删除所有过期 entry,避免无限增长。建议 1min ticker 调用。

func (*StateStore) Take

func (s *StateStore) Take(state string) (*StateEntry, bool)

Take 返回并删除 state 对应 entry;过期视为 miss。

type TokenResponse

type TokenResponse struct {
	AccessToken  string `json:"access_token"`
	TokenType    string `json:"token_type"`
	IDToken      string `json:"id_token"`
	RefreshToken string `json:"refresh_token"`
	Scope        string `json:"scope"`
	ExpiresIn    int    `json:"expires_in"`
}

TokenResponse 是 IDPAdapter.ExchangeCode 的规范化返回。 不同 IdP 的原始字段被各自的实现拍扁到这套通用字段上。

type UserinfoPayload

type UserinfoPayload struct {
	Sub               string `json:"sub"`
	Email             string `json:"email"`
	PreferredUsername string `json:"preferred_username"`
	Name              string `json:"name"`
	Picture           string `json:"picture"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL