goauth

package module
v0.0.0-...-c7f5c52 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 2026 License: MIT Imports: 23 Imported by: 0

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

Constants

This section is empty.

Variables

View Source
var ErrNoDatabase = errors.New("go-auth: no database pool or DSN provided")

Functions

func ErrNoSchema

func ErrNoSchema(driver string) error

func GenerateSchema

func GenerateSchema(driver, outPath string) error

func GetSchema

func GetSchema(driver string) (string, error)

func SplitSQL

func SplitSQL(sql string) []string

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 New

func New(config Config) (*Auth, error)

func (*Auth) CheckSession

func (a *Auth) CheckSession(ctx context.Context, tokenRaw string) bool

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) Close

func (a *Auth) Close()

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) Mount

func (a *Auth) Mount(mux *http.ServeMux)

func (*Auth) Register

func (a *Auth) Register(ctx context.Context, input RegisterInput) (*RegisterResult, *domain.AuthError)

type CompleteInviteInput

type CompleteInviteInput struct {
	Code            string
	Name            string
	Password        string
	ConfirmPassword string
}

type CompleteInviteResult

type CompleteInviteResult struct {
	User         *domain.User
	Session      *domain.Session
	SessionToken string
	RefreshToken string
}

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.

func NewConfig

func NewConfig(opts ...func(*Config)) (Config, error)

NewConfig applies the given option functions to DefaultConfig and validates. If validation fails, the returned error includes all invalid fields.

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 Driver

type Driver string
const (
	DriverPostgres Driver = "postgres"
	DriverSQLite   Driver = "sqlite3"
	DriverMySQL    Driver = "mysql"
)

type EmailConfig

type EmailConfig struct {
	From string
	Host string
	Port int
	User string
	Pass string
}

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 LoginInput struct {
	Email     string
	Password  string
	IP        string
	UserAgent string
}

type LoginResult

type LoginResult struct {
	User                 *domain.User
	Session              *domain.Session
	SessionToken         string
	RefreshToken         string
	RequiresVerification bool
}

type MiddlewareGroup

type MiddlewareGroup struct {
	Authenticate func(http.Handler) http.Handler
	RequireAdmin func(http.Handler) http.Handler
	RateLimit    func(http.Handler) http.Handler
	CORS         func(http.Handler) http.Handler
}

type RegisterInput

type RegisterInput struct {
	Email    string
	Password string
	Name     string
}

type RegisterResult

type RegisterResult struct {
	User                 *domain.User
	Session              *domain.Session
	SessionToken         string
	RefreshToken         string
	RequiresVerification bool
}

type SMTPMailer

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

func (*SMTPMailer) Send

func (m *SMTPMailer) Send(ctx context.Context, to, subject, html, text string) error

Directories

Path Synopsis
internal
provider

Jump to

Keyboard shortcuts

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