A comprehensive authentication and authorization system with social login, email verification, JWT, Two-Factor Authentication, and smart activity logging.
Features • Quick Start • Documentation • API Endpoints • Contributing
- ✅ 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
- ✅ 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
- ✅ 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
actsupport - ✅ Professional Project Structure
- ✅ Redis Integration for caching and session management
- ✅ PostgreSQL Database with GORM ORM
- ✅ Security Best Practices (OWASP guidelines)
- ✅ Automated Cleanup Jobs
- ✅ Environment-Based Configuration
- Docker & Docker Compose (recommended)
- Or: Go 1.22+, PostgreSQL 13+, Redis 6+
# 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
- ✅ 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
- 📖 Configure Environment Variables
- 🔧 Set up Social OAuth Providers
- 📊 Configure Activity Logging
- 🗄️ Learn About Database Migrations
| 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 |
- Migration System Overview
- User Migration Guide
- Upgrade Guide
- Breaking Changes
- Migration Quick Reference
| 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 | ❌ |
| 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 | ✅ |
| 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 |
| Endpoint | Method | Description | Protected |
|---|---|---|---|
/profile |
GET | Get user profile | ✅ |
/auth/validate |
GET | Validate JWT token | ✅ |
| 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)
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
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
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
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.
| 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 |
Automatically logs "informational" events when:
- ✅ New IP address detected
- ✅ New device/browser (user agent) detected
- ✅ Configurable pattern analysis window (default: 30 days)
- ✅ 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
# 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
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_dbREDIS_ADDR=redis:6379 # Use 'localhost:6379' for local dev without Docker
REDIS_PASSWORD= # Optional
REDIS_DB=0JWT_SECRET=your-strong-secret-key-here-change-in-production
ACCESS_TOKEN_EXPIRATION_MINUTES=15
REFRESH_TOKEN_EXPIRATION_HOURS=720 # 30 daysEMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USERNAME=your_email@gmail.com
EMAIL_PASSWORD=your_app_password
EMAIL_FROM=noreply@yourapp.com# 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/callbackPORT=8080
GIN_MODE=debug # Use 'release' for production📖 Complete Reference: Environment Variables Documentation
| 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 |
| 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) |
| 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 |
| 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 |
| 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.
| 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 |
| Command | Description |
|---|---|
make swag-init |
Regenerate Swagger documentation |
| Command | Description |
|---|---|
make help |
Display all available commands |
💡 Pro Tip: Run make help in your terminal to see this list with descriptions!
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
For complex changes:
- ✅ Complex data transformations
- ✅ Column renames and type changes
- ✅ Custom indexes and constraints
- ✅ Performance optimizations
- ✅ Breaking changes
- ✅ Full control with rollback support
# 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# 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# 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
# 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# Using the test script
./test_api.sh
# Or use interactive Swagger UI
# Navigate to: http://localhost:8080/swagger/index.htmlThe project includes:
- ✅ Unit tests for core logic
- ✅ Integration tests for API endpoints
- ✅ 2FA/TOTP verification tests
- ✅ Authentication flow tests
- ✅ Database operation tests
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
| 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 |
| gopkg.in/mail.v2 (SMTP) | |
| Configuration | Viper, godotenv |
| API Documentation | Swagger/Swaggo |
| Development | Air (hot reload) |
| Containerization | Docker, Docker Compose |
| Security Tools | gosec, nancy |
We welcome contributions! Here's how to get started:
- CONTRIBUTING.md - Contribution process and standards
- CODE_OF_CONDUCT.md - Community guidelines
git clone https://github.com/yourusername/auth-api.git
cd auth-api# Install dependencies and tools
make setup
# Copy and configure environment
cp .env.example .env
# Edit .env with your settings
# Start development environment
make docker-devgit checkout -b feature/amazing-feature
# or
git checkout -b fix/bug-description# Format code
make fmt
# Run linter
make lint
# Run tests
make test
# Security checks
make securitygit commit -m "feat(auth): add amazing feature"Follow Conventional Commits:
feat(scope): description- New featurefix(scope): description- Bug fixdocs(scope): description- Documentationrefactor(scope): description- Code refactoringtest(scope): description- Testschore(scope): description- Maintenance
git push origin feature/amazing-featureThen create a Pull Request on GitHub
# 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 commitPlease DO NOT create public issues for security vulnerabilities.
Read SECURITY.md for instructions on how to report security vulnerabilities privately.
- ✅ 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)
# 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-toolsThis project is licensed under the MIT License - see the LICENSE file for details.
- 📖 Complete Documentation - All documentation organized by topic
- 🏗️ Architecture Guide - System design and patterns
- 📡 API Reference - Detailed endpoint documentation
- 🐛 GitHub Issues - Bug reports and feature requests
- 💬 GitHub Discussions - Questions and discussions
- 🤝 Contributing Guide - How to contribute
- Check the documentation
- Search existing issues
- Create a new issue with details
- Join discussions for general questions
Built with modern Go practices and industry-standard security patterns.
- 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