auth

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2026 License: Apache-2.0 Imports: 28 Imported by: 0

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

This section is empty.

Variables

This section is empty.

Functions

func AdminMiddleware

func AdminMiddleware(queries userByIDQuerier) echo.MiddlewareFunc

AdminMiddleware 校验当前登录用户的 is_admin 标志。

func GenerateToken

func GenerateToken(userID, secret string, ttl time.Duration) (string, error)

GenerateToken 用 HS256 签发 JWT。

func HybridAuthMiddleware

func HybridAuthMiddleware(jwtSecret string, verifier ApiKeyVerifier) echo.MiddlewareFunc

HybridAuthMiddleware 同时接受网页登录会话与访问令牌。

判定规则:

  • Authorization: Bearer ol_user_xxx → 走 ApiKeyVerifier
  • Authorization: Bearer eyJ... 或其他 → 走 JWT

命中后写入 c.Set(httpx.CtxKeyUserID, userID),与 JWTMiddleware 行为一致; 这样下游 handler 用 httpx.UserIDFrom(c) 即可拿到当前用户。

func JWTMiddleware

func JWTMiddleware(secret string) echo.MiddlewareFunc

JWTMiddleware 校验 Authorization: Bearer <token>。

成功:c.Set(string(httpx.CtxKeyUserID), userID) 后 next。 失败:返回 httpx.Unauthorized(),由全局 ErrorHandler 转成统一错误响应。

func ParseToken

func ParseToken(tokenStr, secret string) (string, error)

ParseToken 校验签名 + 过期,返回 sub (user_id)。

Types

type ApiKeyVerifier

type ApiKeyVerifier interface {
	Verify(ctx context.Context, plaintextToken string) (uuid.UUID, []string, error)
}

ApiKeyVerifier 抽象 User Token 鉴权能力,避免 auth import cloud token service 形成循环。

实现方(internal/apikey.Service)应在命中后异步刷新 last_used_at, 失败时返回固定错误(不暴露内部细节)。

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
}

Claims JWT payload。

sub = user_id (UUID 字符串)
iat / exp 由 RegisteredClaims 提供

type Handler

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

Handler 认证模块 HTTP 入口。

主程序通过 NewHandler 构造,再用 SetConfig 注入 cfg(OAuth callback 重定向需要)。 单元测试可直接 NewHandler(svc) 不带 cfg。

func NewHandler

func NewHandler(svc authService, cfg ...*config.Config) *Handler

NewHandler 构造 Handler。 cfg 可选:传入则启用 OAuth 回调重定向;不传则只能用作单元测试 / 邮箱注册登录场景。

func (*Handler) GetMe

func (h *Handler) GetMe(c echo.Context) error

GetMe 当前登录用户信息。

func (*Handler) GithubCallback

func (h *Handler) GithubCallback(c echo.Context) error

GithubCallback GitHub OAuth 回调。

func (*Handler) GithubStart

func (h *Handler) GithubStart(c echo.Context) error

GithubStart 重定向到 GitHub OAuth 授权页。

func (*Handler) GoogleCallback

func (h *Handler) GoogleCallback(c echo.Context) error

GoogleCallback Google OAuth 回调。

func (*Handler) GoogleStart

func (h *Handler) GoogleStart(c echo.Context) error

GoogleStart 重定向到 Google OAuth 授权页。

func (*Handler) PatchMe

func (h *Handler) PatchMe(c echo.Context) error

PatchMe 更新当前用户资料。

func (*Handler) PostChangePassword

func (h *Handler) PostChangePassword(c echo.Context) error

PostChangePassword 修改当前用户密码。

func (*Handler) PostLogin

func (h *Handler) PostLogin(c echo.Context) error

PostLogin 邮箱登录。

func (*Handler) PostOAuthExchange

func (h *Handler) PostOAuthExchange(c echo.Context) error

func (*Handler) PostRefresh

func (h *Handler) PostRefresh(c echo.Context) error

PostRefresh 刷新当前网页登录 JWT。

func (*Handler) PostRegister

func (h *Handler) PostRegister(c echo.Context) error

PostRegister 邮箱注册。

func (*Handler) Register

func (h *Handler) Register(api *echo.Group)

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) SetConfig

func (h *Handler) SetConfig(cfg *config.Config) *Handler

SetConfig 注入主配置(OAuth callback 用 FrontendURL 等)。 主程序在 NewHandler 后调用,测试不必调用。

type LoginRequest

type LoginRequest struct {
	Email    string `json:"email" validate:"required,email"`
	Password string `json:"password" validate:"required"`
}

LoginRequest 邮箱登录请求。

type MeResponse

type MeResponse = apitypes.MeResponse

MeResponse GET /me 响应。

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 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 RemoteAPIKeyVerifier

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

func NewRemoteAPIKeyVerifier

func NewRemoteAPIKeyVerifier(endpoint string, internalSecret ...string) *RemoteAPIKeyVerifier

func (*RemoteAPIKeyVerifier) Verify

func (v *RemoteAPIKeyVerifier) Verify(ctx context.Context, plaintextKey string) (uuid.UUID, []string, error)

type Service

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

Service 认证业务逻辑层。

func NewService

func NewService(pool *pgxpool.Pool, jwtSecret string, jwtTTL time.Duration) *Service

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

func (s *Service) ExchangeOAuthCode(ctx context.Context, code string) (*AuthResponse, error)

ExchangeOAuthCode consumes an OAuth redirect code and returns the stored JWT.

func (*Service) FindOrCreateOAuthUser

func (s *Service) FindOrCreateOAuthUser(
	ctx context.Context,
	provider, oauthID, email, displayName, avatarURL string,
) (*AuthResponse, error)

FindOrCreateOAuthUser 处理 Google OAuth 回调用户。

Phase 1 决策(docs/13):邮箱已被密码用户占用 -> Conflict,不自动合并账号。

func (*Service) GetMe

func (s *Service) GetMe(ctx context.Context, userID uuid.UUID) (*MeResponse, error)

GetMe 当前用户信息。

func (*Service) IssueOAuthCode

func (s *Service) IssueOAuthCode(ctx context.Context, resp *AuthResponse) (string, error)

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

func (s *Service) RefreshToken(ctx context.Context, userID uuid.UUID) (*AuthResponse, error)

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 邮箱密码注册。

流程:

  1. email 已存在 -> Conflict
  2. bcrypt(cost=12) 哈希密码
  3. 事务内 CreateUser,并执行可选 UserProvisioner
  4. 签 JWT 返回

func (*Service) ResetPassword

func (s *Service) ResetPassword(ctx context.Context, email, newPassword string) error

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) 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 更新当前用户基础资料。

func (*Service) ValidatePasswordReset

func (s *Service) ValidatePasswordReset(ctx context.Context, email, newPassword string) error

ValidatePasswordReset checks whether a hosted account reset may proceed without changing state or consuming an outer verification code.

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.

Jump to

Keyboard shortcuts

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