A modern, production-ready Go REST API for authentication and authorization, featuring social login, email verification, JWT, Two-Factor Authentication (2FA), and Redis integration.
- 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
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
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.
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
- Clone the repository
- Copy
.env
and update with your credentials - Start development:
- Windows:
dev.bat
- Linux/Mac:
./dev.sh
- Windows:
- API available at http://localhost:8080
- Swagger docs at http://localhost:8080/swagger/index.html
- Create PostgreSQL DB & update
.env
go mod tidy
- Install Air for hot reload:
go install github.com/air-verse/air@latest
- Run:
air
orgo run cmd/api/main.go
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.
POST /register
โ User registrationPOST /login
โ User login (with 2FA support)POST /logout
โ User logout and token revocation (protected)POST /refresh-token
โ Refresh JWT tokensGET /verify-email
โ Email verificationPOST /forgot-password
โ Request password resetPOST /reset-password
โ Reset password with token
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)
GET /auth/google/login
โ Initiate Google OAuth2 loginGET /auth/google/callback
โ Google OAuth2 callbackGET /auth/facebook/login
โ Initiate Facebook OAuth2 loginGET /auth/facebook/callback
โ Facebook OAuth2 callbackGET /auth/github/login
โ Initiate GitHub OAuth2 loginGET /auth/github/callback
โ GitHub OAuth2 callback
GET /profile
โ Get user profile (protected)GET /auth/validate
โ Validate JWT token for external services (protected)
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)
Success:
{
"success": true,
"data": { "token": "..." }
}
Error:
{
"success": false,
"error": "Invalid credentials"
}
- Register/login returns JWT access & refresh tokens
- Access token in
Authorization: Bearer <token>
header - Refresh token endpoint issues new access/refresh tokens
- User enables 2FA via
/2fa/generate
,/2fa/verify-setup
, and/2fa/enable
- During login, if 2FA is enabled, a temporary token is returned
- User provides TOTP code or recovery code via
/2fa/login-verify
- Final JWT tokens are issued upon successful 2FA verification
- Redirect to provider login endpoint (e.g.,
/auth/google/login
) - User authorizes with social provider
- Provider redirects back to callback endpoint
- JWT tokens are issued for authenticated user
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.
The following events are automatically logged:
LOGIN
โ User successfully logged inLOGOUT
โ User logged outREGISTER
โ New user registrationPASSWORD_CHANGE
โ User changed their passwordPASSWORD_RESET
โ User reset their passwordEMAIL_VERIFY
โ User verified their email address2FA_ENABLE
โ User enabled two-factor authentication2FA_DISABLE
โ User disabled two-factor authentication2FA_LOGIN
โ User logged in using 2FATOKEN_REFRESH
โ User refreshed their access tokenSOCIAL_LOGIN
โ User logged in via social media (Google, Facebook, GitHub)PROFILE_ACCESS
โ User accessed their profileRECOVERY_CODE_USED
โ User used a 2FA recovery codeRECOVERY_CODE_GEN
โ User generated new 2FA recovery codes
- 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
curl -X GET "http://localhost:8080/activity-logs?event_type=LOGIN&limit=5" \
-H "Authorization: Bearer your-jwt-token"
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"
curl -X GET "http://localhost:8080/activity-logs/event-types" \
-H "Authorization: Bearer your-jwt-token"
{
"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
}
}
- Run all tests:
make test
orgo test ./...
- Coverage: Unit & integration tests for core logic and endpoints
- Use the provided test script:
./test_api.sh
- Test basic authentication flows and error handling
- Interactive testing via Swagger UI at
/swagger/index.html
# Start development environment with hot reload
make docker-dev
# or
./dev.sh # Linux/Mac
dev.bat # Windows
# Build and start production containers
make docker-compose-up
# or
docker-compose up -d --build
# 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
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
- 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)
make setup
โ Install dependencies and toolsmake dev
โ Start development server with hot reloadmake test
โ Run tests during developmentmake fmt
โ Format code before committingmake lint
โ Check code quality./test_api.sh
โ Test API endpoints manually
Please read CONTRIBUTING.md for details on our code of conduct and the process for submitting pull requests.
Please read SECURITY.md for information about reporting security vulnerabilities.
This project is licensed under the MIT License - see the LICENSE file for details.