auth

module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2025 License: MIT

README

Auth Chassis - Reusable Authentication Service

Tests codecov Go Report Card Go Version License

A comprehensive, production-ready authentication service built with Go and gRPC. This chassis provides a complete authentication solution that can be easily integrated into any application.

Features

Authentication Methods
  • Email/Password Authentication: Traditional email and password-based authentication with secure password hashing (bcrypt)
  • Passwordless Authentication: Magic link authentication via email
  • OAuth 2.0: Support for Google, GitHub, Facebook, Apple, Microsoft, and Discord OAuth providers
  • Two-Factor Authentication (2FA): TOTP-based 2FA with QR code generation and backup codes
Security Features
  • JWT-based access and refresh tokens
  • Secure password hashing with bcrypt
  • Password strength validation
  • Email verification
  • Session management
  • Token refresh mechanism
  • 2FA with backup codes
Additional Features
  • User profile management
  • Password reset flow
  • Session tracking and revocation
  • PostgreSQL database with GORM
  • UUID-based primary keys (generated by PostgreSQL)
  • Customizable email templates (text-based, easy to modify)
  • SendGrid integration for production email sending
  • Comprehensive gRPC API

Architecture

auth/
├── api/proto/auth/v1/        # gRPC protocol definitions
├── cmd/server/               # Application entry point
├── internal/
│   ├── config/              # Configuration management
│   ├── database/            # Database initialization
│   ├── domain/              # Domain models
│   ├── repository/          # Data access layer
│   └── service/             # Business logic
├── .env.example             # Environment variables template
├── config.yaml.example      # YAML configuration template
├── Makefile                 # Build and development commands
└── README.md               # This file

Prerequisites

  • Go 1.25.3 or higher
  • PostgreSQL 12 or higher
  • Protocol Buffers compiler (protoc)

Quick Start

1. Clone and Setup
# Clone the repository
cd auth

# Copy environment variables
cp .env.example .env

# Edit .env with your configuration
# IMPORTANT: Change the JWT secrets to secure random strings!
vim .env
2. Setup PostgreSQL
# Create database
createdb auth_db

# Or using psql
psql -U postgres
CREATE DATABASE auth_db;
3. Configure Environment Variables

Edit .env file and set at minimum:

  • AUTH_JWT_ACCESS_TOKEN_SECRET: A secure random string for access tokens
  • AUTH_JWT_REFRESH_TOKEN_SECRET: A secure random string for refresh tokens
  • AUTH_DATABASE_*: Your PostgreSQL connection details

Generate secure secrets:

# Generate random secrets (on macOS/Linux)
openssl rand -base64 32
4. Install Dependencies
# Install Go dependencies
go mod download

# Install protobuf tools (if not already installed)
make install-tools
5. Run the Service
# Build and run
make build
./bin/auth-server

# Or run directly
make run

The service will:

  • Connect to PostgreSQL
  • Run database migrations automatically
  • Start the gRPC server on :8080

Configuration

The service can be configured using:

  1. Environment variables (prefixed with AUTH_)
  2. YAML configuration file (config.yaml)
  3. Default values

Environment variables take precedence over YAML configuration.

Required Configuration
  • JWT Secrets: Must be set via environment variables
    • AUTH_JWT_ACCESS_TOKEN_SECRET
    • AUTH_JWT_REFRESH_TOKEN_SECRET
Database Configuration
database:
  host: localhost
  port: 5432
  user: postgres
  password: postgres
  dbname: auth_db
  sslmode: disable
Email Configuration

For development, you can leave email settings empty. Emails will be logged to console.

email:
  provider: sendgrid
  api_key: your-sendgrid-api-key
  from_email: noreply@yourapp.com
  from_name: Your App

Or via environment variables:

AUTH_EMAIL_PROVIDER=sendgrid
AUTH_EMAIL_API_KEY=SG.your-api-key-here
AUTH_EMAIL_FROM_EMAIL=noreply@yourapp.com
AUTH_EMAIL_FROM_NAME=Your App

SendGrid Setup:

  1. Sign up at SendGrid
  2. Verify your sender email/domain
  3. Create an API key (Settings → API Keys)
  4. Add the API key to your config
Option 2: SMTP (For Development)
email:
  provider: smtp
  smtp_host: smtp.gmail.com
  smtp_port: 587
  smtp_user: your-email@gmail.com
  smtp_pass: your-app-password
  from_email: noreply@yourapp.com
  from_name: Your App
OAuth Configuration

To enable OAuth providers, configure their client credentials:

oauth:
  google:
    client_id: your-google-client-id
    client_secret: your-google-client-secret
    redirect_url: http://localhost:8080/auth/google/callback

gRPC API

The service exposes the following gRPC methods:

Authentication
  • Register: Register a new user
  • Login: Login with email/password
  • RefreshToken: Refresh access token
  • Logout: Logout and revoke session
Password Management
  • ChangePassword: Change user password
  • ForgotPassword: Request password reset
  • ResetPassword: Reset password with token
Two-Factor Authentication
  • Enable2FA: Enable 2FA for user
  • Verify2FA: Verify 2FA code
  • Disable2FA: Disable 2FA
  • Generate2FABackupCodes: Generate new backup codes
Passwordless Authentication
  • SendPasswordlessEmail: Send magic link
  • VerifyPasswordlessToken: Verify magic link
OAuth
  • GetOAuthURL: Get OAuth authorization URL
  • OAuthCallback: Handle OAuth callback
  • LinkOAuthAccount: Link OAuth account to user
  • UnlinkOAuthAccount: Unlink OAuth account
Token & Session Management
  • ValidateToken: Validate access token
  • RevokeToken: Revoke token
  • GetActiveSessions: Get user's active sessions
  • RevokeSession: Revoke specific session
User Management
  • GetUserProfile: Get user profile
  • UpdateUserProfile: Update user profile
  • VerifyEmail: Verify email address
  • ResendVerificationEmail: Resend verification email

Testing with grpcurl

# Install grpcurl
brew install grpcurl  # macOS
# or
go install github.com/fullstorydev/grpcurl/cmd/grpcurl@latest

# List services
grpcurl -plaintext localhost:8080 list

# List methods
grpcurl -plaintext localhost:8080 list auth.v1.AuthService

# Register a new user
grpcurl -plaintext -d '{
  "email": "user@example.com",
  "password": "SecurePass123",
  "first_name": "John",
  "last_name": "Doe"
}' localhost:8080 auth.v1.AuthService/Register

# Login
grpcurl -plaintext -d '{
  "email": "user@example.com",
  "password": "SecurePass123"
}' localhost:8080 auth.v1.AuthService/Login

Database Schema

The service uses the following tables:

  • users: User accounts
  • sessions: User sessions
  • otps: One-time passwords/tokens
  • oauth_accounts: OAuth account links
  • backup_codes: 2FA backup codes

All tables use UUID as primary keys, generated by PostgreSQL using gen_random_uuid().

Development

Regenerate Protocol Buffers
make proto
Run Tests
make test
Build
make build
Clean
make clean

Deployment

Docker

Create a Dockerfile:

FROM golang:1.25-alpine AS builder
WORKDIR /app
COPY . .
RUN go build -o auth-server cmd/server/main.go

FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /app/auth-server .
EXPOSE 8080
CMD ["./auth-server"]

Build and run:

docker build -t auth-service .
docker run -p 8080:8080 --env-file .env auth-service
Environment Variables for Production

Ensure these are set in production:

  • Use strong, unique JWT secrets
  • Enable SSL for database (sslmode=require)
  • Configure proper email service
  • Set up OAuth callbacks with production URLs
  • Use connection pooling settings appropriate for your load

Integration Guide

To integrate this auth service into your application:

  1. Client-side: Use any gRPC client library
  2. Include access token in gRPC metadata for authenticated requests:
    Authorization: Bearer <access_token>
    
  3. Handle token refresh when access token expires
  4. Validate tokens using the ValidateToken endpoint

Security Considerations

  • Always use HTTPS in production
  • Store JWT secrets securely (use environment variables or secret management)
  • Rotate JWT secrets periodically
  • Implement rate limiting on authentication endpoints
  • Monitor for suspicious authentication patterns
  • Keep dependencies up to date
  • Use strong password requirements
  • Enable 2FA for sensitive accounts

License

This is a reusable chassis for building authentication services.

Support

For issues or questions, please create an issue in the repository.

Directories

Path Synopsis
cmd
server command
internal

Jump to

Keyboard shortcuts

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