Documentation
¶
Overview ¶
Package referral is user-to-user referrals, @marinedotsh/better-auth-referral 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, as better-auth's does. 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
- Variables
- func MaskEmail(addr string) string
- func NormalizeCode(code string) string
- type CodeRequest
- type Dashboard
- type Event
- type ListRequest
- type ListResult
- type Option
- type Plugin
- func (p *Plugin) DataHooks() auth.DataHooks
- func (p *Plugin) Init(a *auth.Auth) error
- func (p *Plugin) List(ctx context.Context, in ListRequest) (ListResult, error)
- func (p *Plugin) MarkStep(ctx context.Context, referredUserID, step string, metadata map[string]string) (StepResult, error)
- func (p *Plugin) MyDashboard(ctx context.Context) (Dashboard, error)
- func (p *Plugin) Name() string
- func (p *Plugin) Operations() []auth.Operation
- func (p *Plugin) OptionErr() error
- func (p *Plugin) RateLimits() []auth.RateRule
- func (p *Plugin) Remember(ctx context.Context, code string) error
- func (p *Plugin) Required() []string
- func (p *Plugin) Tables() []sqlb.Table
- func (p *Plugin) TypedMigrations(engine string, t auth.SQLTypes) ([]auth.Migration, error)
- func (p *Plugin) UserTables() []auth.UserTable
- func (p *Plugin) Validate(*auth.Config) error
- type Progress
- type Referral
- type ReferredUser
- type Stats
- type Status
- type StepResult
- type User
Constants ¶
const ( EndpointDashboard auth.EndpointID = "referral.dashboard" EndpointList auth.EndpointID = "referral.list" EndpointRemember auth.EndpointID = "referral.remember" )
Operation ids, stable wire names.
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, as better-auth-referral's do. 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.
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).
const CookieName = "referral"
CookieName is the plugin cookie remember sets.
const PluginName = "referral"
PluginName is the plugin's permanent identity and route prefix.
const ReferralHeader = "Referral-Code"
ReferralHeader carries a referral code on a sign-up request, better-auth-referral's x-referral-code. ds:def id=referralheader-dmcrtk6w owner=@khanakia stability=stable
const StepSignUp = "sign_up"
StepSignUp is the step every referral records at sign-up; it is reserved.
Variables ¶
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.
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 ¶
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 ¶
NormalizeCode upper-cases and trims a typed code.
Types ¶
type CodeRequest ¶
type CodeRequest struct {
Code string `json:"code"`
}
CodeRequest carries a referral code.
type ListRequest ¶
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 ¶
AfterCompleted runs once, after the step that completes a referral commits: the place to grant the reward.
func AfterSignUp ¶
AfterSignUp runs after a referred sign-up commits. It cannot fail the sign-up, which has already happened.
func AfterStep ¶
AfterStep runs after a newly recorded step commits; a repeated step does not run it again.
func GenerateCode ¶
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.
type Plugin ¶
type Plugin struct {
// contains filtered or unexported fields
}
Plugin is the referral plugin. Build it with New.
func (*Plugin) 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) 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 ¶
MyDashboard returns the signed-in user's code and counts.
func (*Plugin) Operations ¶
Operations lists the three operations.
func (*Plugin) OptionErr ¶
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 ¶
RateLimits bounds remember, the one public operation.
func (*Plugin) Remember ¶
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 ¶
Required is the full list of steps a referral needs: sign-up, then the configured ones.
func (*Plugin) TypedMigrations ¶
TypedMigrations creates the three tables. referred_user_id is unique: a user is referred once.
func (*Plugin) UserTables ¶
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.
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 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.