Documentation
¶
Overview ¶
Package service holds the application's business logic: validation, authorization rules ("you may only touch your own projects") and orchestration of repositories.
The interfaces below are declared HERE, in the consumer, not next to the implementation (Go proverb: "accept interfaces, return structs"). The service states the minimum it needs; store.Store happens to satisfy them, and tests satisfy them with in-memory fakes. Because the interfaces are small and owned by the consumer, swapping SQLite for PostgreSQL later means writing a new implementation and changing one line of wiring in main.
Index ¶
- type AccountRepo
- type AuthService
- func (s *AuthService) Authenticate(ctx context.Context, email, password string) (domain.User, error)
- func (s *AuthService) GetUser(ctx context.Context, id string) (domain.User, error)
- func (s *AuthService) Login(ctx context.Context, email, password string) (LoginResult, error)
- func (s *AuthService) Signup(ctx context.Context, in domain.SignupInput) (domain.User, error)
- type ClientMeta
- type ListTasksParams
- type LoginResult
- type Mailer
- type PasswordHasher
- type ProjectRepo
- type ProjectService
- func (s *ProjectService) Create(ctx context.Context, ownerID, name string) (domain.Project, error)
- func (s *ProjectService) Delete(ctx context.Context, ownerID, id string) error
- func (s *ProjectService) Get(ctx context.Context, ownerID, id string) (domain.Project, error)
- func (s *ProjectService) List(ctx context.Context, ownerID, afterID string, limit int) (domain.Page[domain.Project], error)
- func (s *ProjectService) Rename(ctx context.Context, ownerID, id, name string) (domain.Project, error)
- type SessionAuthDeps
- type SessionAuthService
- func (s *SessionAuthService) Authenticate(ctx context.Context, token string) (SessionState, error)
- func (s *SessionAuthService) CleanupExpired(ctx context.Context) (sessions, verifications int64, err error)
- func (s *SessionAuthService) ForgetPassword(ctx context.Context, email string) error
- func (s *SessionAuthService) ListSessions(ctx context.Context, userID string) ([]domain.Session, error)
- func (s *SessionAuthService) ResetPassword(ctx context.Context, token, newPassword string) error
- func (s *SessionAuthService) RevokeOtherSessions(ctx context.Context, userID, currentSessionID string) error
- func (s *SessionAuthService) RevokeSession(ctx context.Context, userID, sessionID string) error
- func (s *SessionAuthService) RunCleanup(ctx context.Context, every time.Duration)
- func (s *SessionAuthService) SendVerificationEmail(ctx context.Context, userID string) error
- func (s *SessionAuthService) SignIn(ctx context.Context, email, password string, meta ClientMeta) (SessionResult, error)
- func (s *SessionAuthService) SignInWithOAuth(ctx context.Context, p auth.OAuthProfile, meta ClientMeta) (SessionResult, error)
- func (s *SessionAuthService) SignOut(ctx context.Context, token string) error
- func (s *SessionAuthService) SignUp(ctx context.Context, in domain.SignupInput, meta ClientMeta) (SessionResult, error)
- func (s *SessionAuthService) TTL() time.Duration
- func (s *SessionAuthService) VerifyEmail(ctx context.Context, token string) error
- type SessionConfig
- type SessionRepo
- type SessionResult
- type SessionState
- type TaskRepo
- type TaskService
- func (s *TaskService) Create(ctx context.Context, ownerID, projectID string, in domain.CreateTaskInput) (domain.Task, error)
- func (s *TaskService) Delete(ctx context.Context, ownerID, id string) error
- func (s *TaskService) Get(ctx context.Context, ownerID, id string) (domain.Task, error)
- func (s *TaskService) List(ctx context.Context, ownerID, projectID string, p ListTasksParams) (domain.Page[domain.Task], error)
- func (s *TaskService) Update(ctx context.Context, ownerID, id string, in domain.UpdateTaskInput) (domain.Task, error)
- type TokenIssuer
- type UserRepo
- type VerificationRepo
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AccountRepo ¶
type AccountRepo interface {
// GetCredentialAccount returns the email+password account, ErrNotFound if the user has none.
GetCredentialAccount(ctx context.Context, userID string) (domain.Account, error)
UpdatePasswordHash(ctx context.Context, accountID, hash string, at time.Time) error
// ResetCredentialPassword sets the user's password (creating the credential account from a
// if absent) and deletes ALL the user's sessions, atomically.
ResetCredentialPassword(ctx context.Context, a domain.Account) error
GetAccount(ctx context.Context, providerID, accountID string) (domain.Account, error)
CreateAccount(ctx context.Context, a domain.Account) error
UpdateAccountTokens(ctx context.Context, a domain.Account) error
}
AccountRepo persists the ways a user can sign in (Better Auth's "account" table).
type AuthService ¶
type AuthService struct {
// contains filtered or unexported fields
}
AuthService handles signup, credential checking and JWT login. Cookie sessions build on the same two primitives (Signup and Authenticate) in SessionAuthService, so BOTH authentication modes share one definition of "a valid email and password".
func NewAuthService ¶
func NewAuthService(users UserRepo, accounts AccountRepo, hasher PasswordHasher, tokens TokenIssuer, log *slog.Logger) (*AuthService, error)
NewAuthService wires the service. It hashes once at construction to prepare dummyHash. log may be nil.
func (*AuthService) Authenticate ¶
func (s *AuthService) Authenticate(ctx context.Context, email, password string) (domain.User, error)
Authenticate checks an email and password and returns the user. Unknown email, no password on the account (OAuth-only user), unusable legacy hash and wrong password all produce the SAME error (domain.ErrUnauthorized) and take about the same time, so a caller learns nothing about which accounts exist.
If the password is right but the stored hash uses outdated Argon2 parameters, the hash is replaced with a fresh one ("rehash on login"). Login is the only moment we hold the plaintext, so this is how raising the cost parameters upgrades every active account without a reset.
func (*AuthService) Login ¶
func (s *AuthService) Login(ctx context.Context, email, password string) (LoginResult, error)
Login verifies credentials and issues a JWT (the stateless, Bearer mode of authentication).
func (*AuthService) Signup ¶
func (s *AuthService) Signup(ctx context.Context, in domain.SignupInput) (domain.User, error)
Signup validates the input, hashes the password and stores the new user together with its credential account in ONE transaction. A duplicate email surfaces as domain.ErrConflict.
Tradeoff: reporting "email already registered" lets anyone probe which emails have accounts (user enumeration). Most products accept that for signup UX; high-security ones instead always answer "check your inbox" and send the real outcome by email.
type ClientMeta ¶
ClientMeta is what we remember about the device a session was created on, so users can recognise and revoke their sessions ("Chrome on macOS, 203.0.113.9").
type ListTasksParams ¶
type ListTasksParams struct {
Status *domain.TaskStatus // nil = any
AfterID string // cursor: return tasks with id > AfterID
Limit int // 0 = default
}
ListTasksParams are the optional filters and paging controls for listing tasks.
type LoginResult ¶
LoginResult is what a successful JWT login returns.
type PasswordHasher ¶
type PasswordHasher interface {
Hash(password string) (string, error)
// Verify reports whether password matches the stored hash and whether that hash should be
// replaced because it was made with outdated parameters. err means the STORED hash is unusable.
Verify(password, encoded string) (ok, needsRehash bool, err error)
}
PasswordHasher is satisfied by *auth.PasswordHasher.
type ProjectRepo ¶
type ProjectRepo interface {
CreateProject(ctx context.Context, p domain.Project) error
GetProject(ctx context.Context, ownerID, id string) (domain.Project, error)
ListProjects(ctx context.Context, ownerID, afterID string, limit int) ([]domain.Project, error)
RenameProject(ctx context.Context, ownerID, id, name string, at time.Time) (domain.Project, error)
DeleteProject(ctx context.Context, ownerID, id string) error
}
ProjectRepo persists projects. Every method that takes an ownerID scopes the operation to that owner, so another user's project is reported as domain.ErrNotFound.
type ProjectService ¶
type ProjectService struct {
// contains filtered or unexported fields
}
ProjectService manages a user's projects. Every method takes the caller's ownerID, which comes from the verified JWT, never from the request body: a client cannot ask to act as someone else.
func NewProjectService ¶
func NewProjectService(projects ProjectRepo) *ProjectService
func (*ProjectService) Delete ¶
func (s *ProjectService) Delete(ctx context.Context, ownerID, id string) error
Delete removes the project; its tasks go with it (ON DELETE CASCADE).
type SessionAuthDeps ¶
type SessionAuthDeps struct {
Auth *AuthService
Users UserRepo
Accounts AccountRepo
Sessions SessionRepo
Verifications VerificationRepo
Hasher PasswordHasher
Mailer Mailer
Log *slog.Logger // nil = discard
Config SessionConfig
}
SessionAuthDeps are the collaborators of SessionAuthService.
type SessionAuthService ¶
type SessionAuthService struct {
SessionAuthDeps
// contains filtered or unexported fields
}
SessionAuthService implements the Better Auth-style, database-backed authentication mode: cookie sessions, email verification, password reset and OAuth sign-in.
A session is a random token the browser keeps in an HttpOnly cookie. The database keeps its SHA-256 plus metadata. Because the server holds the state, it can do what a stateless JWT cannot: revoke one session, list devices, sign out everywhere after a password change. The price is one database lookup per authenticated request.
func NewSessionAuthService ¶
func NewSessionAuthService(d SessionAuthDeps) (*SessionAuthService, error)
NewSessionAuthService validates the configuration and applies defaults.
func (*SessionAuthService) Authenticate ¶
func (s *SessionAuthService) Authenticate(ctx context.Context, token string) (SessionState, error)
Authenticate resolves a cookie token to a live session. Unknown and expired tokens give the same domain.ErrUnauthorized. An expired row is deleted on the spot ("lazy expiry"); the periodic cleanup catches the ones nobody ever presents again.
Sliding expiry: if the session has not been touched for UpdateAge, its expiry is pushed to now+TTL. Active users never get logged out; abandoned sessions still end TTL after last use.
func (*SessionAuthService) CleanupExpired ¶
func (s *SessionAuthService) CleanupExpired(ctx context.Context) (sessions, verifications int64, err error)
CleanupExpired deletes expired sessions and verification tokens and reports how many. Expired rows are never honoured (lookups check expiry), so this is housekeeping, not security.
func (*SessionAuthService) ForgetPassword ¶
func (s *SessionAuthService) ForgetPassword(ctx context.Context, email string) error
ForgetPassword emails a reset link if an account with that email exists. It returns nil either way: answering "no such user" would let anyone enumerate registered emails. (A remaining side channel is response TIME, since only real accounts trigger the database write and the email. Production systems hand the mail to a background queue so both paths take equally long.)
func (*SessionAuthService) ListSessions ¶
func (s *SessionAuthService) ListSessions(ctx context.Context, userID string) ([]domain.Session, error)
ListSessions returns the user's active sessions, newest first.
func (*SessionAuthService) ResetPassword ¶
func (s *SessionAuthService) ResetPassword(ctx context.Context, token, newPassword string) error
ResetPassword completes a reset: it consumes the single-use token, stores the new Argon2id hash and deletes ALL of the user's sessions in one transaction, so anybody who was logged in with the old password (or a stolen cookie) is out.
The new password is validated BEFORE the token is consumed, so a too-short password does not burn the user's link.
func (*SessionAuthService) RevokeOtherSessions ¶
func (s *SessionAuthService) RevokeOtherSessions(ctx context.Context, userID, currentSessionID string) error
RevokeOtherSessions signs the user out everywhere except the current session ("log out other devices").
func (*SessionAuthService) RevokeSession ¶
func (s *SessionAuthService) RevokeSession(ctx context.Context, userID, sessionID string) error
RevokeSession ends one of the user's own sessions. Someone else's session id is domain.ErrNotFound, exactly like a nonexistent one.
func (*SessionAuthService) RunCleanup ¶
func (s *SessionAuthService) RunCleanup(ctx context.Context, every time.Duration)
RunCleanup calls CleanupExpired every interval until ctx is cancelled, then returns. Start it with `go`; it is the only background goroutine of this service.
func (*SessionAuthService) SendVerificationEmail ¶
func (s *SessionAuthService) SendVerificationEmail(ctx context.Context, userID string) error
SendVerificationEmail emails the user a link to confirm their address. A user whose email is already verified gets nothing (idempotent). Asking again invalidates the earlier link.
func (*SessionAuthService) SignIn ¶
func (s *SessionAuthService) SignIn(ctx context.Context, email, password string, meta ClientMeta) (SessionResult, error)
SignIn checks the password (same code path, same timing and same generic error as the JWT login) and starts a session.
func (*SessionAuthService) SignInWithOAuth ¶
func (s *SessionAuthService) SignInWithOAuth(ctx context.Context, p auth.OAuthProfile, meta ClientMeta) (SessionResult, error)
SignInWithOAuth signs in (or up) a user authenticated by an OAuth provider and starts a session.
- The provider account is already linked: sign in as its user (and refresh stored tokens).
- A user with the same email exists: link the provider account to them. ONLY if the provider vouches for the email (checked here) AND that user's email is verified here too. Otherwise an attacker could pre-register victim@example.com with their own password and wait for the victim to "Sign in with GitHub": the accounts would merge and the attacker would share the victim's data ("account pre-hijacking"). Unverified local accounts get domain.ErrConflict instead.
- Otherwise create a new user (email verified, since the provider verified it) with the provider account, atomically.
func (*SessionAuthService) SignOut ¶
func (s *SessionAuthService) SignOut(ctx context.Context, token string) error
SignOut deletes the session behind token. It is idempotent: an unknown or already-deleted token is not an error, so a client with a stale cookie can always sign out cleanly.
func (*SessionAuthService) SignUp ¶
func (s *SessionAuthService) SignUp(ctx context.Context, in domain.SignupInput, meta ClientMeta) (SessionResult, error)
SignUp creates the account (user + credential account, atomically), starts a session and sends the verification email. Like Better Auth with email verification not enforced, the user is signed in immediately; unverified users can use the API (see README, next steps, for requiring verification).
func (*SessionAuthService) TTL ¶
func (s *SessionAuthService) TTL() time.Duration
TTL returns the session lifetime (the HTTP layer uses it for the cookie's Max-Age).
func (*SessionAuthService) VerifyEmail ¶
func (s *SessionAuthService) VerifyEmail(ctx context.Context, token string) error
VerifyEmail consumes a verification token and marks the user's email verified. The token is single-use and expires after 24 hours; every failure is domain.ErrInvalidToken.
type SessionConfig ¶
type SessionConfig struct {
// TTL is how long a session lives after it was created or last refreshed (default 7 days).
TTL time.Duration
// UpdateAge is Better Auth's "updateAge": a session is only extended when it has not been
// touched for at least this long (default 24h), so an active user's expiry slides forward
// without a database WRITE on every request.
UpdateAge time.Duration
// PublicURL is the externally visible base URL, used to build links in emails.
PublicURL string
// Now overrides the clock (tests). nil means time.Now.
Now func() time.Time
}
SessionConfig tunes cookie sessions.
type SessionRepo ¶
type SessionRepo interface {
CreateSession(ctx context.Context, s domain.Session) error
// GetSessionByTokenHash returns the session even if expired; the service decides.
GetSessionByTokenHash(ctx context.Context, tokenHash string) (domain.Session, error)
ExtendSession(ctx context.Context, id string, expiresAt, at time.Time) error
ListActiveSessions(ctx context.Context, userID string, now time.Time) ([]domain.Session, error)
// The first two deletes are idempotent (no error if nothing matched).
DeleteSessionByTokenHash(ctx context.Context, tokenHash string) error
DeleteSessionByID(ctx context.Context, id string) error
// DeleteUserSession is ErrNotFound unless the session exists AND belongs to userID.
DeleteUserSession(ctx context.Context, userID, id string) error
DeleteOtherSessions(ctx context.Context, userID, keepID string) error
DeleteExpiredSessions(ctx context.Context, now time.Time) (int64, error)
}
SessionRepo persists cookie sessions. Tokens never reach it: only their SHA-256 (TokenHash).
type SessionResult ¶
SessionResult is a freshly created session. Token is the raw cookie value: it exists only here, in memory, on its way to the Set-Cookie header. The database has only its hash.
type SessionState ¶
type SessionState struct {
Session domain.Session
// Refreshed is true when expiry was just extended; the HTTP layer then re-sends the cookie
// so the browser's copy lives as long as the database row.
Refreshed bool
}
SessionState is the outcome of authenticating a cookie.
type TaskRepo ¶
type TaskRepo interface {
CreateTask(ctx context.Context, t domain.Task) error
GetTask(ctx context.Context, ownerID, id string) (domain.Task, error)
// ListTasks does NOT check ownership; callers must have verified the project first.
ListTasks(ctx context.Context, projectID string, status *domain.TaskStatus, afterID string, limit int) ([]domain.Task, error)
// UpdateTask atomically loads the task, calls apply, and saves the result.
UpdateTask(ctx context.Context, ownerID, id string, apply func(*domain.Task) error) (domain.Task, error)
DeleteTask(ctx context.Context, ownerID, id string) error
}
TaskRepo persists tasks. Tasks are owned through their project.
type TaskService ¶
type TaskService struct {
// contains filtered or unexported fields
}
TaskService manages tasks. Tasks have no owner of their own; the owner is whoever owns the project, and every method proves that before touching anything.
func NewTaskService ¶
func NewTaskService(projects ProjectRepo, tasks TaskRepo) *TaskService
func (*TaskService) Create ¶
func (s *TaskService) Create(ctx context.Context, ownerID, projectID string, in domain.CreateTaskInput) (domain.Task, error)
Create adds a task to a project the caller owns.
func (*TaskService) Delete ¶
func (s *TaskService) Delete(ctx context.Context, ownerID, id string) error
type TokenIssuer ¶
TokenIssuer is satisfied by *auth.Issuer.
type UserRepo ¶
type UserRepo interface {
// CreateUserWithAccount inserts the user and its first account atomically (a user with no
// account could never sign in). domain.ErrConflict on a duplicate email.
CreateUserWithAccount(ctx context.Context, u domain.User, a domain.Account) error
GetUserByEmail(ctx context.Context, email string) (domain.User, error)
GetUserByID(ctx context.Context, id string) (domain.User, error)
MarkEmailVerified(ctx context.Context, id string, at time.Time) error
}
UserRepo persists users. Getters return domain.ErrNotFound for a missing row.
type VerificationRepo ¶
type VerificationRepo interface {
// ReplaceVerification stores v and deletes older rows with the same identifier.
ReplaceVerification(ctx context.Context, v domain.Verification) error
// ConsumeVerification atomically deletes and returns the identifier of an unexpired token of
// the given purpose; ErrNotFound if unknown, used, expired or of another purpose.
ConsumeVerification(ctx context.Context, purpose, valueHash string, now time.Time) (identifier string, err error)
DeleteExpiredVerifications(ctx context.Context, now time.Time) (int64, error)
}
VerificationRepo persists single-use emailed tokens (by hash).