authhttp

package
v1.0.0-beta.3 Latest Latest
Warning

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

Go to latest
Published: Jul 25, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrHostNotAllowed is returned when the resolved host is not in the AllowedHosts whitelist.
	ErrHostNotAllowed = errors.New("authhttp: host not in allowed list")
)

Functions

func BuildRedirectURI

func BuildRedirectURI(r *http.Request, cfg RedirectURIConfig) (string, error)

BuildRedirectURI constructs a safe OAuth callback redirect URI from the request.

Security rules:

  • Never trusts the Origin header (trivially forged on GET navigations).
  • Only honours X-Forwarded-Host when it matches AllowedHosts.
  • X-Forwarded-Proto is only trusted to upgrade the scheme to "https"; it cannot downgrade an HTTPS connection to HTTP. Use ForceTLS=true in production to ensure HTTPS regardless of headers.
  • Empty AllowedHosts means only r.Host is used (safe default).
  • Returns ErrHostNotAllowed if the resolved host doesn't match the whitelist.

func GetJWTClaims

func GetJWTClaims(ctx context.Context) *application.PericarpClaims

GetJWTClaims retrieves the PericarpClaims from the request context. Returns nil if the request was not authenticated via RequireJWT middleware.

func GetSessionInfo

func GetSessionInfo(ctx context.Context) *application.SessionInfo

GetSessionInfo retrieves the SessionInfo from the request context. Returns nil if the request was not authenticated via RequireAuth middleware.

func RequireAuth

RequireAuth returns HTTP middleware that validates the session cookie and injects the SessionInfo into the request context. It also injects an auth.Identity for use via auth.AgentFromCtx. The injected Identity.Subscription is always nil — sessions don't snapshot subscription state. Services that mix RequireAuth and RequireJWT will see different IsActive() results for the same agent depending on which middleware served the request; gate paid-tier features behind RequireJWT or fetch subscription state explicitly under RequireAuth. Unauthenticated requests receive a 401 JSON response.

func RequireJWT

func RequireJWT(jwtService application.JWTService, cookieName string) func(http.Handler) http.Handler

RequireJWT returns HTTP middleware that validates a JWT from the Authorization header (Bearer token, case-insensitive scheme) falling back to a named cookie, and injects the PericarpClaims into the request context. It also injects an auth.Identity for use via auth.AgentFromCtx. When cookieName is empty it defaults to "pericarp_token". Unauthenticated or invalid-token requests receive a 401 JSON response.

func SwitchActiveAccountHandler

func SwitchActiveAccountHandler(
	reissuer application.TokenReissuer,
	accounts repositories.AccountRepository,
	opts ...SwitchAccountOption,
) http.Handler

SwitchActiveAccountHandler returns an http.Handler that switches the active account in the JWT. It assumes RequireJWT middleware has already run and placed PericarpClaims in the request context.

The accounts parameter is optional. When nil, membership is validated solely against the JWT's AccountIDs claim. When non-nil, an authoritative FindMemberRole check is performed.

Types

type AuthHandlers

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

AuthHandlers provides standard HTTP handlers for OAuth login, callback, me, and logout. They use net/http directly and work with any router (Echo, Chi, Gin, stdlib).

func NewAuthHandlers

func NewAuthHandlers(cfg HandlerConfig) *AuthHandlers

NewAuthHandlers creates AuthHandlers from the given configuration.

func (*AuthHandlers) Callback

func (h *AuthHandlers) Callback(w http.ResponseWriter, r *http.Request)

Callback handles the OAuth provider callback, exchanges the code for tokens, finds or creates the agent, creates a session, and redirects to the frontend.

func (*AuthHandlers) Login

func (h *AuthHandlers) Login(w http.ResponseWriter, r *http.Request)

Login initiates the OAuth authorization flow. It reads an optional ?redirect= query parameter and stores it in FlowData.Metadata for use after callback.

func (*AuthHandlers) Logout

func (h *AuthHandlers) Logout(w http.ResponseWriter, r *http.Request)

Logout revokes the domain session and destroys the HTTP session cookie.

func (*AuthHandlers) Me

Me returns the authenticated user's basic profile as JSON.

type HandlerConfig

type HandlerConfig struct {
	AuthService     application.AuthenticationService
	SessionManager  session.SessionManager
	Credentials     repositories.CredentialRepository
	RedirectURI     RedirectURIConfig
	DefaultProvider string
	SessionDuration time.Duration
	// FrontendURL is prepended to post-login redirect paths for cross-origin
	// redirects. When empty, post-login redirects use relative paths.
	FrontendURL string
	Logger      application.Logger
	// JWTCookieName is the cookie name for the issued JWT. Defaults to "pericarp_token".
	JWTCookieName string
	// JWTCookieMaxAge is the MaxAge (in seconds) for the JWT cookie. When zero,
	// it defaults to 900 (15 minutes) to match the default token TTL.
	JWTCookieMaxAge int
	// InviteAcceptor is optional. When set and the login flow carries an invite
	// token, the callback handler calls AcceptInvite instead of FindOrCreateAgent.
	// Flows without an invite token use the normal FindOrCreateAgent path regardless.
	InviteAcceptor InviteAcceptor
}

HandlerConfig configures the reference auth HTTP handlers.

type InviteAcceptor

type InviteAcceptor interface {
	AcceptInvite(ctx context.Context, token string, userInfo application.UserInfo) (
		*entities.Agent, *entities.Credential, *entities.Account, error)
}

InviteAcceptor accepts an invite on behalf of a user during the OAuth callback.

type RedirectURIConfig

type RedirectURIConfig struct {
	// CallbackPath is the OAuth callback endpoint path (e.g., "/api/auth/callback").
	CallbackPath string
	// AllowedHosts is a whitelist of permitted hostnames. When empty, only r.Host is trusted.
	// Port numbers are ignored during comparison: "example.com:8080" matches "example.com".
	AllowedHosts []string
	// ForceTLS forces the scheme to "https" regardless of the request.
	ForceTLS bool
}

RedirectURIConfig configures how OAuth callback redirect URIs are built.

type SwitchAccountOption

type SwitchAccountOption func(*switchAccountConfig)

SwitchAccountOption configures the SwitchActiveAccountHandler.

func WithSwitchCookieMaxAge

func WithSwitchCookieMaxAge(maxAge int) SwitchAccountOption

WithSwitchCookieMaxAge sets the MaxAge (in seconds) for the JWT cookie. Defaults to 900 (15 minutes).

func WithSwitchCookieName

func WithSwitchCookieName(name string) SwitchAccountOption

WithSwitchCookieName sets the JWT cookie name. Defaults to "pericarp_token".

func WithSwitchLogger

func WithSwitchLogger(l application.Logger) SwitchAccountOption

WithSwitchLogger sets the logger for the switch-account handler.

Jump to

Keyboard shortcuts

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