Documentation
¶
Overview ¶
Recommended consumer usage:
package main
import (
"log"
"net/http"
"os"
"github.com/nazimdjebloun/go-auth"
"github.com/nazimdjebloun/go-auth/provider/google"
"github.com/nazimdjebloun/go-auth/provider/github"
)
var Auth *goauth.Auth
func initAuth() {
cfg, err := goauth.NewConfig(
func(c *goauth.Config) {
c.AppName = os.Getenv("APP_NAME")
c.Database.URL = os.Getenv("DATABASE_URL")
},
func(c *goauth.Config) {
c.Email = &goauth.EmailConfig{
Host: os.Getenv("SMTP_HOST"),
Port: 587,
User: os.Getenv("SMTP_USER"),
Pass: os.Getenv("SMTP_PASS"),
From: os.Getenv("EMAIL_FROM"),
}
},
func(c *goauth.Config) {
c.Cookie.Domain = os.Getenv("COOKIE_DOMAIN")
c.Cookie.Secure = os.Getenv("ENV") == "production"
},
goauth.WithProvider(google.New(google.Config{
ClientID: os.Getenv("GOOGLE_CLIENT_ID"),
ClientSecret: os.Getenv("GOOGLE_CLIENT_SECRET"),
RedirectURL: os.Getenv("GOOGLE_REDIRECT_URL"),
})),
goauth.WithProvider(github.New(github.Config{
ClientID: os.Getenv("GITHUB_CLIENT_ID"),
ClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"),
RedirectURL: os.Getenv("GITHUB_REDIRECT_URL"),
})),
)
if err != nil {
log.Fatalf("goauth config invalid: %v", err)
}
Auth, err = goauth.New(cfg)
if err != nil {
log.Fatalf("goauth init failed: %v", err)
}
}
Then in main.go:
func main() {
initAuth()
mux := http.NewServeMux()
Auth.Mount(mux)
log.Fatal(http.ListenAndServe(":8080", mux))
}
Index ¶
- Variables
- func ErrNoSchema(driver string) error
- func GenerateSchema(driver, outPath string) error
- func GetSchema(driver string) (string, error)
- func SplitSQL(sql string) []string
- func WithProvider(p port.OAuthProvider) func(*Config)
- type Auth
- func (a *Auth) CheckSession(ctx context.Context, tokenRaw string) bool
- func (a *Auth) Close()
- func (a *Auth) CompleteInviteRegistration(ctx context.Context, input CompleteInviteInput) (*CompleteInviteResult, *domain.AuthError)
- func (a *Auth) GetSession(ctx context.Context, tokenRaw string) (*domain.User, *domain.Session, error)
- func (a *Auth) Login(ctx context.Context, input LoginInput) (*LoginResult, *domain.AuthError)
- func (a *Auth) Mount(mux *http.ServeMux)
- func (a *Auth) Register(ctx context.Context, input RegisterInput) (*RegisterResult, *domain.AuthError)
- type CompleteInviteInput
- type CompleteInviteResult
- type Config
- type CookieConfig
- type DatabaseConfig
- type Driver
- type EmailConfig
- type HandlerGroup
- type LoginInput
- type LoginResult
- type MiddlewareGroup
- type RegisterInput
- type RegisterResult
- type SMTPMailer
- type Services
Constants ¶
This section is empty.
Variables ¶
var ErrNoDatabase = errors.New("go-auth: no database pool or DSN provided")
Functions ¶
func ErrNoSchema ¶
func GenerateSchema ¶
func WithProvider ¶
func WithProvider(p port.OAuthProvider) func(*Config)
WithProvider registers an OAuth provider. The provider's Name() must be non-empty and unique across all registered providers. Nil providers are rejected.
Types ¶
type Auth ¶
type Auth struct {
Config Config
Pool *pgxpool.Pool
DB *sqlstore.DB
Services Services
Handlers HandlerGroup
Middleware MiddlewareGroup
// contains filtered or unexported fields
}
func (*Auth) CheckSession ¶
CheckSession validates a raw session token and returns whether it is valid. It checks the session exists, is not expired, and the associated user exists and is not banned.
func (*Auth) CompleteInviteRegistration ¶
func (a *Auth) CompleteInviteRegistration(ctx context.Context, input CompleteInviteInput) (*CompleteInviteResult, *domain.AuthError)
func (*Auth) GetSession ¶
func (a *Auth) GetSession(ctx context.Context, tokenRaw string) (*domain.User, *domain.Session, error)
GetSession validates a raw session token and returns the associated user and session. Returns the user, session, and nil error on success. Returns nil, nil, error if the token is invalid, expired, or the user is banned.
func (*Auth) Login ¶
func (a *Auth) Login(ctx context.Context, input LoginInput) (*LoginResult, *domain.AuthError)
func (*Auth) Register ¶
func (a *Auth) Register(ctx context.Context, input RegisterInput) (*RegisterResult, *domain.AuthError)
type CompleteInviteInput ¶
type CompleteInviteResult ¶
type Config ¶
type Config struct {
// ─── Application ───────────────────────────────────────────────
AppName string // displayed in email subjects (default "App")
BaseURL string // frontend base URL for email links (e.g. "http://localhost:3000")
// ─── Database ──────────────────────────────────────────────────
Database DatabaseConfig
// ─── Password Policy ───────────────────────────────────────────
PasswordPolicy domain.PasswordPolicy
// ─── Sessions & Tokens ─────────────────────────────────────────
SessionTTL time.Duration // absolute hard expiry (default 30d)
SessionIdleTTL time.Duration // idle timeout after last activity (default 7d)
RefreshTokenTTL time.Duration // refresh token absolute expiry (default 30d)
MaxLifetime time.Duration // max session lifetime from created_at (0 = no limit)
GraceWindow time.Duration // grace period for reusing old refresh token (default 10s)
TouchDebounce time.Duration // minimum interval between last_active_at updates (default 5m)
Cookie CookieConfig
TokenTTL time.Duration // how long verification/reset tokens live (default 1h)
// ─── Email & Verification ──────────────────────────────────────
RequireEmailVerification bool // require email verification on signup (default false)
VerificationCodeTTL time.Duration // how long verification codes live (default 15m)
Mailer port.Mailer // custom mailer implementation (optional)
Email *EmailConfig // SMTP mailer config (used if Mailer is nil)
// ─── Invites ───────────────────────────────────────────────────
InviteOnly bool // only invited users can register (default false)
InviteTTL time.Duration // how long invites last (default 7d)
// ─── Security ──────────────────────────────────────────────────
AllowedOrigins []string // allowed origins for CSRF Origin/Referer check
AllowMissingCSRFHeaders bool // allow requests without Origin/Referer headers (default false)
RateLimit *ratelimit.Config // rate limiting config (optional)
// ─── Logging ──────────────────────────────────────────────────
Logger *slog.Logger // structured logger (default: slog.Default())
// contains filtered or unexported fields
}
Config is the top-level configuration for go-auth. Fields are grouped by concern for readability.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a Config with sensible defaults.
type CookieConfig ¶
type CookieConfig struct {
Name string
Domain string
Path string
Secure bool
SameSite http.SameSite
}
CookieConfig configures the session cookie.
type DatabaseConfig ¶
type DatabaseConfig struct {
URL string // connection string (preferred)
DB *sql.DB // pre-opened *sql.DB (library borrows, does not close)
Pool *pgxpool.Pool // pre-opened pgx pool (library borrows, does not close)
Driver Driver // DriverPostgres (default), DriverSQLite, DriverMySQL
// contains filtered or unexported fields
}
DatabaseConfig configures the database connection. Provide one of URL, DB, or Pool. URL is the preferred option — the library will open, validate, and close the connection automatically.
type EmailConfig ¶
EmailConfig configures SMTP email delivery.
type HandlerGroup ¶
type HandlerGroup struct {
Register http.HandlerFunc
Login http.HandlerFunc
Logout http.HandlerFunc
ForgotPassword http.HandlerFunc
ResetPassword http.HandlerFunc
ChangePassword http.HandlerFunc
SetPasswordRequest http.HandlerFunc
SetPasswordConfirm http.HandlerFunc
VerifyEmail http.HandlerFunc
ResendVerification http.HandlerFunc
ResendVerificationPublic http.HandlerFunc
ListSessions http.HandlerFunc
RevokeSession http.HandlerFunc
RevokeAllSessions http.HandlerFunc
InviteRegister http.HandlerFunc
CheckSession http.HandlerFunc
RefreshToken http.HandlerFunc
GetMe http.HandlerFunc
ChangeName http.HandlerFunc
DeleteAccount http.HandlerFunc
RequestDeleteAccount http.HandlerFunc
ConfirmDeleteAccount http.HandlerFunc
ListUsers http.HandlerFunc
UpdateUserRole http.HandlerFunc
BanUser http.HandlerFunc
UnbanUser http.HandlerFunc
DeleteUser http.HandlerFunc
RevokeUserSessions http.HandlerFunc
AdminCreateUser http.HandlerFunc
AdminListUserSessions http.HandlerFunc
AdminRevokeUserSession http.HandlerFunc
GetInviteInfo http.HandlerFunc
CreateInvite http.HandlerFunc
ListInvites http.HandlerFunc
RevokeInvite http.HandlerFunc
ResendInvite http.HandlerFunc
HardDeleteInvite http.HandlerFunc
OAuthInitiate http.HandlerFunc
OAuthCallback http.HandlerFunc
OAuthLink http.HandlerFunc
OAuthUnlink http.HandlerFunc
OAuthProviders http.HandlerFunc
}
type LoginInput ¶
type LoginResult ¶
type MiddlewareGroup ¶
type RegisterInput ¶
type RegisterResult ¶
type SMTPMailer ¶
type SMTPMailer struct {
// contains filtered or unexported fields
}
type Services ¶
type Services struct {
Auth *service.AuthService
Password *service.PasswordService
Session *service.SessionService
Verify *service.VerificationService
Invite *service.InviteService
Admin *service.AdminService
OAuth *service.OAuthService
}