I built a sophisticated, prod-ready authentication API with Go, to have JWT-based authentication, role-based access control, and comprehensive security measures.
(I used ChatGPT to write this documentation from my rough notes about what this can do, so you can understand it well)
- π JWT Authentication - Secure token-based authentication with access and refresh tokens
- π₯ Role-Based Access Control - Admin and user roles with granular permissions
- ποΈ PostgreSQL Database - Full database integration with GORM ORM
- π Swagger Documentation - Interactive API documentation
- π³ Docker Support - Complete containerization with Docker Compose
- π Security Features - Password hashing, CORS, rate limiting, input validation
- π Health Checks - Database and application health monitoring
- π Auto Migration - Automatic database schema management
- π± Data Seeding - Pre-populated test data
- π Structured Logging - Comprehensive request and error logging
- β‘ High Performance - Optimized for production workloads
- Language: Go 1.21+
- Framework: Gin (HTTP router)
- Database: PostgreSQL 15
- ORM: GORM
- Authentication: JWT (JSON Web Tokens)
- Documentation: Swagger/OpenAPI 3.0
- Containerization: Docker & Docker Compose
- Logging: Logrus
- Validation: Go validator
- Go 1.21 or higher
- Docker and Docker Compose
- PostgreSQL (or use Docker)
- Git
# Clone the repository
git clone https://github.com/1cbyc/go-auth-api.git
cd go-auth-api
# Run the automated setup
make quick-start
# 1. Clone the repository
git clone https://github.com/1cbyc/go-auth-api.git
cd go-auth-api
# 2. Set up environment
cp env.example .env
# 3. Start PostgreSQL database
docker-compose up -d postgres
# 4. Install dependencies
go mod tidy
# 5. Generate Swagger docs
go install github.com/swaggo/swag/cmd/swag@latest
swag init
# 6. Run the application
go run main.go
# Start all services (app + database)
docker-compose up --build
# Start only the database
docker-compose up -d postgres
# View logs
docker-compose logs -f
# Build production image
make docker-build
# Run with environment variables
docker run -p 8080:8080 \
-e DB_HOST=your-db-host \
-e DB_PASSWORD=your-db-password \
-e JWT_SECRET=your-jwt-secret \
go-auth-api:latest
The application uses environment variables for configuration. Copy env.example
to .env
and customize:
# Server Configuration
SERVER_PORT=8080
SERVER_READ_TIMEOUT=15s
SERVER_WRITE_TIMEOUT=15s
SERVER_IDLE_TIMEOUT=60s
# Database Configuration
DB_DRIVER=postgres
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=postgres
DB_PASSWORD=password
DB_NAME=go_auth_api
DB_SSL_MODE=disable
# JWT Configuration
JWT_SECRET=your-super-secret-jwt-key-change-in-production
JWT_ACCESS_TOKEN_TTL=15m
JWT_REFRESH_TOKEN_TTL=168h
# Logging
LOG_LEVEL=info
LOG_FORMAT=text
Once the application is running, access the interactive API documentation:
- Swagger UI: https://localhost:8080/docs
- OpenAPI JSON: https://localhost:8080/swagger/doc.json
The application comes with pre-seeded users:
-
Admin User:
- Email:
admin@example.com
- Password:
adminpass123
- Role:
admin
- Email:
-
Regular User:
- Email:
user@example.com
- Password:
userpass123
- Role:
user
- Email:
POST /api/v1/auth/register
- User registrationPOST /api/v1/auth/login
- User loginPOST /api/v1/auth/refresh
- Refresh access tokenPOST /api/v1/auth/logout
- User logoutPOST /api/v1/auth/request-password-reset
- Request password reset (simulated email)POST /api/v1/auth/confirm-password-reset
- Confirm password resetPOST /api/v1/auth/verify-email
- Verify user emailGET /health
- Health check
GET /api/v1/users/profile
- Get user profilePUT /api/v1/users/profile
- Update user profilePOST /api/v1/users/change-password
- Change passwordPOST /api/v1/users/2fa/setup
- Initiate 2FA setup (get QR/secret)POST /api/v1/users/2fa/verify
- Verify 2FA code and enable 2FAPOST /api/v1/users/2fa/disable
- Disable 2FA
GET /api/v1/admin/users
- List all usersGET /api/v1/admin/users/{id}
- Get user by IDPUT /api/v1/admin/users/{id}
- Update userDELETE /api/v1/admin/users/{id}
- Delete user
The application automatically creates the following tables:
- users - User accounts and profiles
- refresh_tokens - JWT refresh token storage
Database migrations run automatically on startup. The application uses GORM's auto-migration feature.
Initial data is seeded automatically:
- Admin user account
- Regular user account
# Run all tests
make test
# Run tests with coverage
make test-coverage
# Run benchmark tests
make test-bench
# Test API endpoints
make test-api
# Show all available commands
make help
# Development workflow
make dev-setup # Set up development environment
make run # Run application locally
make build # Build application
make test # Run tests
make swagger # Generate Swagger docs
# Database operations
make db-start # Start PostgreSQL
make db-stop # Stop PostgreSQL
make db-reset # Reset database
make migrate # Run migrations
make seed # Seed data
# Docker operations
make docker-build # Build Docker image
make run-docker # Run with Docker Compose
make docker-stop # Stop containers
make docker-clean # Clean Docker resources
scripts/dev-setup.sh
- Linux/macOS development setupscripts/dev-setup.ps1
- Windows development setup
# Check application health
curl https://localhost:8080/health
# Response includes:
{
"status": "healthy",
"timestamp": "2024-01-01T00:00:00Z",
"service": "go-auth-api",
"version": "1.0.0",
"database": {
"status": "healthy"
}
}
The application uses structured logging with Logrus. Logs include:
- Request details (method, path, status, duration)
- User agent and client IP
- Request ID for tracing
- Error details with stack traces
Set these environment variables in production:
# Required
JWT_SECRET=your-super-secret-jwt-key-change-in-production
DB_HOST=your-production-db-host
DB_PASSWORD=your-production-db-password
# Optional
LOG_LEVEL=info
LOG_FORMAT=json
DB_SSL_MODE=require
# Build optimized production image
make prod-build
# Run production container
docker run -d \
--name go-auth-api \
-p 8080:8080 \
--env-file .env \
go-auth-api:latest
See k8s/
directory for Kubernetes manifests.
- JWT Secret: Use a strong, unique secret in production
- Database: Use SSL connections in production
- Passwords: Automatically hashed with bcrypt
- CORS: Configure allowed origins for your domain
- Rate Limiting: Implemented to prevent abuse
- Input Validation: All inputs are validated
- HTTPS: Use HTTPS in production
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Run the test suite
- Submit a pull request
This project is licensed under the MIT License - see the LICENSE file for details.
- Documentation: Check the docs/ directory
- Issues: Create an issue on GitHub
- Discussions: Use GitHub Discussions
See docs/whats-next.md for upcoming features and improvements.