lognify

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2026 License: MIT Imports: 2 Imported by: 0

README ΒΆ

πŸ” Loginfy-go

Plug-and-play authentication and authorization framework for Go applications

Go Reference Tests


Lognify.go (module: loginfy.go) is a modular, extensible authentication and authorization framework for Go. It provides everything you need to add secure auth to your application β€” strategies, sessions, RBAC, policy-based authorization, middleware, hooks, and structured logging β€” all with a clean, composable API.

✨ Features

  • Modular Auth Strategies β€” Plug in email/password, OAuth (coming soon), or build your own
  • JWT Session Management β€” Stateless token-based sessions with HMAC-SHA256 signing
  • Role-Based Access Control (RBAC) β€” Define roles, assign permissions, enforce with middleware
  • Policy-Based Authorization β€” Fine-grained resource-level access control
  • Storage Adapters β€” In-memory (built-in), MongoDB (planned), or implement your own
  • HTTP Middleware β€” RequireAuth, RequireRole, RequirePermission for net/http
  • Lifecycle Hooks β€” OnLogin, OnRegister callbacks for custom logic
  • Structured Logging β€” Built-in service logger with sessions, levels, and colored output

πŸš€ Quick Start

package main

import (
    "fmt"
    "github.com/AryanAg08/loginfy-go/core"
    "github.com/AryanAg08/loginfy-go/strategies/emailPassword"
    "github.com/AryanAg08/loginfy-go/storage/memory"
    "github.com/AryanAg08/loginfy-go/sessions/jwt"
)

func main() {
    app := core.New()
    app.Use(emailPassword.New())
    app.SetStorage(memory.New())
    app.SetSessionManager(jwt.New(jwt.Config{Secret: "my-secret"}))

    // Register, authenticate, create sessions β€” you're ready!
    fmt.Println("Lognify is running!")
}

πŸ“¦ Installation

go get github.com/AryanAg08/loginfy-go

Requires Go 1.21+.

πŸ“– Usage

Basic Setup with Email/Password
package main

import (
    "fmt"
    "time"

    "github.com/AryanAg08/loginfy-go/core"
    "github.com/AryanAg08/loginfy-go/strategies/emailPassword"
    "github.com/AryanAg08/loginfy-go/storage/memory"
    "github.com/AryanAg08/loginfy-go/sessions/jwt"
)

func main() {
    // 1. Create the Loginfy instance
    app := core.New()

    // 2. Register the email/password strategy
    app.Use(emailPassword.New())

    // 3. Set up storage and session manager
    app.SetStorage(memory.New())
    app.SetSessionManager(jwt.New(jwt.Config{
        Secret:     "your-secret-key",
        Expiration: 24 * time.Hour,
    }))

    // 4. Register a user
    strategy, _ := app.GetStrategy("email_password")
    ep := strategy.(*emailPassword.EmailPasswordStrategy)

    ctx := &core.Context{Loginfy: app, RequestID: "setup"}
    ctx.Set("email", "user@example.com")
    ctx.Set("password", "securepass123")

    user, err := ep.Register(ctx)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Registered: %s (%s)\n", user.Email, user.ID)

    // 5. Authenticate
    authCtx := &core.Context{Loginfy: app, RequestID: "login"}
    authCtx.Set("email", "user@example.com")
    authCtx.Set("password", "securepass123")

    user, err = app.Authenticate("email_password", authCtx)
    if err != nil {
        panic(err)
    }

    // 6. Create a JWT session
    token, _ := app.Login(user)
    fmt.Printf("Token: %s\n", token)
}
OAuth (Planned for v0.2)

OAuth strategies (Google, GitHub, etc.) are on the roadmap. You'll be able to add them the same way:

// Coming in v0.2
app.Use(oauth.NewGoogle(oauth.GoogleConfig{
    ClientID:     "...",
    ClientSecret: "...",
    RedirectURL:  "http://localhost:8080/callback",
}))
JWT Session Management
import "github.com/AryanAg08/loginfy-go/sessions/jwt"

sm := jwt.New(jwt.Config{
    Secret:     "your-256-bit-secret",
    Expiration: 2 * time.Hour,
})

// Create a session token
token, err := sm.CreateSession(user.ID)

// Create with full user details embedded
token, err = sm.CreateSessionWithUser(user)

// Validate a token
userID, err := sm.ValidateSession(ctx, token)

// Validate and get full claims
claims, err := sm.ValidateSessionWithClaims(ctx, token)
// claims.UserID, claims.Email, claims.Roles, claims.ExpiresAt

// Destroy session (logout)
err = sm.DestroySession(ctx, token)
RBAC Authorization
import "github.com/AryanAg08/loginfy-go/authorization"

auth := authorization.New()

// Define roles with permissions
auth.DefineRole("admin", "users:read", "users:write", "users:delete")
auth.DefineRole("editor", "posts:read", "posts:write")
auth.DefineRole("viewer", "posts:read")

// Grant/revoke individual permissions
auth.GrantPermission("editor", "posts:delete")
auth.RevokePermission("editor", "posts:delete")

// Check permissions
if auth.HasPermission(user, "users:write") {
    // User has permission via one of their roles
}
Policy-Based Authorization
auth := authorization.New()

// Define policies for fine-grained access control
auth.AllowPolicy("edit-post", func(user *core.User, resource interface{}) bool {
    post := resource.(*Post)
    return post.AuthorID == user.ID || user.HasRole("admin")
})

// Check policy
if auth.Can(user, "edit-post", post) {
    // User can edit this specific post
}
Middleware Usage
import "github.com/AryanAg08/loginfy-go/middleware"

mux := http.NewServeMux()

// Mount Loginfy context (required for other middleware)
handler := app.Mount()(mux)

// Require any valid auth token
mux.Handle("/api/data", middleware.RequireAuth(dataHandler))

// Require valid JWT + load user into context
mux.Handle("/api/profile",
    middleware.RequireAuthWithLoginfy(app)(profileHandler))

// Require specific roles
mux.Handle("/api/admin",
    middleware.RequireAuthWithLoginfy(app)(
        middleware.RequireRole(app, "admin")(adminHandler)))

// Require specific permission
mux.Handle("/api/posts/delete",
    middleware.RequireAuthWithLoginfy(app)(
        middleware.RequirePermission(app, "posts:delete")(deleteHandler)))
Hooks
app.SetHooks(core.Hooks{
    OnLogin: func(user *core.User) {
        fmt.Printf("User logged in: %s\n", user.Email)
        // Send notification, update last login, etc.
    },
    OnRegister: func(user *core.User) {
        fmt.Printf("New user registered: %s\n", user.Email)
        // Send welcome email, initialize defaults, etc.
    },
})
Storage Adapters
import "github.com/AryanAg08/loginfy-go/storage/memory"

// In-memory storage (great for development/testing)
store := memory.New()
app.SetStorage(store)

// Storage interface β€” implement for any backend:
// CreateUser, GetUserByEmail, GetUserById, UpdateUser, DeleteUser

MongoDB support is planned for a future release. See Storage Adapters Guide for how to build your own.

πŸ— Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                   Your Application                  β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                  HTTP Middleware                     β”‚
β”‚   RequireAuth β”‚ RequireRole β”‚ RequirePermission      β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚   Strategies  β”‚  Sessions   β”‚   Authorization       β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚Email/Passβ”‚ β”‚ β”‚   JWT   β”‚ β”‚  β”‚  RBAC + Policy  β”‚  β”‚
β”‚  β”‚  OAuth*  β”‚ β”‚ β”‚         β”‚ β”‚  β”‚                 β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                    Core (Loginfy)                    β”‚
β”‚          Context β”‚ User β”‚ Hooks β”‚ Errors            β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                  Storage Adapters                   β”‚
β”‚              Memory β”‚ MongoDB* β”‚ Custom             β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                   pkg/ Utilities                    β”‚
β”‚           crypto β”‚ logger β”‚ constants β”‚ status      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                    * = planned

πŸ“ Project Structure

loginfy.go/
β”œβ”€β”€ core/                   # Core types: Loginfy, User, Context, Strategy, Storage interfaces
β”‚   β”œβ”€β”€ loginfy.go          # Main Loginfy struct and methods
β”‚   β”œβ”€β”€ user.go             # User model with role helpers
β”‚   β”œβ”€β”€ context.go          # Request context with data store
β”‚   β”œβ”€β”€ startegy.go         # Strategy interface
β”‚   β”œβ”€β”€ storage.go          # Storage interface
β”‚   β”œβ”€β”€ session.go          # SessionManager interface
β”‚   β”œβ”€β”€ hooks.go            # OnLogin/OnRegister hooks
β”‚   └── errors.go           # Sentinel errors
β”œβ”€β”€ strategies/
β”‚   └── emailPassword/      # Email + password authentication strategy
β”œβ”€β”€ sessions/
β”‚   └── jwt/                # JWT session manager (HMAC-SHA256)
β”œβ”€β”€ storage/
β”‚   β”œβ”€β”€ memory/             # Thread-safe in-memory storage
β”‚   └── mongodb/            # MongoDB adapter (placeholder)
β”œβ”€β”€ authorization/          # RBAC roles/permissions + policy engine
β”œβ”€β”€ middleware/              # HTTP middleware (RequireAuth, RequireRole, etc.)
β”œβ”€β”€ pkg/
β”‚   β”œβ”€β”€ crypto/             # Password hashing (bcrypt), token generation
β”‚   β”œβ”€β”€ logger/             # Structured logging with sessions and service loggers
β”‚   β”œβ”€β”€ constants/          # Shared constants
β”‚   └── status/             # HTTP status helpers
β”œβ”€β”€ examples/               # Working example applications
β”œβ”€β”€ tests/                  # Test suite
└── docs/                   # Documentation

βš™οΈ Configuration

JWT Session Config
Field Type Default Description
Secret string required HMAC-SHA256 signing key
Expiration time.Duration 24h Token expiration duration
Logger Config
Field Type Default Description
Service string "" Service name for log entries
Level Level INFO Minimum log level
TimeFormat string RFC3339 Timestamp format
LogDir string "" Directory for session log files
UseColor bool false Enable colored console output
JSONOutput bool false Output logs as JSON

πŸ”’ Security Features

  • bcrypt Password Hashing β€” Industry-standard adaptive hashing via golang.org/x/crypto
  • HMAC-SHA256 JWT Signing β€” Tamper-proof stateless tokens
  • Constant-Time Comparison β€” Prevents timing attacks on token validation
  • Cryptographically Secure Token Generation β€” Uses crypto/rand for IDs and API keys
  • Password Never Serialized β€” User.Password tagged with json:"-"
  • Structured Error Handling β€” Sentinel errors prevent information leakage

🀝 Contributing

Contributions are welcome! Here's how to get started:

  1. Fork the repository
  2. Clone your fork: git clone https://github.com/AryanAg08/loginfy-go.git
  3. Create a branch: git checkout -b feature/my-feature
  4. Make changes and add tests
  5. Run tests: go test ./...
  6. Commit: git commit -m "feat: add my feature"
  7. Push: git push origin feature/my-feature
  8. Open a Pull Request

Please follow Conventional Commits for commit messages.

πŸ“„ License

This project is licensed under the MIT License β€” see the LICENSE file for details.

Copyright (c) 2026 Aryan Goyal

πŸ—Ί Roadmap

Version Milestone Features
v0.1 (current) Foundation Core framework, email/password, JWT, memory storage, middleware
v0.2 OAuth Google, GitHub, Discord OAuth strategies
v0.3 Authorization Enhanced RBAC, permission inheritance, audit logging
v0.4 Advanced MongoDB/PostgreSQL storage, rate limiting, 2FA, refresh tokens

Built with ❀️ by Aryan Goyal

Documentation ΒΆ

Overview ΒΆ

Package lognify provides a plug-and-play authentication and authorization framework for Go applications. It supports multiple authentication strategies, OAuth providers, JWT and session management, RBAC and policy-based authorization, storage adapters, and middleware integration.

Quick Start:

import lognify "github.com/AryanAg08/loginfy-go"

auth := lognify.New()
auth.Use(emailpassword.New())
auth.SetStorage(memory.New())
auth.SetSessionManager(jwt.New("your-secret", time.Hour))

For more information, see https://github.com/AryanAg08/loginfy-go

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

This section is empty.

Functions ΒΆ

func Configure ΒΆ

func Configure(l *core.Loginfy, opts ...Option)

Configure applies options to a Loginfy instance.

func New ΒΆ

func New() *core.Loginfy

New creates a new Lognify authentication instance.

func NewAuthorization ΒΆ

func NewAuthorization() *authorization.Authorizer

NewAuthorization creates a new RBAC authorization manager.

Types ΒΆ

type Option ΒΆ

type Option func(*core.Loginfy)

WithJWTSecret is a convenience option type for configuring JWT secret.

func WithSessionManager ΒΆ

func WithSessionManager(sm core.SessionManager) Option

WithSessionManager returns an option that sets the session manager.

func WithStorage ΒΆ

func WithStorage(s core.Storage) Option

WithStorage returns an option that sets the storage adapter.

Directories ΒΆ

Path Synopsis
examples
basic-server command
logger-usage command
pkg
providers
sessions
jwt
storage
sql
strategies

Jump to

Keyboard shortcuts

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