beaconauth

package module
v0.6.3 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2025 License: MIT Imports: 4 Imported by: 0

README

BeaconAuth

Go Reference Go Report Card CI Release

A modular, plugin-based authentication library for Go with support for multiple databases, OAuth providers, and web frameworks.

Features

  • 🔌 Plugin Architecture - Extend with OAuth, 2FA, magic links, and custom plugins
  • 🗄️ Database Agnostic - PostgreSQL, MySQL, MongoDB, SQLite, or custom adapters
  • Framework Flexible - Fiber, Chi, Gin, Echo, Gorilla Mux, or standard net/http
  • 🔒 Secure by Default - CSRF protection, rate limiting, secure sessions
  • 🛠️ CLI Tool - Built-in CLI for easy schema generation and maintenance
  • 📦 Production Ready - Built-in session management, migrations, and security features

Installation

go get github.com/marshallshelly/beacon-auth

Quick Start

package main

import (
    "log"
    "net/http"

    "github.com/marshallshelly/beacon-auth"
    "github.com/marshallshelly/beacon-auth/adapters/postgres"
)

func main() {
    // Initialize database adapter
    adapter, err := postgres.New(&postgres.Config{
        Host:     "localhost",
        Port:     5432,
        User:     "postgres",
        Password: "password",
        Database: "myapp",
    })
    if err != nil {
        log.Fatal(err)
    }

    // Initialize BeaconAuth
    auth, err := beaconauth.New(
        beaconauth.WithAdapter(adapter),
        beaconauth.WithSecret("your-secret-key"),
    app := fiber.New()

    // Database adapter
    db, _ := postgres.New(context.Background(), &postgres.Config{
        Host: "localhost", Port: 5432, Database: "myapp",
        Username: "postgres", Password: "password",
    })
    defer db.Close()

    // Session manager
    sm, _ := session.NewManager(&session.Config{
        CookieName: "session", CookieSecure: true,
        ExpiresIn: 24 * time.Hour, EnableDBStore: true,
        Secret: "your-secret-at-least-32-bytes-long",
        Issuer: "myapp",
    }, db)

    // Session middleware
    app.Use(beaconfiber.SessionMiddleware(sm))

    // Auth routes
    authHandler := beaconfiber.NewHandler(db, sm, &auth.Config{
        MinPasswordLength: 8,
        AllowSignup:       true,
    })
    app.Post("/auth/signup", authHandler.SignUp)
    app.Post("/auth/signin", authHandler.SignIn)
    app.Post("/auth/signout", authHandler.SignOut)

    // Protected routes
    api := app.Group("/api")
    api.Use(beaconfiber.RequireAuthJSON(sm))
    api.Get("/profile", func(c *fiber.Ctx) error {
        user := beaconfiber.GetUser(c)
        return c.JSON(fiber.Map{"user": user})
    })

    log.Fatal(app.Listen(":3000"))
}

Multi-Tenant Support:

// Tenant extraction from subdomain
tenantConfig := &beaconfiber.TenantConfig{
    BaseDomain: "myapp.com", // Extract from tenant1.myapp.com
}
app.Use(beaconfiber.TenantMiddleware(tenantConfig))

// Tenant-specific databases
app.Use(beaconfiber.TenantIsolationMiddleware(getTenantDB))

// Access tenant in routes
tenant := beaconfiber.GetTenant(c)

See Fiber Integration Guide for complete documentation.

OAuth Providers

BeaconAuth supports multiple OAuth providers out of the box:

import (
    "github.com/marshallshelly/beacon-auth/plugins/oauth"
    "github.com/marshallshelly/beacon-auth/plugins/oauth/providers"
)

// GitHub
githubProvider := providers.NewGitHub(
    "your-client-id",
    "your-client-secret",
    []string{"user:email"},
)

// Google (with PKCE)
googleProvider := providers.NewGoogle(&providers.GoogleOptions{
    ClientID:     "your-client-id",
    ClientSecret: "your-client-secret",
    AccessType:   "offline", // For refresh tokens
})

// Discord
discordProvider := providers.NewDiscord(&providers.DiscordOptions{
    ClientID:     "your-client-id",
    ClientSecret: "your-client-secret",
    Prompt:       "none", // or "consent"
})

// Add to BeaconAuth
auth, _ := beaconauth.New(
    beaconauth.WithAdapter(adapter),
    beaconauth.WithPlugins(
        oauth.New(githubProvider, googleProvider, discordProvider),
    ),
    // ... other options
)

Project Status

🚧 In Development - BeaconAuth is currently under active development. The API may change.

Current Progress

Core Infrastructure:

  • Core infrastructure
  • Configuration system
  • Context management
  • Error handling
  • Logging system

Data Layer:

  • Adapter system with automatic type transformations
  • Memory adapter (for testing)
  • PostgreSQL adapter
  • MongoDB adapter
  • MySQL adapter
  • SQLite adapter
  • MSSQL adapter

Session Management:

  • Multi-layer session management (Cookie, Redis, Database)
  • Session strategies (Redis-first, DB-first, Cookie-only, etc.)
  • Automatic TTL and cleanup
  • Session middleware

Authentication:

  • Password hashing (Argon2id)
  • Secure token generation
  • Email/Password authentication handlers

Plugins:

  • Plugin system foundation
  • OAuth plugin (4 providers: GitHub, Google, Discord, Apple)
  • Email/Password plugin
  • Two-Factor Authentication (TOTP + backup codes)
  • Magic link plugin
  • Passkey/WebAuthn plugin
  • Additional OAuth providers (Microsoft, Twitter, Facebook, etc.)

Framework Integrations:

  • Fiber (with multi-tenant support)
  • Chi
  • Gin
  • Echo
  • Standard net/http

Documentation:

  • Comprehensive inline documentation
  • Example code and tests
  • Documentation website (beaconauth.dev)

Architecture

BeaconAuth follows a modular architecture with these core components:

  • Core - Main authentication logic and interfaces
  • Adapters - Database adapters for different databases
  • Plugins - Extensible plugin system for adding features
  • Integrations - Framework-specific integrations
  • Session - Multi-layer session management
  • Security - Rate limiting, CSRF protection, password hashing

Documentation

Coming soon! Full documentation will be available at beaconauth.dev

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT License - see LICENSE file for details

Acknowledgments

Inspired by better-auth - bringing modern auth patterns to Go.

Documentation

Overview

Package beaconauth provides a modular, plugin-based authentication library for Go

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	WithSecret         = core.WithSecret
	WithBaseURL        = core.WithBaseURL
	WithBasePath       = core.WithBasePath
	WithAdapter        = core.WithAdapter
	WithPlugins        = core.WithPlugins
	WithMailer         = core.WithMailer
	WithOAuthProviders = core.WithOAuthProviders
	WithRateLimit      = core.WithRateLimit
	WithSessionConfig  = core.WithSessionConfig
	WithEmailPassword  = core.WithEmailPassword
	WithLogger         = core.WithLogger
	WithTrustedOrigins = core.WithTrustedOrigins
)

Configuration options

View Source
var (
	ErrInvalidCredentials = core.ErrInvalidCredentials
	ErrUserNotFound       = core.ErrUserNotFound
	ErrSessionNotFound    = core.ErrSessionNotFound
	ErrSessionExpired     = core.ErrSessionExpired
	ErrEmailTaken         = core.ErrEmailTaken
	ErrInvalidEmail       = core.ErrInvalidEmail
	ErrInvalidPassword    = core.ErrInvalidPassword
	ErrEmailNotVerified   = core.ErrEmailNotVerified
	ErrUnauthorized       = core.ErrUnauthorized
	ErrForbidden          = core.ErrForbidden
	ErrNotFound           = core.ErrNotFound
	ErrBadRequest         = core.ErrBadRequest
	ErrInternalServer     = core.ErrInternalServer
)

Common errors

Functions

This section is empty.

Types

type Account

type Account = core.Account

Account represents an authentication account

type Auth

type Auth = core.Auth

Auth is the main authentication interface

func New

func New(opts ...Option) (Auth, error)

New creates a new BeaconAuth instance

Example
package main

import (
	"fmt"
	"log"

	beaconauth "github.com/marshallshelly/beacon-auth"
	"github.com/marshallshelly/beacon-auth/adapters/memory"
)

type SilentLogger struct{}

func (l *SilentLogger) Debug(msg string, fields ...interface{}) {}
func (l *SilentLogger) Info(msg string, fields ...interface{})  {}
func (l *SilentLogger) Warn(msg string, fields ...interface{})  {}
func (l *SilentLogger) Error(msg string, fields ...interface{}) {}

func main() {
	// Initialize memory adapter
	adapter := memory.New()

	// Initialize BeaconAuth with silent logger to avoid random output in test
	authInstance, err := beaconauth.New(
		beaconauth.WithAdapter(adapter),
		beaconauth.WithSecret("test-secret-key-must-be-32-bytes-long!"),
		beaconauth.WithBaseURL("http://localhost:3000"),
		beaconauth.WithLogger(&SilentLogger{}),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer authInstance.Close()

	fmt.Println("BeaconAuth initialized successfully")

}
Output:
BeaconAuth initialized successfully

type Config

type Config = core.Config

Config holds the authentication configuration

type Option

type Option = core.Option

Option is a functional option for configuring BeaconAuth

type Session

type Session = core.Session

Session represents a user session

type User

type User = core.User

User represents an authenticated user

Directories

Path Synopsis
adapters
cmd
beacon command
integrations
chi
gin
mux
plugins

Jump to

Keyboard shortcuts

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