Skip to content

A modern, production-ready Go REST API for authentication and authorization, featuring social login, email verification, JWT, and Redis integration.

License

Notifications You must be signed in to change notification settings

gjovanovicst/golang-auth-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

24 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

🔐 Authentication API

Modern, Production-Ready Go REST API

A comprehensive authentication and authorization system with social login, email verification, JWT, Two-Factor Authentication, and smart activity logging.

Go Version License Docker Swagger

FeaturesQuick StartDocumentationAPI EndpointsContributing


✨ Features

🔑 Authentication & Authorization

  • Secure Registration & Login with JWT access/refresh tokens
  • Two-Factor Authentication (2FA) with TOTP and recovery codes
  • Social Authentication (Google, Facebook, GitHub OAuth2)
  • Email Verification and password reset flows
  • Token Blacklisting for secure logout
  • Role-Based Access Control with middleware

📊 Smart Activity Logging

  • Intelligent Event Categorization (Critical/Important/Informational)
  • Anomaly Detection (new IP address, device detection)
  • Automatic Log Retention and cleanup (80-95% database size reduction)
  • Pagination & Filtering for audit trails
  • Configurable Logging via environment variables

🛠️ Developer Experience

  • Interactive Swagger Documentation at /swagger/index.html
  • Docker & Docker Compose for easy setup
  • Hot Reload development with Air
  • Database Migrations with tracking system
  • Comprehensive Testing suite
  • CI/CD with GitHub Actions (test, build, security scan)
  • Local CI Testing with act support
  • Professional Project Structure

🚀 Production Ready

  • Redis Integration for caching and session management
  • PostgreSQL Database with GORM ORM
  • Security Best Practices (OWASP guidelines)
  • Automated Cleanup Jobs
  • Environment-Based Configuration

🚀 Quick Start

Prerequisites

  • Docker & Docker Compose (recommended)
  • Or: Go 1.22+, PostgreSQL 13+, Redis 6+

Installation

# 1. Clone the repository
git clone <repository-url>
cd <project-directory>

# 2. Copy environment configuration
cp .env.example .env
# Edit .env with your configuration

# 3. Start with Docker (recommended)
make docker-dev
# Or: Windows: dev.bat | Linux/Mac: ./dev.sh

# 4. Optional: Apply database enhancements
make migrate-up

🎉 That's it! Your API is now running at http://localhost:8080

What Just Happened?

  • ✅ PostgreSQL & Redis started in Docker containers
  • ✅ Database tables created automatically (GORM AutoMigrate)
  • ✅ Application running with hot reload enabled
  • ✅ Swagger docs available at http://localhost:8080/swagger/index.html

Next Steps


📚 Documentation

Quick Links

Document Description
📖 Documentation Index Complete documentation overview
🏗️ Architecture System architecture and design
📡 API Reference Detailed API documentation
🔄 Migration Guide Database migration system
🤝 Contributing Contribution guidelines
🛡️ Security Policy Security and vulnerability reporting

Documentation by Category

🎯 Getting Started

📦 Features

🗄️ Database & Migrations

🔧 Development


🌐 API Endpoints

Authentication

Endpoint Method Description Protected
/register POST User registration
/login POST User login (with 2FA support)
/logout POST Logout and token revocation
/refresh-token POST Refresh JWT tokens
/verify-email GET Email verification
/forgot-password POST Request password reset
/reset-password POST Reset password with token

Two-Factor Authentication (2FA)

Endpoint Method Description Protected
/2fa/generate POST Generate 2FA secret and QR code
/2fa/verify-setup POST Verify initial 2FA setup
/2fa/enable POST Enable 2FA and get recovery codes
/2fa/disable POST Disable 2FA
/2fa/login-verify POST Verify 2FA code during login
/2fa/recovery-codes POST Generate new recovery codes

Social Authentication

Endpoint Method Description
/auth/google/login GET Initiate Google OAuth2
/auth/google/callback GET Google OAuth2 callback
/auth/facebook/login GET Initiate Facebook OAuth2
/auth/facebook/callback GET Facebook OAuth2 callback
/auth/github/login GET Initiate GitHub OAuth2
/auth/github/callback GET GitHub OAuth2 callback

User Management

Endpoint Method Description Protected
/profile GET Get user profile
/auth/validate GET Validate JWT token

Activity Logs

Endpoint Method Description Protected
/activity-logs GET Get user's activity logs (paginated)
/activity-logs/:id GET Get specific activity log
/activity-logs/event-types GET Get available event types
/admin/activity-logs GET Get all users' logs (admin)

📖 Full API Documentation: Swagger UI (when running)


🔐 Authentication Flow

Standard Authentication

1. POST /register or /login → Returns JWT access & refresh tokens
2. Include token in header: Authorization: Bearer <token>
3. POST /refresh-token → Get new tokens when expired
4. POST /logout → Revoke tokens and blacklist

Two-Factor Authentication

1. POST /2fa/generate → Get QR code and secret
2. POST /2fa/verify-setup → Verify TOTP code
3. POST /2fa/enable → Enable 2FA, receive recovery codes
4. POST /login → Returns temporary token (if 2FA enabled)
5. POST /2fa/login-verify → Verify TOTP/recovery code → Get full JWT tokens

Social Authentication

1. GET /auth/{provider}/login → Redirect to provider
2. User authorizes on provider's site
3. GET /auth/{provider}/callback → Provider redirects back
4. Receive JWT tokens for authenticated user

📊 Activity Logging System

Overview

A professional activity logging system that balances security auditing with database performance. Uses intelligent categorization, anomaly detection, and automatic cleanup to reduce database bloat by 80-95% while maintaining critical security data.

Event Categories

Severity Events Retention Always Logged?
CRITICAL LOGIN, LOGOUT, PASSWORD_CHANGE, 2FA_ENABLE/DISABLE 1 year ✅ Yes
IMPORTANT REGISTER, EMAIL_VERIFY, SOCIAL_LOGIN, PROFILE_UPDATE 6 months ✅ Yes
INFORMATIONAL TOKEN_REFRESH, PROFILE_ACCESS 3 months ⚠️ Only on anomalies

Anomaly Detection

Automatically logs "informational" events when:

  • ✅ New IP address detected
  • ✅ New device/browser (user agent) detected
  • ✅ Configurable pattern analysis window (default: 30 days)

Default Behavior

  • ✅ All critical security events logged
  • ✅ All important events logged
  • ❌ Token refreshes NOT logged (happens every 15 minutes)
  • ❌ Profile access NOT logged (happens on every view)
  • ✅ BUT logs both if anomaly detected (new IP/device)
  • ✅ Automatic cleanup based on retention policies

Quick Configuration

# High-frequency events (default: disabled)
LOG_TOKEN_REFRESH=false
LOG_PROFILE_ACCESS=false

# Anomaly detection (default: enabled)
LOG_ANOMALY_DETECTION_ENABLED=true
LOG_ANOMALY_NEW_IP=true
LOG_ANOMALY_NEW_USER_AGENT=true

# Retention policies (days)
LOG_RETENTION_CRITICAL=365      # 1 year
LOG_RETENTION_IMPORTANT=180     # 6 months
LOG_RETENTION_INFORMATIONAL=90  # 3 months

# Automatic cleanup
LOG_CLEANUP_ENABLED=true
LOG_CLEANUP_INTERVAL=24h

📖 Complete Guide: Activity Logging Documentation


⚙️ Environment Configuration

Database

DB_HOST=postgres        # Use 'localhost' for local dev without Docker
DB_PORT=5432
DB_USER=your_db_user
DB_PASSWORD=your_db_password
DB_NAME=auth_db

Redis

REDIS_ADDR=redis:6379   # Use 'localhost:6379' for local dev without Docker
REDIS_PASSWORD=         # Optional
REDIS_DB=0

JWT

JWT_SECRET=your-strong-secret-key-here-change-in-production
ACCESS_TOKEN_EXPIRATION_MINUTES=15
REFRESH_TOKEN_EXPIRATION_HOURS=720  # 30 days

Email

EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USERNAME=your_email@gmail.com
EMAIL_PASSWORD=your_app_password
EMAIL_FROM=noreply@yourapp.com

Social Authentication Setup

# Google OAuth2
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
GOOGLE_REDIRECT_URL=http://localhost:8080/auth/google/callback

# Facebook OAuth2
FACEBOOK_CLIENT_ID=your_facebook_app_id
FACEBOOK_CLIENT_SECRET=your_facebook_app_secret
FACEBOOK_REDIRECT_URL=http://localhost:8080/auth/facebook/callback

# GitHub OAuth2
GITHUB_CLIENT_ID=your_github_client_id
GITHUB_CLIENT_SECRET=your_github_client_secret
GITHUB_REDIRECT_URL=http://localhost:8080/auth/github/callback

Server

PORT=8080
GIN_MODE=debug          # Use 'release' for production

📖 Complete Reference: Environment Variables Documentation


🔧 Makefile Commands

Development Commands

Command Description
make setup Install dependencies and development tools
make dev Run with hot reload (Air)
make run Run without hot reload
make build Build binary to bin/api.exe
make build-prod Build production binary (Linux, static)
make clean Remove build artifacts and temporary files
make install-air Install Air for hot reloading

Testing Commands

Command Description
make test Run all tests with verbose output
make test-totp Run TOTP-specific test
make fmt Format code with go fmt
make lint Run linter (requires golangci-lint)

Docker Commands

Command Description
make docker-dev Start development environment (with hot reload)
make docker-compose-up Start production containers
make docker-compose-down Stop and remove all containers
make docker-compose-build Build Docker images
make docker-build Build single Docker image
make docker-run Run Docker container

Database Migration Commands

Command Description
make migrate Interactive migration tool
make migrate-status Check migration status (tracked in DB)
make migrate-up Apply pending migrations
make migrate-down Rollback last migration
make migrate-list List all available migrations
make migrate-backup Backup database to file
make migrate-init Initialize migration tracking table
make migrate-test Test migration scripts
make migrate-check Check migration file syntax
make migrate-mark-applied Manually mark migration as applied

CI/CD Commands

Command Description
act -j test Run test job locally with act
act -j build Run build job locally with act
act -j security-scan Run security scan locally with act
act -l List all available GitHub Actions jobs

Note: Install act to run GitHub Actions workflows locally for testing CI/CD pipelines before pushing.

Security Commands

Command Description
make security Run all security checks (gosec + nancy)
make security-scan Run gosec security scanner
make vulnerability-scan Run nancy dependency vulnerability scanner
make install-security-tools Install security scanning tools

Documentation Commands

Command Description
make swag-init Regenerate Swagger documentation

Help

Command Description
make help Display all available commands

💡 Pro Tip: Run make help in your terminal to see this list with descriptions!


🗄️ Database Migrations

Two-Tier Migration System

1. GORM AutoMigrate (Automatic)

Runs on application startup:

  • ✅ Creates tables from Go models
  • ✅ Adds missing columns
  • ✅ Creates indexes
  • ✅ Safe for production
  • ⚠️ Cannot handle: column renames, data transformations, complex constraints

2. SQL Migrations (Manual)

For complex changes:

  • ✅ Complex data transformations
  • ✅ Column renames and type changes
  • ✅ Custom indexes and constraints
  • ✅ Performance optimizations
  • ✅ Breaking changes
  • ✅ Full control with rollback support

Quick Migration Workflow

# Check current migration status
make migrate-status

# Apply all pending migrations
make migrate-up

# Rollback last migration if needed
make migrate-down

# Interactive migration tool (recommended for beginners)
make migrate

For New Contributors

# 1. Start the project (GORM creates base tables automatically)
make docker-dev

# 2. Apply SQL enhancements (optional, but recommended)
make migrate-up

# 3. You're ready to develop!
make dev

Creating New Migrations

# 1. Copy the template
cp migrations/TEMPLATE.md migrations/YYYYMMDD_HHMMSS_your_migration.md

# 2. Create forward migration SQL
# migrations/YYYYMMDD_HHMMSS_your_migration.sql

# 3. Create rollback SQL
# migrations/YYYYMMDD_HHMMSS_your_migration_rollback.sql

# 4. Test and apply
make migrate-test
make migrate-up

📖 Complete Guide: Migration System Documentation


🧪 Testing

Run Tests

# All tests with verbose output
make test

# Specific package
go test -v ./internal/auth/...

# With coverage report
go test -cover ./...

# 2FA TOTP test (requires TEST_TOTP_SECRET env var)
make test-totp

Manual API Testing

# Using the test script
./test_api.sh

# Or use interactive Swagger UI
# Navigate to: http://localhost:8080/swagger/index.html

Test Coverage

The project includes:

  • ✅ Unit tests for core logic
  • ✅ Integration tests for API endpoints
  • ✅ 2FA/TOTP verification tests
  • ✅ Authentication flow tests
  • ✅ Database operation tests

🏗️ Project Structure

project-root/
├── cmd/api/                    # Application entry point
│   └── main.go
├── internal/                   # Private application code
│   ├── auth/                  # Authentication handlers
│   ├── user/                  # User management
│   ├── social/                # Social OAuth2 providers
│   ├── twofa/                 # Two-factor authentication
│   ├── log/                   # Activity logging system
│   ├── email/                 # Email verification & reset
│   ├── middleware/            # JWT auth middleware
│   ├── database/              # Database connection & migrations
│   ├── redis/                 # Redis connection & operations
│   ├── config/                # Configuration management
│   └── util/                  # Utility functions
├── pkg/                        # Public packages
│   ├── models/                # Database models (GORM)
│   ├── dto/                   # Data transfer objects
│   ├── errors/                # Custom error types
│   └── jwt/                   # JWT token utilities
├── docs/                       # Documentation
│   ├── features/              # Feature-specific docs
│   ├── guides/                # Setup and configuration guides
│   ├── migrations/            # Migration system docs
│   ├── implementation/        # Implementation details
│   ├── implementation_phases/ # Original project phases
│   ├── API.md                 # API reference
│   ├── ARCHITECTURE.md        # System architecture
│   └── README.md              # Documentation index
├── migrations/                 # SQL migration files
│   ├── README.md              # Developer migration guide
│   ├── TEMPLATE.md            # Migration template
│   └── *.sql                  # Migration scripts
├── scripts/                    # Helper scripts
│   ├── migrate.sh             # Migration runner (Unix)
│   ├── migrate.bat            # Migration runner (Windows)
│   └── cleanup_activity_logs.sh
├── .github/                    # GitHub configuration
│   ├── ISSUE_TEMPLATE/        # Issue templates
│   └── workflows/             # CI/CD workflows
├── Dockerfile                  # Production Docker image
├── Dockerfile.dev              # Development Docker image
├── docker-compose.yml          # Production compose config
├── docker-compose.dev.yml      # Development compose config
├── Makefile                    # Build and development commands
├── .air.toml                   # Hot reload configuration
├── .env.example                # Environment variables template
├── go.mod                      # Go module dependencies
├── go.sum                      # Dependency checksums
├── CONTRIBUTING.md             # Contribution guidelines
├── CODE_OF_CONDUCT.md          # Code of conduct
├── SECURITY.md                 # Security policy
├── CHANGELOG.md                # Version history
├── BREAKING_CHANGES.md         # Breaking changes tracker
├── docs/migrations/MIGRATIONS.md  # Migration system overview
├── LICENSE                     # MIT License
└── README.md                   # This file

🛠️ Tech Stack

Category Technology
Language Go 1.22+
Web Framework Gin
Database PostgreSQL 13+ with GORM ORM
Cache & Sessions Redis 6+ with go-redis
Authentication JWT (golang-jwt/jwt), OAuth2
2FA TOTP (pquerna/otp), QR codes
Validation go-playground/validator
Email gopkg.in/mail.v2 (SMTP)
Configuration Viper, godotenv
API Documentation Swagger/Swaggo
Development Air (hot reload)
Containerization Docker, Docker Compose
Security Tools gosec, nancy

🤝 Contributing

We welcome contributions! Here's how to get started:

1. Read the Guidelines

2. Fork & Clone

git clone https://github.com/yourusername/auth-api.git
cd auth-api

3. Set Up Development Environment

# Install dependencies and tools
make setup

# Copy and configure environment
cp .env.example .env
# Edit .env with your settings

# Start development environment
make docker-dev

4. Create a Branch

git checkout -b feature/amazing-feature
# or
git checkout -b fix/bug-description

5. Make Changes & Test

# Format code
make fmt

# Run linter
make lint

# Run tests
make test

# Security checks
make security

6. Commit Your Changes

git commit -m "feat(auth): add amazing feature"

Follow Conventional Commits:

  • feat(scope): description - New feature
  • fix(scope): description - Bug fix
  • docs(scope): description - Documentation
  • refactor(scope): description - Code refactoring
  • test(scope): description - Tests
  • chore(scope): description - Maintenance

7. Push & Create Pull Request

git push origin feature/amazing-feature

Then create a Pull Request on GitHub

Development Workflow

# Daily development
make dev              # Start with hot reload
make test             # Run tests
make fmt && make lint # Format and check code
make security         # Security checks before commit

🛡️ Security

Reporting Vulnerabilities

Please DO NOT create public issues for security vulnerabilities.

Read SECURITY.md for instructions on how to report security vulnerabilities privately.

Security Features

  • JWT Authentication with access & refresh tokens
  • Token Blacklisting on logout for immediate invalidation
  • Password Hashing using bcrypt
  • Two-Factor Authentication with TOTP and recovery codes
  • Email Verification for account security
  • Rate Limiting (configurable)
  • SQL Injection Protection (GORM parameterized queries)
  • XSS Protection (input validation and sanitization)
  • CORS Configuration (customizable)
  • Activity Logging and comprehensive audit trails
  • Security Headers (recommended middleware)

Security Tools & Scanning

# Run all security checks
make security

# Individual scans
make security-scan         # gosec - Go security checker
make vulnerability-scan    # nancy - dependency vulnerability scanner

# Install security tools
make install-security-tools

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.


📞 Support & Resources

Documentation

Community

Getting Help

  1. Check the documentation
  2. Search existing issues
  3. Create a new issue with details
  4. Join discussions for general questions

🙏 Acknowledgments

Built with modern Go practices and industry-standard security patterns.

Special Thanks To:

  • Gin Web Framework - Fast HTTP web framework
  • GORM - Powerful ORM library
  • Swaggo - Swagger documentation generator
  • Air - Live reload for Go apps
  • All open-source contributors and maintainers

Made with ❤️ using Go

⬆ Back to Top

About

A modern, production-ready Go REST API for authentication and authorization, featuring social login, email verification, JWT, and Redis integration.

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published