authbridge

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: Apache-2.0 Imports: 14 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package authbridge signs people in through an existing API instead of a separate user store. A JSON config describes the API's endpoints and where the token, user and role are in its responses, so Visionary can sit in front of any backend that already has authentication.

Two flows are supported:

  • "otp": request a code for an identifier (phone, email), then verify it.
  • "password": send an identifier and password in one call (Login).

Index

Constants

View Source
const (
	TypeOTP      = "otp"
	TypePassword = "password"
	TypeShared   = "shared"
	TypeNone     = "none"

	// AnyRole in AllowedRoles or VISIONARY_ROLE_MAP matches every user of the
	// API, whatever their role.
	AnyRole = "*"

	LocationNone     = "none"
	LocationOptional = "optional"
	LocationRequired = "required"
)

Modes. otp and password delegate to an existing API; shared is one team password checked by Visionary itself; none skips sign-in (local use only).

Variables

View Source
var ErrInvalidIdentifier = errors.New("invalid identifier")

ErrInvalidIdentifier means the identifier failed the configured pattern.

View Source
var ErrNoProfile = errors.New("no profile endpoint configured")

ErrNoProfile means the role cannot be re-checked: no profile endpoint.

Functions

func ApplyEnv

func ApplyEnv(c *Config, getenv func(string) string) error

ApplyEnv overlays VISIONARY_AUTH_* variables on c, so a deployment can be configured with environment variables alone, or tweak a JSON config per environment. Unset variables leave c unchanged.

Endpoints are written as "METHOD /path", bodies and headers as JSON.

func IsUnavailable

func IsUnavailable(err error) bool

Types

type APIError

type APIError struct {
	Status  int
	Message string
}

APIError is the API rejecting a call (Status set) or failing to answer (Status 0 or 5xx).

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Unavailable

func (e *APIError) Unavailable() bool

type Bridge

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

func New

func New(cfg Config, userAgent string) *Bridge

func (*Bridge) Allowed

func (b *Bridge) Allowed(u *User) bool

Allowed reports whether any of the user's roles is an allowed role, or every role is allowed ("*"). Comparison ignores case.

func (*Bridge) CanRecheck

func (b *Bridge) CanRecheck() bool

CanRecheck reports whether sessions can be re-validated against the API.

func (*Bridge) Complete

func (b *Bridge) Complete(ctx context.Context, identifier, secret, clientUA string, pos *Position) (*Result, error)

Complete exchanges the code or password for a token and loads the user. pos may be nil when location is not required.

func (*Bridge) Config

func (b *Bridge) Config() *Config

func (*Bridge) Logout

func (b *Bridge) Logout(ctx context.Context, token string) error

Logout revokes token on the API, when a logout endpoint is configured.

func (*Bridge) Normalize

func (b *Bridge) Normalize(id string) (string, error)

Normalize applies the identifier rules and checks the pattern.

func (*Bridge) Recheck

func (b *Bridge) Recheck(ctx context.Context, token string) (*User, error)

Recheck loads the token's user again, so revoked tokens and removed roles take effect during a session.

func (*Bridge) Start

func (b *Bridge) Start(ctx context.Context, identifier string) (string, error)

Start sends a one-time code (otp flow) and returns where it went.

type Config

type Config struct {
	// Provider is shown on the sign-in screen: "Sign in with your <Provider> account".
	Provider string `json:"provider"`
	Type     string `json:"type"`
	BaseURL  string `json:"base_url"`
	// Timeout per API call, as a Go duration ("15s").
	Timeout string `json:"timeout,omitempty"`

	Identifier Identifier `json:"identifier"`
	// CodeLength and ResendSeconds apply to the otp flow.
	CodeLength    int `json:"code_length,omitempty"`
	ResendSeconds int `json:"resend_seconds,omitempty"`
	// Location asks the browser for the user's position at sign-in, for APIs
	// that expect it: "none" (default), "optional" or "required". Body values
	// "{{latitude}}" and "{{longitude}}" are sent as numbers.
	Location string `json:"location,omitempty"`

	// RequestCode sends the one-time code (otp only).
	RequestCode *Endpoint `json:"request_code,omitempty"`
	// Login signs in with identifier and password in one call (password
	// only). It is stored as Verify once loaded.
	Login *Endpoint `json:"login,omitempty"`
	// Verify exchanges the code for a token (otp). Password configs from
	// before Login may still use it.
	Verify Endpoint `json:"verify"`
	// Profile returns the signed-in user. Without it, user fields are read
	// from the Verify response and the role can't be re-checked later.
	Profile *Endpoint `json:"profile,omitempty"`
	Logout  *Endpoint `json:"logout,omitempty"`

	Token TokenConfig `json:"token"`
	// Headers are sent on every call, e.g. an API key the auth API requires.
	Headers      map[string]string `json:"headers,omitempty"`
	Fields       Fields            `json:"fields"`
	AllowedRoles []string          `json:"allowed_roles"`

	// SharedPassword is the team password in shared mode. It is only read
	// from VISIONARY_SHARED_PASSWORD, never from a config file.
	SharedPassword string `json:"-"`
}

func Load

func Load(src Source) (Config, error)

Load reads and validates the auth config. There is no built-in default: every deployment chooses its mode.

func (*Config) Delegated

func (c *Config) Delegated() bool

Delegated reports whether sign-in goes through an external API.

func (*Config) Public

func (c *Config) Public() Public

type Endpoint

type Endpoint struct {
	Method  string            `json:"method"`
	Path    string            `json:"path"`
	Body    map[string]any    `json:"body,omitempty"`
	Headers map[string]string `json:"headers,omitempty"`
}

Endpoint is one call. Body values may contain {{identifier}}, {{code}} and {{password}}; a value that is exactly one placeholder is replaced as is.

type Fields

type Fields struct {
	SentTo       string `json:"sent_to,omitempty"`
	Token        string `json:"token"`
	ExpiresAt    string `json:"expires_at,omitempty"`
	UserID       string `json:"user_id,omitempty"`
	Name         string `json:"name,omitempty"`
	Handle       string `json:"handle,omitempty"`
	Role         string `json:"role"`
	ErrorMessage string `json:"error_message,omitempty"`
}

Fields are dotted paths into JSON responses, e.g. "data.token" or "user.roles.0". Token, ExpiresAt, UserID and SentTo are read from the Verify / RequestCode responses; Name, Handle and Role from Profile (or Verify when there is no Profile endpoint). Role may point at a string or an array of strings.

type Identifier

type Identifier struct {
	Label       string `json:"label"`
	Placeholder string `json:"placeholder,omitempty"`
	// Input is the HTML input type: "tel", "email" or "text".
	Input string `json:"input,omitempty"`
	// Normalize is applied before validation: "digits", "lowercase" or "trim".
	Normalize string `json:"normalize,omitempty"`
	Pattern   string `json:"pattern,omitempty"`
	// PatternHint is shown when the pattern does not match.
	PatternHint string `json:"pattern_hint,omitempty"`
}

type Position

type Position struct {
	Latitude  float64
	Longitude float64
}

Position is the browser's location, sent when the config asks for it.

type Public

type Public struct {
	Provider      string     `json:"provider"`
	Type          string     `json:"type"`
	Identifier    Identifier `json:"identifier"`
	CodeLength    int        `json:"code_length,omitempty"`
	ResendSeconds int        `json:"resend_seconds,omitempty"`
	Location      string     `json:"location"`
	AllowedRoles  []string   `json:"allowed_roles"`
}

Public is what the sign-in screen needs; it holds nothing secret.

type Result

type Result struct {
	Token     string
	ExpiresAt time.Time
	User      User
}

type Source

type Source struct {
	Path   string
	Inline string
	Getenv func(string) string
}

Source says where the auth config comes from: an optional JSON file (Path) or JSON text (Inline), then VISIONARY_AUTH_* variables from Getenv on top. Environment variables alone are enough.

type TokenConfig

type TokenConfig struct {
	Header string `json:"header"`
	Prefix string `json:"prefix"`
}

TokenConfig says how the API expects the token back on later calls.

type User

type User struct {
	ID     string   `json:"id"`
	Name   string   `json:"name"`
	Handle string   `json:"handle"`
	Roles  []string `json:"roles"`
}

User is who signed in, as the API describes them.

Jump to

Keyboard shortcuts

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