Documentation
¶
Overview ¶
Package domain holds the application's core types and rules: entities, input validation and the error vocabulary. It imports nothing from the rest of the project (no HTTP, no SQL), so every other layer can depend on it without creating import cycles.
Index ¶
- Constants
- Variables
- func NewValidationError(field, msg string) error
- func NormalizeLimit(n int) int
- func ValidateEmail(s string) error
- func ValidatePassword(field, password string) error
- func ValidateProjectName(name string) error
- type Account
- type CreateTaskInput
- type Page
- type Project
- type Session
- type SignupInput
- type Task
- type TaskStatus
- type UpdateTaskInput
- type User
- type ValidationError
- type Verification
Constants ¶
const ( MaxEmailLength = 254 // RFC 5321 path limit MaxNameLength = 100 MaxTitleLength = 200 MinPriority = 1 MaxPriority = 5 DefaultPriority = 3 DefaultPageSize = 20 MaxPageSize = 100 MinPasswordBytes = 8 // MaxPasswordBytes bounds the CPU a single login or signup can make us spend. Argon2id, // unlike bcrypt (72-byte limit), would happily hash megabytes; 128 bytes is far more than // any typed password or password-manager output. Mirrors auth.MaxPasswordBytes. MaxPasswordBytes = 128 )
Limits shared by validation and documentation (api/openapi.yaml mirrors them).
const ( ProviderCredential = "credential" // email + password; the account holds the argon2id hash ProviderGitHub = "github" )
Account provider ids. In Better Auth's data model a user can have several "accounts", one per way of signing in.
const ( PurposeEmailVerification = "email-verification" PurposePasswordReset = "password-reset" )
Purposes of a verification token. The stored identifier is "<purpose>:<user id>".
Variables ¶
var ( // ErrNotFound means the entity does not exist OR the caller may not see it. Returning the // same error for both avoids telling an attacker which ids belong to other users. ErrNotFound = errors.New("not found") // ErrConflict means a uniqueness rule was violated (duplicate email, duplicate project name). ErrConflict = errors.New("conflict") ErrUnauthorized = errors.New("unauthorized") // ErrForbidden means the caller is authenticated but not allowed to do this. Resource // ownership checks deliberately use ErrNotFound instead; this one is for future role checks // (e.g. admin-only endpoints) where revealing existence is not a concern. ErrForbidden = errors.New("forbidden") // ErrInvalidToken means a single-use emailed token (email verification, password reset) is // unknown, already used or expired. One error for all three: telling them apart would help // someone guessing tokens. ErrInvalidToken = errors.New("invalid or expired token") )
Sentinel errors. Lower layers wrap them with context (fmt.Errorf("get task: %w", err)); the HTTP layer finds them with errors.Is in ONE place (httpapi.mapError) and picks a status code. Nothing below the HTTP layer knows what a status code is.
Functions ¶
func NewValidationError ¶
NewValidationError builds a single-field *ValidationError. Other layers (cursor parsing, query parameters) use it so every "bad input" ends up as the same error type.
func NormalizeLimit ¶
NormalizeLimit applies the default and the cap to a client-supplied page size.
func ValidateEmail ¶
ValidateEmail checks that s (already normalized) is a bare, plausible email address.
func ValidatePassword ¶
ValidatePassword applies the password length rules (bytes, so multi-byte characters count fully, matching what the hash function actually receives).
func ValidateProjectName ¶
ValidateProjectName checks a project name.
Types ¶
type Account ¶
type Account struct {
ID string
UserID string
ProviderID string // ProviderCredential or ProviderGitHub
// AccountID identifies the user at the provider: the user's own id for credential accounts,
// the provider's user id (e.g. GitHub's numeric id) for OAuth accounts.
AccountID string
// Password is the argon2id PHC string; set only for credential accounts.
Password *string
// OAuth provider credentials; nil for credential accounts.
AccessToken *string
RefreshToken *string
IDToken *string
AccessTokenExpiresAt *time.Time
RefreshTokenExpiresAt *time.Time
Scope *string
CreatedAt time.Time
UpdatedAt time.Time
}
Account is one way a user can sign in (Better Auth's "account" table). Never serialized.
type CreateTaskInput ¶
type CreateTaskInput struct {
Title string `json:"title"`
Priority *int `json:"priority"`
DueDate *string `json:"due_date"`
}
CreateTaskInput is the payload for creating a task. Pointers distinguish "not sent" (use the default) from an explicit zero value.
func (CreateTaskInput) Validate ¶
func (in CreateTaskInput) Validate() error
Validate checks the input.
type Project ¶
type Project struct {
ID string `json:"id"`
OwnerID string `json:"owner_id"`
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
Project groups tasks and belongs to exactly one user.
type Session ¶
type Session struct {
ID string `json:"id"`
UserID string `json:"-"`
TokenHash string `json:"-"` // SHA-256 of the cookie value; see auth.NewToken
ExpiresAt time.Time `json:"expires_at"`
IPAddress string `json:"ip_address"`
UserAgent string `json:"user_agent"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
Session is a server-side login session (cookie authentication). The JSON form is what clients may see: no user id, and above all never the token or its hash.
type SignupInput ¶
type SignupInput struct {
Email string `json:"email"`
Name string `json:"name"`
Password string `json:"password"`
}
SignupInput is the payload for creating an account.
func (*SignupInput) Normalize ¶
func (in *SignupInput) Normalize()
Normalize trims and lower-cases the email so "Ada@Example.com " and "ada@example.com" are the same account. (Lower-casing the whole address is a practical simplification: the local part is technically case-sensitive, but virtually no provider treats it that way.)
func (SignupInput) Validate ¶
func (in SignupInput) Validate() error
Validate checks the (normalized) input. Error messages never echo the password.
type Task ¶
type Task struct {
ID string `json:"id"`
ProjectID string `json:"project_id"`
Title string `json:"title"`
Status TaskStatus `json:"status"`
Priority int `json:"priority"`
// DueDate is a calendar date (YYYY-MM-DD), not an instant: "due on the 5th" has no time zone.
DueDate *string `json:"due_date"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
Task is a unit of work inside a project. Ownership is derived from the project.
type TaskStatus ¶
type TaskStatus string
TaskStatus is a closed set of values; the database enforces it too with a CHECK constraint.
const ( StatusTodo TaskStatus = "todo" StatusDoing TaskStatus = "doing" StatusDone TaskStatus = "done" )
func (TaskStatus) Valid ¶
func (s TaskStatus) Valid() bool
Valid reports whether s is one of the known statuses.
type UpdateTaskInput ¶
type UpdateTaskInput struct {
Title *string `json:"title"`
Status *TaskStatus `json:"status"`
Priority *int `json:"priority"`
DueDate *string `json:"due_date"`
}
UpdateTaskInput is a PATCH payload: nil fields are left unchanged. To clear the due date send "due_date": "" (JSON null decodes to nil, which is indistinguishable from "not sent" with plain pointers; the empty string is the explicit "clear" signal).
func (UpdateTaskInput) Apply ¶
func (in UpdateTaskInput) Apply(t *Task, now time.Time)
Apply copies the provided fields onto t. Call Validate first.
func (UpdateTaskInput) Validate ¶
func (in UpdateTaskInput) Validate() error
Validate checks the provided fields and rejects an empty patch.
type User ¶
type User struct {
ID string `json:"id"`
Email string `json:"email"`
Name string `json:"name"`
EmailVerified bool `json:"email_verified"`
Image *string `json:"image"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
User is a person. WHO they are lives here; HOW they authenticate lives in Account rows, so the password hash is not part of User and no handler can leak it by accident.
type ValidationError ¶
ValidationError reports which input fields were rejected and why. It is a pointer type so callers use errors.As with *ValidationError.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
Error lists the fields in sorted order so messages (and tests) are deterministic.
type Verification ¶
type Verification struct {
ID string
Identifier string // "<purpose>:<user id>"
Value string
ExpiresAt time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
Verification is a single-use emailed token (verify email, reset password). Value holds the SHA-256 of the token, never the token.