Documentation
¶
Overview ¶
Package auth —— auth 模块占位。
阶段 2 由对应 subagent 填充:handler.go / service.go / dto.go 等。 见 docs/13-phase1-prd.md 和 docs/14-week1-day-by-day.md。
Package auth —— 认证模块。
提供:
- 邮箱密码注册 / 登录
- Google OAuth 登录
- JWT 签发与校验中间件
- GET /me 当前用户信息
见 docs/13-phase1-prd.md。
Index ¶
- Constants
- func AdminMiddleware(queries userByIDQuerier) echo.MiddlewareFunc
- func GenerateToken(userID, secret string, ttl time.Duration) (string, error)
- func GenerateTokenWithVersion(userID, secret string, ttl time.Duration, tokenVersion int64) (string, error)
- func HybridAuthMiddlewareWithUserStatus(jwtSecret string, verifier ApiKeyVerifier, users UserStatusChecker) echo.MiddlewareFunc
- func JWTMiddlewareWithUserStatus(secret string, users UserStatusChecker) echo.MiddlewareFunc
- func ParseToken(tokenStr, secret string) (string, error)
- func RequireAnyPermission(c echo.Context, permission, resourceType string) error
- func RequirePermission(c echo.Context, permission, resourceType string, resourceID *uuid.UUID) error
- func SetPrincipal(c echo.Context, principal *AuthPrincipal)
- func ValidateUserStatusChecker(users UserStatusChecker) error
- type ApiKeyVerifier
- type AuthPrincipal
- type AuthResponse
- type ChangePasswordRequest
- type Claims
- type DBUserStatusChecker
- type Grant
- type Handler
- func (h *Handler) GetMe(c echo.Context) error
- func (h *Handler) GithubCallback(c echo.Context) error
- func (h *Handler) GithubStart(c echo.Context) error
- func (h *Handler) GoogleCallback(c echo.Context) error
- func (h *Handler) GoogleStart(c echo.Context) error
- func (h *Handler) PatchMe(c echo.Context) error
- func (h *Handler) PostChangePassword(c echo.Context) error
- func (h *Handler) PostLogin(c echo.Context) error
- func (h *Handler) PostOAuthExchange(c echo.Context) error
- func (h *Handler) PostRefresh(c echo.Context) error
- func (h *Handler) PostRegister(c echo.Context) error
- func (h *Handler) Register(api *echo.Group)
- func (h *Handler) RegisterProtected(api *echo.Group, jwtMiddleware echo.MiddlewareFunc)
- func (h *Handler) RegisterRuntimeAttachOnly(api *echo.Group)
- func (h *Handler) SetConfig(cfg *config.Config) *Handler
- type LoginRequest
- type MeResponse
- type OAuthCodeStorageMode
- type OAuthExchangeRequest
- type PrincipalAPIKeyVerifier
- type RegisterRequest
- type Service
- func (s *Service) ChangePassword(ctx context.Context, userID uuid.UUID, req *ChangePasswordRequest) error
- func (s *Service) ExchangeOAuthCode(ctx context.Context, code string) (*AuthResponse, error)
- func (s *Service) FindOrCreateOAuthUser(ctx context.Context, provider, oauthID, email, displayName, avatarURL string) (*AuthResponse, error)
- func (s *Service) GetAuthResponseWithTx(ctx context.Context, tx pgx.Tx, userID uuid.UUID) (*AuthResponse, error)
- func (s *Service) GetMe(ctx context.Context, userID uuid.UUID) (*MeResponse, error)
- func (s *Service) IssueOAuthCode(ctx context.Context, resp *AuthResponse) (string, error)
- func (s *Service) Login(ctx context.Context, req *LoginRequest) (*AuthResponse, error)
- func (s *Service) RefreshToken(ctx context.Context, userID uuid.UUID) (*AuthResponse, error)
- func (s *Service) Register(ctx context.Context, req *RegisterRequest) (*AuthResponse, error)
- func (s *Service) ResetPassword(ctx context.Context, email, newPassword string) error
- func (s *Service) SetOAuthCodeStorageMode(mode OAuthCodeStorageMode) error
- func (s *Service) SetUserProvisioner(provisioner UserProvisioner)
- func (s *Service) UpdateMe(ctx context.Context, userID uuid.UUID, req *UpdateMeRequest) (*MeResponse, error)
- func (s *Service) ValidatePasswordReset(ctx context.Context, email, newPassword string) error
- type UpdateMeRequest
- type UserProvisioner
- type UserStatusChecker
Constants ¶
const ( AuthMethodJWT = "jwt" AuthMethodUserToken = "user_token" )
Variables ¶
This section is empty.
Functions ¶
func AdminMiddleware ¶
func AdminMiddleware(queries userByIDQuerier) echo.MiddlewareFunc
AdminMiddleware 校验当前登录用户的 is_admin 标志。
func GenerateToken ¶
GenerateToken 用 HS256 签发 JWT。
func GenerateTokenWithVersion ¶ added in v0.1.56
func GenerateTokenWithVersion(userID, secret string, ttl time.Duration, tokenVersion int64) (string, error)
GenerateTokenWithVersion signs a user-session JWT bound to the current durable users.token_version value.
func HybridAuthMiddlewareWithUserStatus ¶ added in v0.1.7
func HybridAuthMiddlewareWithUserStatus(jwtSecret string, verifier ApiKeyVerifier, users UserStatusChecker) echo.MiddlewareFunc
HybridAuthMiddlewareWithUserStatus accepts JWT sessions and User Tokens while requiring the durable user-status authority for every unverified principal.
func JWTMiddlewareWithUserStatus ¶ added in v0.1.7
func JWTMiddlewareWithUserStatus(secret string, users UserStatusChecker) echo.MiddlewareFunc
JWTMiddlewareWithUserStatus validates a JWT and its current durable user session version before exposing the principal to a protected handler.
func ParseToken ¶
ParseToken 校验签名 + 过期,返回 sub (user_id)。
func RequireAnyPermission ¶ added in v0.1.41
RequireAnyPermission performs a pre-body check without treating a resource-specific grant as wildcard. Callers must still call RequirePermission after parsing the concrete resource ID.
func RequirePermission ¶ added in v0.1.41
func SetPrincipal ¶ added in v0.1.41
func SetPrincipal(c echo.Context, principal *AuthPrincipal)
func ValidateUserStatusChecker ¶ added in v0.1.56
func ValidateUserStatusChecker(users UserStatusChecker) error
ValidateUserStatusChecker rejects both a nil interface and an interface that contains a typed-nil checker.
Types ¶
type ApiKeyVerifier ¶
type ApiKeyVerifier interface {
Verify(ctx context.Context, plaintextToken string) (uuid.UUID, []string, error)
}
ApiKeyVerifier 抽象 User Token 鉴权能力,避免 auth 与具体 Token 存储或桥接实现耦合。
实现方应在命中后合并刷新 last_used_at,失败时返回固定错误 (不暴露内部细节)。
type AuthPrincipal ¶ added in v0.1.41
type AuthPrincipal struct {
UserID uuid.UUID `json:"user_id"`
AuthMethod string `json:"auth_method"`
TokenID *uuid.UUID `json:"token_id,omitempty"`
IssuerInstanceID string `json:"issuer_instance_id,omitempty"`
Grants []Grant `json:"grants"`
UserStatusVerified bool `json:"-"`
}
AuthPrincipal is the single authenticated identity passed to Core handlers. JWT sessions represent the first-party user and are not narrowed by token grants; User Token requests always go through Allows.
func PrincipalFrom ¶ added in v0.1.41
func PrincipalFrom(c echo.Context) *AuthPrincipal
func (*AuthPrincipal) Allows ¶ added in v0.1.41
func (p *AuthPrincipal) Allows(permission, resourceType string, resourceID *uuid.UUID) bool
Allows evaluates the token grant only. It deliberately does not replace downstream ownership, visibility, or state-machine checks.
func (*AuthPrincipal) HasPermission ¶ added in v0.1.41
func (p *AuthPrincipal) HasPermission(permission, resourceType string) bool
func (*AuthPrincipal) Permissions ¶ added in v0.1.41
func (p *AuthPrincipal) Permissions() []string
type AuthResponse ¶
type AuthResponse struct {
UserID string `json:"user_id"`
Email string `json:"email"`
DisplayName string `json:"display_name"`
JWT string `json:"jwt"`
}
AuthResponse 注册 / 登录 / OAuth 成功响应。
type ChangePasswordRequest ¶
type ChangePasswordRequest struct {
CurrentPassword string `json:"current_password" validate:"required"`
NewPassword string `json:"new_password" validate:"required,min=8,max=72"`
NewPasswordConfirm string `json:"new_password_confirm"`
}
ChangePasswordRequest POST /me/password 请求。
type Claims ¶
type Claims struct {
jwt.RegisteredClaims
TokenVersion int64 `json:"token_version"`
}
Claims JWT payload。
sub = user_id (UUID 字符串) iat / exp 由 RegisteredClaims 提供
func ParseTokenClaims ¶ added in v0.1.56
ParseTokenClaims verifies a user-session JWT and returns its complete claims.
type DBUserStatusChecker ¶ added in v0.1.41
type DBUserStatusChecker struct {
// contains filtered or unexported fields
}
func NewDBUserStatusChecker ¶ added in v0.1.41
func NewDBUserStatusChecker(dbtx db.DBTX) *DBUserStatusChecker
func (*DBUserStatusChecker) EnsureJWTUserVersion ¶ added in v0.1.56
func (*DBUserStatusChecker) EnsureUserEnabled ¶ added in v0.1.41
type Grant ¶ added in v0.1.41
type Grant struct {
Permission string `json:"permission"`
ResourceType string `json:"resource_type"`
ResourceID *uuid.UUID `json:"resource_id,omitempty"`
Constraints json.RawMessage `json:"constraints"`
}
Grant narrows a Core permission to one resource, or to all resources when ResourceID is nil. Domain owner/visibility/state checks still apply.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler 认证模块 HTTP 入口。
主程序通过 NewHandler 构造,再用 SetConfig 注入 cfg(OAuth callback 重定向需要)。 单元测试可直接 NewHandler(svc) 不带 cfg。
func NewHandler ¶
NewHandler 构造 Handler。 cfg 可选:传入则启用 OAuth 回调重定向;不传则只能用作单元测试 / 邮箱注册登录场景。
func (*Handler) GithubCallback ¶
GithubCallback GitHub OAuth 回调。
func (*Handler) GithubStart ¶
GithubStart 重定向到 GitHub OAuth 授权页。
func (*Handler) GoogleCallback ¶
GoogleCallback Google OAuth 回调。
func (*Handler) GoogleStart ¶
GoogleStart 重定向到 Google OAuth 授权页。
func (*Handler) PostChangePassword ¶
PostChangePassword 修改当前用户密码。
func (*Handler) PostRefresh ¶
PostRefresh 刷新当前网页登录 JWT。
func (*Handler) PostRegister ¶
PostRegister 邮箱注册。
func (*Handler) Register ¶
Register 注册公开认证路由(不需 JWT)。
POST /auth/login POST /auth/register GET /auth/google GET /auth/google/callback GET /auth/github GET /auth/github/callback
func (*Handler) RegisterProtected ¶
func (h *Handler) RegisterProtected(api *echo.Group, jwtMiddleware echo.MiddlewareFunc)
RegisterProtected 注册需要 JWT 的端点。
GET /me PATCH /me POST /me/password POST /auth/refresh
func (*Handler) RegisterRuntimeAttachOnly ¶ added in v0.1.56
RegisterRuntimeAttachOnly mounts the single read-only credential check used by persistent SDK clients during a release cutover. Registration, refresh, profile mutation, and OAuth flows must remain unavailable in this mode.
type LoginRequest ¶
type LoginRequest struct {
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"required"`
}
LoginRequest 邮箱登录请求。
type OAuthCodeStorageMode ¶ added in v0.1.56
type OAuthCodeStorageMode string
OAuthCodeStorageMode selects the database representation of a short-lived OAuth redirect code. The default remains legacy-jwt for rolling compatibility.
const ( OAuthCodeStorageModeLegacyJWT OAuthCodeStorageMode = "legacy-jwt" OAuthCodeStorageModeSubjectOnly OAuthCodeStorageMode = "subject-only" )
func ParseOAuthCodeStorageMode ¶ added in v0.1.56
func ParseOAuthCodeStorageMode(value string) (OAuthCodeStorageMode, error)
ParseOAuthCodeStorageMode returns the compatibility default for an empty value and rejects every unknown mode without echoing the supplied value.
type OAuthExchangeRequest ¶
type OAuthExchangeRequest struct {
Code string `json:"code" validate:"required,len=64"`
}
OAuthExchangeRequest exchanges the short-lived OAuth redirect code for a JWT.
type PrincipalAPIKeyVerifier ¶ added in v0.1.41
type PrincipalAPIKeyVerifier interface {
VerifyPrincipal(ctx context.Context, plaintextToken string) (*AuthPrincipal, error)
}
PrincipalAPIKeyVerifier is implemented by Core's local User Token service. The legacy Verify method remains temporarily for bridge compatibility.
type RegisterRequest ¶
type RegisterRequest struct {
Email string `json:"email" validate:"required,email,max=120"`
Password string `json:"password" validate:"required,min=8,max=72"`
DisplayName string `json:"display_name" validate:"required,min=2,max=50"`
}
RegisterRequest 邮箱注册请求。
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service 认证业务逻辑层。
func NewService ¶
NewService 构造 Service。jwtTTL 是 token 有效期(time.Duration)。
func (*Service) ChangePassword ¶
func (s *Service) ChangePassword(ctx context.Context, userID uuid.UUID, req *ChangePasswordRequest) error
ChangePassword 修改当前邮箱密码用户的密码。
func (*Service) ExchangeOAuthCode ¶
ExchangeOAuthCode consumes an OAuth redirect code and returns either the legacy stored JWT or a freshly signed JWT for a subject-only row.
func (*Service) FindOrCreateOAuthUser ¶
func (s *Service) FindOrCreateOAuthUser( ctx context.Context, provider, oauthID, email, displayName, avatarURL string, ) (*AuthResponse, error)
FindOrCreateOAuthUser 处理 Google OAuth 回调用户。
邮箱已被密码用户占用时返回 Conflict,不自动合并账号。
func (*Service) GetAuthResponseWithTx ¶ added in v0.1.56
func (s *Service) GetAuthResponseWithTx(ctx context.Context, tx pgx.Tx, userID uuid.UUID) (*AuthResponse, error)
GetAuthResponseWithTx reads identity state and issues a JWT through the caller's transaction. It preserves GetMe's not-found semantics and does not commit or roll back tx. Hosted flows use this primitive while retaining ownership of their OAuth handoff row.
func (*Service) IssueOAuthCode ¶
IssueOAuthCode stores a one-time redirect code for OAuth callback handoff.
func (*Service) Login ¶
func (s *Service) Login(ctx context.Context, req *LoginRequest) (*AuthResponse, error)
Login 邮箱 + 密码登录。
func (*Service) RefreshToken ¶
RefreshToken issues a fresh JWT for the currently authenticated user.
func (*Service) Register ¶
func (s *Service) Register(ctx context.Context, req *RegisterRequest) (*AuthResponse, error)
Register 邮箱密码注册。
流程:
- email 已存在 -> Conflict
- bcrypt(cost=12) 哈希密码
- 事务内 CreateUser,并执行可选 UserProvisioner
- 签 JWT 返回
func (*Service) ResetPassword ¶
ResetPassword replaces a password after an outer account flow has verified the user's email ownership, such as the hosted cloud verification-code flow.
func (*Service) SetOAuthCodeStorageMode ¶ added in v0.1.56
func (s *Service) SetOAuthCodeStorageMode(mode OAuthCodeStorageMode) error
SetOAuthCodeStorageMode changes only future OAuth handoff writes. Readers always remain compatible with both legacy JWT and subject-only rows. Configure this before serving requests.
func (*Service) SetUserProvisioner ¶
func (s *Service) SetUserProvisioner(provisioner UserProvisioner)
SetUserProvisioner 注入用户创建后的扩展逻辑。传 nil 表示不做额外初始化。
func (*Service) UpdateMe ¶
func (s *Service) UpdateMe(ctx context.Context, userID uuid.UUID, req *UpdateMeRequest) (*MeResponse, error)
UpdateMe 更新当前用户基础资料。
type UpdateMeRequest ¶
type UpdateMeRequest struct {
DisplayName string `json:"display_name" validate:"required,min=2,max=50"`
}
UpdateMeRequest PATCH /me 请求。
type UserProvisioner ¶
type UserProvisioner interface {
ProvisionUser(ctx context.Context, tx pgx.Tx, userID uuid.UUID) error
}
UserProvisioner is an optional extension point after user creation.
Core standalone deployments do not inject an implementation; hosted deployments can use it for cloud-owned provisioning in the same transaction.
type UserStatusChecker ¶ added in v0.1.41
type UserStatusChecker interface {
EnsureUserEnabled(context.Context, uuid.UUID) error
EnsureJWTUserVersion(context.Context, uuid.UUID, int64) error
}
UserStatusChecker is the bounded user-session authority shared by HTTP, Hybrid HTTP, A2A gRPC, and hosted Cloud composition.