authingo

package module
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Apr 28, 2026 License: MIT Imports: 9 Imported by: 0

README ΒΆ

AuthInGo πŸ”

A lightweight, developer-first authentication library for Go and React. Build secure, cookie-based auth in minutes without the bloat of a full identity provider.

Features

  • Go Core: Opaque token session management for high security.
  • Refresh Token Rotation: Built-in silent refreshing (15-min access / 30-day refresh) to prevent session hijacking without interrupting the user.
  • Postgres Adapter: Isolated, built-in support for scalable data storage.
  • React SDK: Global <AuthProvider> with smart request queueing to prevent "Thundering Herd" API failures.
  • Security First: HttpOnly, Secure, and SameSite cookie defaults.

Quick Start (Go Backend)

go get github.com/binit2-1/authingo
go get github.com/binit2-1/authingo/adapters/postgres
package main

import (
    "database/sql"
    "net/http"

    "github.com/binit2-1/authingo"
    "github.com/binit2-1/authingo/adapters/postgres"
    _ "github.com/jackc/pgx/v5/stdlib"
)

func main() {
    db, _ := sql.Open("pgx", "postgres://user:pass@localhost:5432/mydb")
    
    auth := authingo.New(authingo.Options{
        Store: postgres.NewAdapter(db),
    })

    mux := http.NewServeMux()

    // 1. Mount the core authentication endpoints (/sign-in, /sign-up, /refresh, etc.)
    mux.Handle("/api/auth/", http.StripPrefix("/api/auth", auth.Handler()))

    // 2. Protect your custom routes with built-in middleware
    mux.Handle("/api/protected", auth.RequireAuth(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Only logged-in users can see this!"))
    })))

    http.ListenAndServe(":8080", mux)
}

Quick Start (React Frontend)

npm install @authingo/react

1. Wrap your application in the Provider

Provide global state and enable the silent refresh interceptor by wrapping your app (e.g., in Next.js layout.tsx or React App.tsx).

import { AuthProvider } from "@authingo/react";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html>
      <body>
        <AuthProvider baseURL="http://localhost:8080/api/auth">
          {children}
        </AuthProvider>
      </body>
    </html>
  );
}

2. Read state and trigger actions

Use the useAuth() hook to read the global state, and the createAuthClient to trigger server actions.

"use client";

import { useAuth, createAuthClient } from "@authingo/react";

// Initialize the action client
const authClient = createAuthClient({ baseURL: "http://localhost:8080/api/auth" });

export default function Dashboard() {
  const { user, isLoading, checkSession, logout } = useAuth();

  if (isLoading) return <p>Loading session...</p>;

  if (!user) {
    return (
      <button onClick={async () => {
        await authClient.signIn.email({ email: "test@example.com", password: "password123" });
        await checkSession(); // Force the global provider to update the UI
      }}>
        Sign In
      </button>
    );
  }

  return (
    <div>
      <h1>Welcome back, {user.name}!</h1>
      <button onClick={logout}>Sign Out</button>
    </div>
  );
}

Documentation ΒΆ

Overview ΒΆ

Package authingo provides a lightweight, secure, and developer-first authentication framework for Go applications.

Unlike heavy identity providers, AuthInGo focuses on keeping authentication within your infrastructure using opaque tokens and database-backed sessions. It is designed to work seamlessly with modern frontend frameworks (like React/Next.js) via its companion npm package, @authingo/react.

Key Features:

  • Opaque Token Sessions: High security by keeping JWTs/session data out of the browser.
  • Refresh Token Rotation: Built-in short-lived access tokens (15 minutes) and long-lived refresh tokens (30 days) for silent, secure session renewals.
  • Secure Defaults: Automatically handles HttpOnly, Secure, and SameSite cookie configurations.
  • Pluggable Storage: Bring your own database via the Store interface (e.g., adapters/postgres).
  • Middleware Protection: Built-in HTTP middleware to strictly secure your private routes.

For complete guides and frontend integration instructions, visit the repository: https://github.com/binit2-1/authingo

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

This section is empty.

Functions ΒΆ

This section is empty.

Types ΒΆ

type Auth ΒΆ

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

Auth is the core engine. It holds the database adapter and the HTTP router.

func New ΒΆ

func New(opts Options) *Auth

New initializes the AuthInGo framework.

Example:

auth := authingo.New(authingo.Options{
	Store: postgres.NewAdapter(dbConn),
})

func (*Auth) Handler ΒΆ

func (a *Auth) Handler() http.Handler

func (*Auth) RequireAuth ΒΆ

func (a *Auth) RequireAuth(next http.Handler) http.Handler

RequireAuth is a middleware that protects routes from CSRF and unauthorized access.

type ContextKey ΒΆ

type ContextKey string
const (
	UserContextKey ContextKey = "user"
)

type Options ΒΆ

type Options struct {
	// Store is the database adapter (Required).
	Store Store

	// Plugins is an optional list of extensions.
	Plugins []Plugin
}

Options holds the configuration for initializing AuthInGo.

type Plugin ΒΆ

type Plugin interface {
	ID() string

	// InjectRoutes allows the plugin to add custom endpoints (e.g., /api/auth/2fa)
	InjectRoutes(mux *http.ServeMux)
}

Plugin defines an extension that can modify the core AuthInGo behavior.

type Session ΒΆ

type Session struct {
	ID               string    `json:"id"`
	UserID           string    `json:"user_id"`
	Token            string    `json:"-"`
	RefreshToken     string    `json:"-"`
	CreatedAt        time.Time `json:"created_at"`
	ExpiresAt        time.Time `json:"expires_at"`
	RefreshExpiresAt time.Time `json:"refresh_expires_at"`
}

Session represents an active login instance.

type Store ΒΆ

type Store interface {
	// CreateUser inserts a new user into the database.
	// We pass a pointer (*User) so the adapter can populate the generated ID.
	CreateUser(ctx context.Context, user *User) error

	// GetUserByEmail fetches a user for login validation.
	GetUserByEmail(ctx context.Context, email string) (*User, error)

	// CreateSession stores a newly generated opaque token.
	CreateSession(ctx context.Context, session *Session) error

	// GetSession fetches the session and its associated user from the database.
	GetSession(ctx context.Context, token string) (*Session, *User, error)

	// DeleteSession removes the session (used for logging out).
	DeleteSession(ctx context.Context, token string) error

	//RefreshSession updates the session's expiration time (used for "remember me" functionality).
	RefreshSession(ctx context.Context, oldRefreshToken string) (*Session, *User, error)

	//CleanupExpiredSessions removes sessions that have passed their expiration time.
	CleanupExpiredSessions(ctx context.Context) error
}

Store defines the exact database operations required by AuthInGo. Any database (Postgres, MySQL, SQLite) can be used as long as it implements these exact methods.

type User ΒΆ

type User struct {
	ID            string    `json:"id"`
	Email         string    `json:"email"`
	Name          string    `json:"name"`
	PasswordHash  string    `json:"-"`
	EmailVerified bool      `json:"email_verified"`
	CreatedAt     time.Time `json:"created_at"`
	UpdatedAt     time.Time `json:"updated_at"`
}

User represents a registered account in the system.

Directories ΒΆ

Path Synopsis
adapters
postgres module

Jump to

Keyboard shortcuts

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