referral

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

README

github.com/ubgo/auth/plugin/referral

Ported from @marinedotsh/better-auth-referral by marinedotsh, MIT; see NOTICE.

User-to-user referrals: every user has a code, a sign-up that brings one records who referred whom. The guide is docs/plugins/referral.md.

Install

go get github.com/ubgo/auth/plugin/referral

A separate module, because referrals are not authentication: an app without them never compiles it. It depends on github.com/ubgo/auth and github.com/ubgo/sqlb only.

What it does

  • Every new user gets an eight-character code (auth_referral_code).
  • A sign-up that brings a code in the Referral-Code header, or in the cookie POST /auth/referral/remember {code} sets, records the referral and its sign_up step in the sign-up's transaction; a code naming nobody refuses the sign-up.
  • MarkStep(ctx, referredUserID, step, metadata) records the app's own steps from Go; the last required step completes the referral once.
  • GET /auth/referral/dashboard and GET /auth/referral/list show the signed-in user's code, counts and referred users (addresses masked unless ShowEmails()).

Options

Steps(...), ShowEmails(), GenerateCode(fn), AfterSignUp(fn), AfterStep(fn), AfterCompleted(fn).

Tests

Unit tests in this module; the flows on SQLite, Postgres and MySQL, and every database failure, in integration/p3_community_test.go.

Documentation

Overview

Package referral is user-to-user referrals as a Go plugin: every user has a referral code; a sign-up that brings one records who referred whom; a referral completes once every required step is recorded (sign-up always, then the app's own steps such as a first purchase); and the referrer reads a dashboard and the list of the people they referred.

It is a separate module because referrals are not authentication (the module rule, 2026-10-02): an app without them never compiles it.

The code reaches the sign-up the way an invite does: the ReferralHeader header, or the referral cookie remember sets for a visitor who signs up through an OAuth provider later. A data hook on user creation records the referral inside the sign-up's transaction, and a code that names nobody refuses the sign-up. Steps are recorded from Go only (MarkStep), never by a client, because a step is the app's statement that a reward was earned.

Index

Constants

View Source
const (
	EndpointDashboard auth.EndpointID = "referral.dashboard"
	EndpointList      auth.EndpointID = "referral.list"
	EndpointRemember  auth.EndpointID = "referral.remember"
)

Operation ids, stable wire names.

View Source
const (
	// CodeLength is a code's length: eight upper-case letters and digits,
	// unique-indexed and shared on purpose, so not a secret. The default
	// codes use base32's letters and digits 2-7 (40 bits); GenerateCode may
	// use any of A-Z and 0-9.
	CodeLength = 8
	// DefaultCookieTTL is how long remember keeps a code: long enough for
	// an OAuth round trip and a sign-up form.
	DefaultCookieTTL = time.Hour
	// MaxListLimit bounds one page of list.
	MaxListLimit = 100
	// MaxMetadataLength bounds a step's metadata once encoded.
	MaxMetadataLength = 4096
)

Code shape and limits.

View Source
const (
	TableNameCode      = "auth_referral_code"
	TableAliasCode     = "rfc"
	TableNameReferral  = "auth_referral"
	TableAliasReferral = "rfr"
	TableNameStep      = "auth_referral_step"
	TableAliasStep     = "rfs"

	ColCodeUserID    = "user_id"
	ColCode          = "code"
	ColCodeCreatedAt = "created_at"

	ColID          = "id"
	ColReferrer    = "referrer_user_id"
	ColReferred    = "referred_user_id"
	ColUsedCode    = "code"
	ColStatus      = "status"
	ColCompletedAt = "completed_at"
	ColCreatedAt   = "created_at"

	ColStepReferral = "referral_id"
	ColStep         = "step"
	ColStepMeta     = "metadata"
	ColStepAt       = "completed_at"
)

The tables. No foreign keys (ADR-0002).

View Source
const CookieName = "referral"

CookieName is the plugin cookie remember sets.

View Source
const PluginName = "referral"

PluginName is the plugin's permanent identity and route prefix.

View Source
const ReferralHeader = "Referral-Code"

ReferralHeader carries a referral code on a sign-up request. ds:def id=referralheader-dmcrtk6w owner=@khanakia stability=stable

View Source
const StepSignUp = "sign_up"

StepSignUp is the step every referral records at sign-up; it is reserved.

Variables

View Source
var (
	TableCode     = sqlb.Table{Name: TableNameCode, Alias: TableAliasCode}
	TableReferral = sqlb.Table{Name: TableNameReferral, Alias: TableAliasReferral}
	TableStep     = sqlb.Table{Name: TableNameStep, Alias: TableAliasStep}

	CodeUserID    = sqlb.Col[string](TableCode, ColCodeUserID)
	CodeValue     = sqlb.Col[string](TableCode, ColCode)
	CodeCreatedAt = sqlb.Col[time.Time](TableCode, ColCodeCreatedAt)

	ReferralID          = sqlb.Col[string](TableReferral, ColID)
	ReferralReferrer    = sqlb.Col[string](TableReferral, ColReferrer)
	ReferralReferred    = sqlb.Col[string](TableReferral, ColReferred)
	ReferralCode        = sqlb.Col[string](TableReferral, ColUsedCode)
	ReferralStatus      = sqlb.Col[Status](TableReferral, ColStatus)
	ReferralCompletedAt = sqlb.Col[*time.Time](TableReferral, ColCompletedAt)
	ReferralCreatedAt   = sqlb.Col[time.Time](TableReferral, ColCreatedAt)

	StepReferralID = sqlb.Col[string](TableStep, ColStepReferral)
	StepName       = sqlb.Col[string](TableStep, ColStep)
	StepMetadata   = sqlb.Col[string](TableStep, ColStepMeta)
	StepAt         = sqlb.Col[time.Time](TableStep, ColStepAt)
)

The tables and their typed columns, for an app that reads them.

View Source
var (
	ErrInvalidCode = auth.NewError("referral.invalid_code", http.StatusBadRequest, "This referral code is not valid.")
	ErrUnknownStep = auth.NewError("referral.unknown_step", http.StatusBadRequest, "This referral step is not configured.")
	ErrNotFound    = auth.NewError("referral.not_found", http.StatusNotFound, "This user was not referred.")

	ErrBadSteps = errors.New("referral: steps must be unique, trimmed, non-empty, and not \"sign_up\"")
	// ErrNoCode fails the write that needed a code when codeAttempts draws
	// gave no free code of the right shape: with the default generator that
	// does not happen, with GenerateCode it means the generator repeats.
	ErrNoCode = errors.New("referral: no free code after several draws")
)

Errors.

Functions

func MaskEmail

func MaskEmail(addr string) string

MaskEmail keeps the first character of the local part and the domain: "a***@example.com"; anything without both parts becomes "hidden", and "" stays "".

func NormalizeCode

func NormalizeCode(code string) string

NormalizeCode upper-cases and trims a typed code.

Types

type CodeRequest

type CodeRequest struct {
	Code string `json:"code"`
}

CodeRequest carries a referral code.

type Dashboard

type Dashboard struct {
	Code  string `json:"code"`
	Stats Stats  `json:"stats"`
}

Dashboard is the caller's code and counts.

type Event

type Event struct {
	ReferralID string
	Referrer   User
	Referred   User
	Step       string
	Progress   Progress
}

Event is what the callbacks receive. Step is set for AfterStep.

type ListRequest

type ListRequest struct {
	Limit  int `json:"limit,omitempty"`
	Offset int `json:"offset,omitempty"`
}

ListRequest pages list, newest first.

type ListResult

type ListResult struct {
	Code      string     `json:"code"`
	Referrals []Referral `json:"referrals"`
	Total     int64      `json:"total"`
	Limit     int        `json:"limit"`
	Offset    int        `json:"offset"`
}

ListResult is a page of list.

type Option

type Option func(*Plugin)

Option configures the plugin.

func AfterCompleted

func AfterCompleted(fn func(ctx context.Context, e Event)) Option

AfterCompleted runs once, after the step that completes a referral commits: the place to grant the reward.

func AfterSignUp

func AfterSignUp(fn func(ctx context.Context, e Event)) Option

AfterSignUp runs after a referred sign-up commits. It cannot fail the sign-up, which has already happened.

func AfterStep

func AfterStep(fn func(ctx context.Context, e Event)) Option

AfterStep runs after a newly recorded step commits; a repeated step does not run it again.

func GenerateCode

func GenerateCode(fn func() string) Option

GenerateCode replaces the code generator, for vanity codes. Its output is normalized (NormalizeCode) and must be CodeLength letters and digits; a draw that is not, or that another user holds, is drawn again, and codeAttempts failed draws fail with ErrNoCode.

func ShowEmails

func ShowEmails() Option

ShowEmails shows referred users' email addresses in list unmasked. By default they read "a***@example.com": the referrer did not need the address to refer them.

func Steps

func Steps(steps ...string) Option

Steps are the app's steps a referral needs after sign-up to complete, such as "email_verified" and "first_purchase", recorded with MarkStep.

type Plugin

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

Plugin is the referral plugin. Build it with New.

func New

func New(opts ...Option) *Plugin

New builds the plugin.

func (*Plugin) DataHooks

func (p *Plugin) DataHooks() auth.DataHooks

DataHooks give every new user a code and, when the sign-up brings a referral code, record the referral and its sign-up step, in the sign-up's transaction. ds:def id=plugin-datahooks-h9da73gq owner=@khanakia stability=stable

func (*Plugin) Init

func (p *Plugin) Init(a *auth.Auth) error

Init captures the core.

func (*Plugin) List

func (p *Plugin) List(ctx context.Context, in ListRequest) (ListResult, error)

List returns a page of the signed-in user's referrals.

func (*Plugin) MarkStep

func (p *Plugin) MarkStep(ctx context.Context, referredUserID, step string, metadata map[string]string) (StepResult, error)

MarkStep records that the user referredUserID reached step, with metadata for the app's records (an order id), and completes the referral when it was the last required step. It is Go only: a step is the app's statement that a reward was earned, never a client's. Recording a step twice is a no-op. ds:def id=plugin-markstep-sk2dyp6p owner=@khanakia stability=stable

func (*Plugin) MyDashboard

func (p *Plugin) MyDashboard(ctx context.Context) (Dashboard, error)

MyDashboard returns the signed-in user's code and counts.

func (*Plugin) Name

func (p *Plugin) Name() string

Name returns PluginName.

func (*Plugin) Operations

func (p *Plugin) Operations() []auth.Operation

Operations lists the three operations.

func (*Plugin) OptionErr

func (p *Plugin) OptionErr() error

OptionErr is every error the options recorded, such as auth.ErrNilOption naming an option given nil; auth.New refuses to start while it is not nil (auth.OptionChecker).

func (*Plugin) RateLimits

func (p *Plugin) RateLimits() []auth.RateRule

RateLimits bounds remember, the one public operation.

func (*Plugin) Remember

func (p *Plugin) Remember(ctx context.Context, code string) error

Remember keeps a valid code in the referral cookie, for a visitor who will sign up through a provider, whose callback request carries no header.

func (*Plugin) Required

func (p *Plugin) Required() []string

Required is the full list of steps a referral needs: sign-up, then the configured ones.

func (*Plugin) Tables

func (p *Plugin) Tables() []sqlb.Table

Tables declares the three tables.

func (*Plugin) TypedMigrations

func (p *Plugin) TypedMigrations(engine string, t auth.SQLTypes) ([]auth.Migration, error)

TypedMigrations creates the three tables. referred_user_id is unique: a user is referred once.

func (*Plugin) UserTables

func (p *Plugin) UserTables() []auth.UserTable

UserTables tells DeleteUser which rows are a user's: the code, and the referrals in which the user was referred or referred someone. Steps of a deleted referral stay until the app clears them; they name no user.

func (*Plugin) Validate

func (p *Plugin) Validate(*auth.Config) error

Validate refuses a bad step list.

type Progress

type Progress struct {
	RequiredSteps  []string `json:"requiredSteps"`
	CompletedSteps []string `json:"completedSteps"`
	RemainingSteps []string `json:"remainingSteps"`
	Completed      int      `json:"completed"`
	Total          int      `json:"total"`
	IsCompleted    bool     `json:"isCompleted"`
}

Progress is how far a referral got.

type Referral

type Referral struct {
	ID           string       `json:"id"`
	Status       Status       `json:"status"`
	CompletedAt  *time.Time   `json:"completedAt"`
	CreatedAt    time.Time    `json:"createdAt"`
	Progress     Progress     `json:"progress"`
	ReferredUser ReferredUser `json:"referredUser"`
}

Referral is one row of list.

type ReferredUser

type ReferredUser struct {
	ID    string `json:"id"`
	Name  string `json:"name"`
	Email string `json:"email"`
	Image string `json:"image,omitempty"`
}

ReferredUser is the referred side of a row in list.

type Stats

type Stats struct {
	Total       int64 `json:"total"`
	Completed   int64 `json:"completed"`
	Pending     int64 `json:"pending"`
	JoinedToday int64 `json:"joinedToday"`
}

Stats counts the caller's referrals.

type Status

type Status string

Status is a referral's state.

const (
	StatusPending   Status = "pending"
	StatusCompleted Status = "completed"
)

The states.

type StepResult

type StepResult struct {
	// AlreadyCompleted is true when the step had been recorded before; the
	// call changed nothing and ran no callback.
	AlreadyCompleted bool
	Status           Status
	Progress         Progress
}

StepResult is the answer of MarkStep.

type User

type User struct {
	ID   string
	Name string
}

User is the user side of an event.

Jump to

Keyboard shortcuts

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