behemoth

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: May 12, 2025 License: MIT Imports: 10 Imported by: 0

README

Behemoth: Authentication Library for Golang

Behemoth is a flexible authentication library for Go applications. It simplifies adding common authentication strategies like password-based login and OAuth 2.0 with JWT or Sessions. It handles user registration, authentication, and management, with various database integrations like Postgres and SQLite through a configurable interface. Behemoth provides a basic User Model with full built in CRUD features. It’s also compatible with custom user models and supports additional OAuth providers.

Installation

$ go get github.com/MastewalB/behemoth

Supported Databases

  • PostgreSQL
  • SQLite

Examples

Create a Behemoth instance with built-in User Model.

import (
    "github.com/MastewalB/behemoth"
    "github.com/MastewalB/behemoth/models"
)

// Custom providers can be added to this list
oauthProviders := []behemoth.Provider{
		providers.NewGoogle(
			"GoogleClientID",
			"GoogleClientSecret",
			"GoogleRedirectURL",
			"email", "profile",
		),
		providers.NewFacebook(
			"FBClientID",
			"FBClientSecret",
			"FBRedirectURL",
			"email", "public_profile",
		),
	}

func main() {
	pgCfg := &behemoth.Config[*models.User]{
		DatabaseConfig: behemoth.DatabaseConfig[*models.User]{
			Name:           behemoth.Postgres,
			DB:             pg,
			UseDefaultUser: true,
		},
		Password:       &behemoth.PasswordConfig{HashCost: 10},
		OAuthProviders: oauthProviders,
		JWT:            &behemoth.JWTConfig{Secret: "mysecret", Expiry: 24 * time.Hour},
		UseSessions:    true,
		Session: &behemoth.SessionConfig{
			CookieName: "session_id",
			Expiry:     2 * time.Hour,
			Factory: func(id string) behemoth.Session {
				return behemoth.NewDefaultSession(id, time.Hour)
			},
		},
	}
	
	behemoth, err := auth.New(config)

}

Check examples for a demo application using PostgreSQL and SQLite.

Clone the repo and create .env file containing the client credentials for the providers used in examples/main.go.

$ cd examples/
$ go run main.go

Open http://localhost:8080 in your browser.

Supported Providers

  • Google
  • Facebook
  • Github
  • Apple
  • Amazon

Custom providers can be added by implementing the Provider interface.

User Models

Behemoth accepts any User model which implements the User interface. It also provides a built-in lightweight user model.

The User Model is configured together with the database using the DatabaseConfig type:

type DatabaseConfig[T User] struct {
	Name           DatabaseName
	DB             *sql.DB
	UserTable      string
	PrimaryKey     string
	FindUserFn     FindUserFn
	UserModel      User
	UseDefaultUser bool
}

A UserModel type should be provided if the UseDefaultUser flag is not set to true. Either a Database connection(DB) or a User Finder Function(FindUserFn) must be provided to retrieve users. To retrieve a user from the database, the FindUserFn is called if present, otherwise type reflection will be used to construct the user entity.

JWT

The JWTService type is responsible for handling JSON Web Token operations. It uses the golang-jwt package to sign and validate tokens. Tokens can be configured through the JWTConfig struct

import "github.com/golang-jwt/jwt/v5"

type JWTConfig struct {
	Secret        string
	Expiry        time.Duration
	SigningMethod jwt.SigningMethod
	Claims        jwt.Claims
}

By default tokens are signed with jwt.SigningMethodHS256. JWT tokens will be used as default authentication method if Sessions are not configured explicitly. Claims can be customized as long as they implement the jwt.Claims interface.

Session

Sessions can be enabled using the UseSession flag in the config struct. A default Config will be used if no custom SessionConfig is provided.

type SessionConfig struct {
	CookieName string
	Expiry     time.Duration
	Factory    SessionFactory
}

A custom session type should implement the Session interface and provide a SessionFactory function.

Upcoming Features

  • Revocable JWT Tokens
  • Support for Gin and Echo routers

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefalultSessionConfig = SessionConfig{
	CookieName: "session_id",
	Expiry:     2 * time.Hour,
	Factory: func(id string) Session {
		return NewDefaultSession(id, 2*time.Hour)
	},
}
View Source
var DefaultJWTConfig = JWTConfig{
	Secret:        utils.GenerateRandomString(64),
	Expiry:        24 * time.Hour,
	SigningMethod: jwt.SigningMethodHS256,
}
View Source
var DefaultPasswordConfig = PasswordConfig{
	HashCost: 10,
}

Functions

This section is empty.

Types

type Config

type Config[T User] struct {
	DatabaseConfig DatabaseConfig[T]
	JWT            *JWTConfig
	Session        *SessionConfig
	Password       *PasswordConfig
	OAuthProviders []Provider
	UseSessions    bool
}

type Database

type Database[T User] interface {

	// FindByPK retrieves a user object from the database
	FindByPK(val any) (T, error)

	// SaveUser persists a user object to the database
	SaveUser(user *models.User) (*models.User, error)

	// UpdateUser updates a user object in the database. User should be instance of models.User.
	UpdateUser(user *models.User) (*models.User, error)

	// DeleteUser removes a user object from the database. User should be instance of models.User.
	DeleteUser(user *models.User) error

	// GetAllUsers retrieves all users from the database.
	GetAllUsers() ([]T, error)

	// SaveSession stores a session in the database with its expiration time.
	SaveSession(session Session, expiresAt time.Time) error

	// GetSession retrieves a session by ID, returning an error if not found or expired.
	GetSession(sessionID string) (Session, error)

	// DeleteSession removes a session by ID.
	DeleteSession(sessionID string) error
}

Database is an interface that defines the methods for interacting with a database.

type DatabaseConfig

type DatabaseConfig[T User] struct {
	Name           DatabaseName
	DB             *sql.DB
	UserTable      string
	PrimaryKey     string
	FindUserFn     FindUserFn
	UserModel      User
	UseDefaultUser bool
}

DatabaseConfig defines configuration for database connection and user model/table.

type DatabaseName

type DatabaseName string

DatabaseName is a string type that represents the name of the database.

const (
	SQLite   DatabaseName = "sqlite"
	Postgres DatabaseName = "postgres"
)

type FindUserFn

type FindUserFn func(db, val any) (User, error)

FindUser is a customized function type that takes a value of any type and returns a User type The database interface will use this function if provided, instead of retrieving the user by type reflection.

type JWTConfig

type JWTConfig struct {
	Secret        string
	Expiry        time.Duration
	SigningMethod jwt.SigningMethod
	Claims        jwt.Claims
}

type PasswordConfig

type PasswordConfig struct {
	HashCost int
}

type Provider

type Provider interface {
	// Name returns the name of the provider
	Name() string

	// GetEndpoint returns the OAuth endpoint
	GetEndpoint() oauth2.Endpoint

	// GetScopes returns the scopes provided for the OAuth.
	GetScopes() []string

	// GetConfig returns the oauth2 config
	GetConfig() *oauth2.Config

	// FetchUserInfo retrieves user information from the OAuth provider and returns UserInfo type.
	FetchUserInfo(client *http.Client, ctx context.Context, token *oauth2.Token) (models.UserInfo, error)
}

Provider defines the interface for OAuth providers like Google or Facebook. It provides methods to retrieve provider-specific OAuth endpoints, scopes, and user information.

type Session

type Session interface {

	// Set inserts a key with a value in the session
	Set(key, value any) error

	// Get returns a value associated with a key in the session
	Get(key any) any

	// Delete removes a key from the session
	Delete(key any) error

	// SessionID returns the unique session ID
	SessionID() string

	// MarshalJSON serializes the session data to JSON.
	MarshalJSON() ([]byte, error)

	// UnmarshalJSON deserializes JSON data into the session.
	UnmarshalJSON(data []byte) error
}

func NewDefaultSession

func NewDefaultSession(id string, expiry time.Duration) Session

NewDefaultSession creates a new DefaultSession with the given ID.

type SessionConfig

type SessionConfig struct {
	CookieName string
	Expiry     time.Duration
	Factory    SessionFactory
}

type SessionFactory

type SessionFactory = func(id string) Session

SessionFactory is a type alias for a function that creates a new Session instance with the given ID.

type SessionStore

type SessionStore interface {

	// SaveSession stores a session with its expiration time.
	SaveSession(session Session, expiresAt time.Time) error

	// GetSession retrieves a session by ID, returning an error if not found or expired.
	GetSession(sessionID string) (Session, error)

	// DeleteSession removes a session by ID.
	DeleteSession(sessionID string) error
}

SessionStore defines the interface for storing and retrieving sessions.

type User

type User interface {
	GetID() string
	GetPasswordHash() string
}

func FindUserByEmailPG

func FindUserByEmailPG(dbConn, val any) (User, error)

FindUserByEmailPG is a function that retrieves a user by email from a PostgreSQL database. It will be automatically passed to the database if the default user model is used.

func FindUserByEmailSQLite

func FindUserByEmailSQLite(dbConn, val any) (User, error)

FindUserByEmailSQLite is a function that retrieves a user by email from a SQLite database. It will be automatically passed to the database if the default user model is used.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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