/golang-auth-api

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

Primary LanguageGoMIT LicenseMIT

Authentication API

A modern, production-ready Go REST API for authentication and authorization, featuring social login, email verification, JWT, Two-Factor Authentication (2FA), and Redis integration.


๐Ÿš€ Features

  • Secure user registration & login (JWT access/refresh tokens)
  • Two-Factor Authentication (2FA) with TOTP and recovery codes
  • User Activity Logs with pagination and filtering
  • Social login: Google, Facebook, GitHub
  • Email verification & password reset
  • Role-based access control (middleware)
  • Redis for token/session management
  • Dockerized for local development & deployment
  • Unit & integration tests
  • Interactive Swagger API documentation
  • Development and production Docker configurations

๐Ÿ—‚๏ธ Project Structure

cmd/api/main.go         # Entry point
internal/               # Core logic
โ”œโ”€โ”€ auth/              # Authentication handlers
โ”œโ”€โ”€ user/              # User management
โ”œโ”€โ”€ social/            # Social authentication (OAuth2)
โ”œโ”€โ”€ twofa/             # Two-Factor Authentication
โ”œโ”€โ”€ log/               # Activity logging system
โ”œโ”€โ”€ email/             # Email verification & password reset
โ”œโ”€โ”€ middleware/        # JWT auth middleware
โ”œโ”€โ”€ database/          # Database connection & migrations
โ”œโ”€โ”€ redis/             # Redis connection & session management
โ”œโ”€โ”€ config/            # Configuration management
โ””โ”€โ”€ util/              # Utility functions
pkg/                   # Shared packages
โ”œโ”€โ”€ models/            # Database models
โ”œโ”€โ”€ dto/               # Data Transfer Objects
โ”œโ”€โ”€ errors/            # Custom error types
โ””โ”€โ”€ jwt/               # JWT utilities
docs/                  # API documentation
โ”œโ”€โ”€ swagger.json       # Generated Swagger spec
โ”œโ”€โ”€ swagger.yaml       # Generated Swagger spec
โ”œโ”€โ”€ docs.go            # Generated Swagger docs
โ”œโ”€โ”€ README.md          # Documentation overview
โ”œโ”€โ”€ ARCHITECTURE.md    # System architecture
โ””โ”€โ”€ API.md             # API reference
.env                   # Environment variables
.github/               # GitHub templates and workflows
โ”œโ”€โ”€ ISSUE_TEMPLATE/    # Issue templates
โ””โ”€โ”€ workflows/         # CI/CD workflows (if any)
Dockerfile             # Production Docker image
Dockerfile.dev         # Development Docker image
docker-compose.yml     # Production Docker Compose
docker-compose.dev.yml # Development Docker Compose
Makefile               # Build and development commands
test_api.sh            # API testing script
.air.toml              # Air configuration for hot reload
dev.sh, dev.bat        # Development startup scripts
CONTRIBUTING.md        # Contribution guidelines
CODE_OF_CONDUCT.md     # Code of conduct
SECURITY.md            # Security policy
LICENSE                # MIT License

๐Ÿ“– API Documentation (Swagger)

After starting the server, access the interactive API docs at:

You can try out all endpoints, including social logins and 2FA operations, directly from the browser.

๐Ÿ”„ Regenerating Swagger Documentation

If you make changes to your API routes or annotations, regenerate the Swagger docs with:

make swag-init

or

swag init -g cmd/api/main.go -o docs
  • Requires the swag CLI (go install github.com/swaggo/swag/cmd/swag@latest)
  • This will update the docs/ folder with the latest API documentation

โšก Quick Start (Docker)

  1. Clone the repository
  2. Copy .env and update with your credentials
  3. Start development:
    • Windows: dev.bat
    • Linux/Mac: ./dev.sh
  4. API available at http://localhost:8080
  5. Swagger docs at http://localhost:8080/swagger/index.html

๐Ÿ› ๏ธ Manual Setup

  1. Create PostgreSQL DB & update .env
  2. go mod tidy
  3. Install Air for hot reload: go install github.com/air-verse/air@latest
  4. Run: air or go run cmd/api/main.go

๐Ÿ› ๏ธ Makefile Commands

The following make commands are available for development, testing, building, and Docker operations:

Command Description
make build Build the application binary (bin/api.exe).
make run Run the application without hot reload.
make dev Run with hot reload using Air.
make test Run all Go tests with verbose output.
make test-totp Run TOTP test (requires TEST_TOTP_SECRET environment variable).
make clean Remove build artifacts and temporary files.
make install-air Install Air for hot reloading.
make setup Setup development environment (installs Air, tidy/download deps).
make fmt Format code using go fmt.
make lint Run linter (golangci-lint).
make install-security-tools Install security scanning tools (gosec and nancy).
make security-scan Run gosec security scanner.
make vulnerability-scan Run nancy vulnerability scanner.
make security Run all security checks (gosec + nancy).
make build-prod Build for production (Linux, static binary).
make docker-dev Run development environment with Docker (./dev.sh).
make docker-compose-build Build Docker images using docker-compose.
make docker-compose-down Stop and remove Docker containers, networks, images, volumes.
make docker-compose-up Start Docker containers in detached mode with build.
make docker-build Build Docker image (auth-api).
make docker-run Run Docker container with environment from .env.
make swag-init Generate Swagger documentation (docs/).
make help Show all available make commands.

Tip: You can also run make help to see this list in your terminal.

๐Ÿ”‘ API Endpoints

Authentication

  • POST /register โ€” User registration
  • POST /login โ€” User login (with 2FA support)
  • POST /logout โ€” User logout and token revocation (protected)
  • POST /refresh-token โ€” Refresh JWT tokens
  • GET /verify-email โ€” Email verification
  • POST /forgot-password โ€” Request password reset
  • POST /reset-password โ€” Reset password with token

Two-Factor Authentication (2FA)

  • POST /2fa/generate โ€” Generate 2FA secret and QR code (protected)
  • POST /2fa/verify-setup โ€” Verify initial 2FA setup (protected)
  • POST /2fa/enable โ€” Enable 2FA and get recovery codes (protected)
  • POST /2fa/disable โ€” Disable 2FA (protected)
  • POST /2fa/login-verify โ€” Verify 2FA code during login (public)
  • POST /2fa/recovery-codes โ€” Generate new recovery codes (protected)

Social Authentication

  • GET /auth/google/login โ€” Initiate Google OAuth2 login
  • GET /auth/google/callback โ€” Google OAuth2 callback
  • GET /auth/facebook/login โ€” Initiate Facebook OAuth2 login
  • GET /auth/facebook/callback โ€” Facebook OAuth2 callback
  • GET /auth/github/login โ€” Initiate GitHub OAuth2 login
  • GET /auth/github/callback โ€” GitHub OAuth2 callback

User Management

  • GET /profile โ€” Get user profile (protected)
  • GET /auth/validate โ€” Validate JWT token for external services (protected)

Activity Logs

  • GET /activity-logs โ€” Get authenticated user's activity logs with pagination and filtering (protected)
  • GET /activity-logs/:id โ€” Get specific activity log by ID (protected)
  • GET /activity-logs/event-types โ€” Get available event types for filtering (protected)
  • GET /admin/activity-logs โ€” Get all users' activity logs for admin use (protected)

๐Ÿ“ฆ API Response Format

Success:

{
  "success": true,
  "data": { "token": "..." }
}

Error:

{
  "success": false,
  "error": "Invalid credentials"
}

๐Ÿ”’ Authentication Flow

Standard Authentication

  1. Register/login returns JWT access & refresh tokens
  2. Access token in Authorization: Bearer <token> header
  3. Refresh token endpoint issues new access/refresh tokens

Two-Factor Authentication Flow

  1. User enables 2FA via /2fa/generate, /2fa/verify-setup, and /2fa/enable
  2. During login, if 2FA is enabled, a temporary token is returned
  3. User provides TOTP code or recovery code via /2fa/login-verify
  4. Final JWT tokens are issued upon successful 2FA verification

Social Authentication Flow

  1. Redirect to provider login endpoint (e.g., /auth/google/login)
  2. User authorizes with social provider
  3. Provider redirects back to callback endpoint
  4. JWT tokens are issued for authenticated user

๐Ÿ“‹ Activity Logs

Overview

The Activity Logs system provides comprehensive tracking of user actions for security auditing, compliance, and debugging purposes. All user activities are automatically logged with detailed context information.

Tracked Events

The following events are automatically logged:

  • LOGIN โ€” User successfully logged in
  • LOGOUT โ€” User logged out
  • REGISTER โ€” New user registration
  • PASSWORD_CHANGE โ€” User changed their password
  • PASSWORD_RESET โ€” User reset their password
  • EMAIL_VERIFY โ€” User verified their email address
  • 2FA_ENABLE โ€” User enabled two-factor authentication
  • 2FA_DISABLE โ€” User disabled two-factor authentication
  • 2FA_LOGIN โ€” User logged in using 2FA
  • TOKEN_REFRESH โ€” User refreshed their access token
  • SOCIAL_LOGIN โ€” User logged in via social media (Google, Facebook, GitHub)
  • PROFILE_ACCESS โ€” User accessed their profile
  • RECOVERY_CODE_USED โ€” User used a 2FA recovery code
  • RECOVERY_CODE_GEN โ€” User generated new 2FA recovery codes

Features

  • Pagination: Efficient handling of large datasets with configurable page sizes (1-100 items)
  • Filtering: Filter by event type, date ranges (YYYY-MM-DD format)
  • Security: Users can only access their own logs; admin endpoint for comprehensive access
  • Performance: Optimized database queries with proper indexing on UserID, EventType, and Timestamp
  • Audit Trail: IP addresses, user agents, and contextual details captured for forensic analysis

API Examples

Get User's Recent Login Activities

curl -X GET "http://localhost:8080/activity-logs?event_type=LOGIN&limit=5" \
     -H "Authorization: Bearer your-jwt-token"

Get Activities from Date Range

curl -X GET "http://localhost:8080/activity-logs?start_date=2024-01-01&end_date=2024-01-31&page=1&limit=20" \
     -H "Authorization: Bearer your-jwt-token"

Get Available Event Types

curl -X GET "http://localhost:8080/activity-logs/event-types" \
     -H "Authorization: Bearer your-jwt-token"

Response Format

{
  "data": [
    {
      "id": "123e4567-e89b-12d3-a456-426614174000",
      "user_id": "987fcdeb-51a2-43d8-a456-426614174001",
      "event_type": "LOGIN",
      "timestamp": "2024-01-15T10:30:00Z",
      "ip_address": "192.168.1.100",
      "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
      "details": {
        "login_method": "password",
        "success": true
      }
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 20,
    "total_records": 45,
    "total_pages": 3,
    "has_next": true,
    "has_previous": false
  }
}

๐Ÿงช Testing

Automated Testing

  • Run all tests: make test or go test ./...
  • Coverage: Unit & integration tests for core logic and endpoints

Manual API Testing

  • Use the provided test script: ./test_api.sh
  • Test basic authentication flows and error handling
  • Interactive testing via Swagger UI at /swagger/index.html

๐Ÿณ Docker Configuration

Development Environment

# Start development environment with hot reload
make docker-dev
# or
./dev.sh  # Linux/Mac
dev.bat   # Windows

Production Environment

# Build and start production containers
make docker-compose-up
# or
docker-compose up -d --build

โš™๏ธ Environment Variables

Required Configuration

# Database Configuration
DB_HOST=localhost          # postgres (for Docker)
DB_PORT=5432
DB_USER=your_db_user
DB_PASSWORD=your_db_password
DB_NAME=auth_db

# Redis Configuration  
REDIS_ADDR=localhost:6379  # redis:6379 (for Docker)

# JWT Configuration
JWT_SECRET=supersecretjwtkey
ACCESS_TOKEN_EXPIRATION_MINUTES=15
REFRESH_TOKEN_EXPIRATION_HOURS=720

# Email Configuration
EMAIL_HOST=smtp.example.com
EMAIL_PORT=587
EMAIL_USERNAME=your_email@example.com
EMAIL_PASSWORD=your_email_password

# Social Authentication (OAuth2)
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
FACEBOOK_CLIENT_ID=your_facebook_client_id
FACEBOOK_CLIENT_SECRET=your_facebook_client_secret
GITHUB_CLIENT_ID=your_github_client_id
GITHUB_CLIENT_SECRET=your_github_client_secret

# Server Configuration
PORT=8080

Docker vs Local Development

For Docker Compose, use service names:

  • DB_HOST=postgres
  • REDIS_ADDR=redis:6379

For local development, use localhost:

  • DB_HOST=localhost
  • REDIS_ADDR=localhost:6379

๐Ÿงฉ Key Dependencies

  • Web Framework: Gin
  • Database: GORM + PostgreSQL
  • Caching: Go-Redis + Redis
  • Authentication: JWT, OAuth2
  • Configuration: Viper, godotenv
  • Validation: go-playground/validator
  • Email: gopkg.in/mail.v2
  • 2FA: pquerna/otp, skip2/go-qrcode
  • Documentation: Swaggo/Swag
  • Development: Air (hot reload)

๐Ÿงช Development Workflow

  1. make setup โ€” Install dependencies and tools
  2. make dev โ€” Start development server with hot reload
  3. make test โ€” Run tests during development
  4. make fmt โ€” Format code before committing
  5. make lint โ€” Check code quality
  6. ./test_api.sh โ€” Test API endpoints manually

๐Ÿค Contributing

Please read CONTRIBUTING.md for details on our code of conduct and the process for submitting pull requests.

๐Ÿ›ก๏ธ Security

Please read SECURITY.md for information about reporting security vulnerabilities.

๐Ÿ“š Documentation


๐Ÿ“„ License

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