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-initor
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
.envand 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:
airorgo 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 helpto 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 testorgo 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=8080For Docker Compose, use service names:
DB_HOST=postgresREDIS_ADDR=redis:6379
For local development, use localhost:
DB_HOST=localhostREDIS_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.