A comprehensive Customer Relationship Management (CRM) backend API built with Go, Gin framework, and GORM. This system provides a robust foundation for managing customer relationships, deals, tasks, and notes through a RESTful API.
This backend API is designed with modern architecture principles and provides a complete set of endpoints for a CRM system. It includes authentication, authorization, and full CRUD operations for all necessary entities in a CRM application.
- Language: Go (1.17+)
- Web Framework: Gin
- ORM: GORM
- Database: PostgreSQL
- Authentication: JWT with role-based access control
- Validation: go-playground/validator
- Logging: Structured logging with logrus
- Documentation: Swagger/OpenAPI
- Monitoring: Prometheus metrics
- Security:
- Rate limiting with IP-based restrictions
- Request size limiting
- CORS configuration
- API key validation
- Content security policies
- Secure JWT-based authentication
- Role-based access control (admin/user roles)
- Resource ownership validation
- Refresh token mechanism
- Mobile-specific authentication endpoints
- Protection against brute-force attacks with stricter rate limiting for auth endpoints
- Complete CRUD operations for all entities
- Relationship management between all models
- Structured response format for consistent API
- Data validation using go-playground/validator
- Health check endpoints for container orchestration (
/healthand/ready) - Prometheus metrics for monitoring (admin-protected)
- Structured logging with request tracking
- Configurable log levels
- Comprehensive Swagger documentation with interactive testing
- Special test mode for UI development
- Test data seeding capabilities
- Standardized error responses
The system includes the following core data models with appropriate relationships:
-
User
- Core attributes: Username, Email, Password (encrypted), Role
- Validation: Email format, username length, password strength
- Relationships: One-to-one with Settings, one-to-many with Contacts, Deals, Tasks, Notes
-
Contact
- Core attributes: First Name, Last Name, Email, Phone, etc.
- Relationships: Belongs to User, has many Deals and Notes
-
Deal
- Core attributes: Title, Description, Value, Status
- Relationships: Belongs to Contact and User, has many Tasks
-
Task
- Core attributes: Title, Details, Due Date, Completed Status
- Relationships: Belongs to Deal and User
-
Note
- Core attributes: Content, timestamps
- Relationships: Can belong to Contact, Deal, and User
-
Settings
- Core attributes: Theme, Language
- Relationship: Belongs to User
- Go 1.17 or higher
- PostgreSQL 12 or higher
- Docker & Docker Compose (optional, for containerized setup)
- Clone the repository:
git clone https://github.com/yourusername/mini-crm.git
cd mini-crm- Set up environment variables:
Create a
.envfile in the backend directory with the following variables:
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=yourpassword
DB_NAME=mini_crm
JWT_SECRET_KEY=your-secret-key
JWT_EXPIRATION_HOURS=24
PORT=8081
ENV=development
ALLOWED_ORIGINS=http://localhost:3000
LOG_LEVEL=info
- Install backend dependencies:
cd backend
go mod download- Start the backend server:
# Run directly
go run main.go
# Using make commands
make run # Standard run
make run-dev # Development mode with hot reload
# Using Docker
docker-compose up -dThe system creates a default admin user on first run:
- Username:
admin - Email:
[email protected] - Password:
admin123
Important: Change these credentials immediately in a production environment.
The API is accessible at:
http://localhost:8081/api/v1
All protected endpoints require a valid JWT token in the Authorization header:
Authorization: Bearer YOUR_JWT_TOKEN
To obtain a token, send a POST request to /api/v1/auth/login with valid credentials.
POST /api/v1/auth/register- Register new userPOST /api/v1/auth/login- LoginGET /api/v1/auth/me- Get current userPOST /api/v1/auth/refresh- Refresh tokenPOST /api/v1/auth/mobile/login- Mobile-optimized loginPOST /api/v1/auth/mobile/refresh- Mobile-optimized token refresh
GET /api/v1/users- List all usersGET /api/v1/users/:id- Get user by IDPOST /api/v1/users- Create user (admin only)PUT /api/v1/users/:id- Update userDELETE /api/v1/users/:id- Delete user (admin only)
GET /api/v1/contacts- List user's contactsGET /api/v1/contacts/:id- Get contact by IDPOST /api/v1/contacts- Create contactPUT /api/v1/contacts/:id- Update contactDELETE /api/v1/contacts/:id- Delete contact
Similar endpoints exist for Deals, Notes, Tasks, and Settings.
- Access the Swagger UI at
/swagger/index.htmlwhen running in development mode - For a complete collection of API requests, import the file
mini_crm_api_complete.jsoninto Postman
- JWT tokens with configurable expiration
- Separate middleware for admin-only routes
- Resource ownership verification on all operations
- Password encryption with bcrypt
- IP-based rate limiting with different thresholds for sensitive endpoints
- Request size limiting (default: 10MB) to prevent DoS attacks
- CORS configuration with environment-specific settings
- Content Security Policy headers
- API key validation for external applications
- Protection against common web vulnerabilities
- Security headers (X-Content-Type-Options, X-Frame-Options, etc.)
- Detailed request logging with unique request IDs
- Configurable log levels based on environment
- Prometheus metrics for monitoring (protected by admin authentication)
- Environment-specific security configurations
The application uses structured logging with configurable levels:
- debug: Detailed information for debugging
- info: General operational information
- warn: Warning conditions that should be addressed
- error: Error conditions that affect functionality
Logs include contextual information such as request ID, user ID (when authenticated), IP address, and timing information.
Comprehensive Swagger/OpenAPI documentation is integrated:
- Access the interactive UI at
/swagger/index.htmlin development mode - Test endpoints directly from the browser
- View complete request/response models
- Export documentation in JSON or YAML format
In production, Swagger is disabled by default but can be enabled with the ENABLE_SWAGGER=true environment variable.
/healthendpoint provides system health information/readyendpoint for container orchestration readiness probes- Prometheus metrics at
/metrics(admin-protected)
The backend includes a specialized mode for frontend development, making it easier to work on the UI without managing authentication and test data manually.
-
Configure the environment by using the
.env.developmentfile with these settings:# Core test mode settings UI_TEST_MODE=true SEED_TEST_DATA=true # Test user credentials [email protected] UI_TEST_PASSWORD=test1234 # Authentication bypass (use with caution) DISABLE_AUTH_FOR_TESTS=false -
Start the server in development mode:
make run-dev
- Test Data Generation: Creates realistic sample data including users, contacts, deals, tasks, and notes
- Authentication Helpers: Simplified authentication for development
- Automatic CORS: Development origins are automatically allowed
- Diagnostic Headers: Special headers indicate test mode is active
This mode is designed only for development. The server automatically disables these features in production, but as an additional precaution, never deploy with these settings enabled.
/backend
├── cmd/ # Application entry point
├── config/ # Database and application configuration
├── controllers/ # API endpoint handlers for all models
├── middleware/ # HTTP middleware components
├── models/ # Data models and database schema
├── routes/ # API route definitions
├── utils/ # Helper functions and shared utilities
├── main.go # Main application file
├── go.mod # Go module definition
├── go.sum # Go module checksums
└── Dockerfile # Container definition
- Add new models in
/models - Create corresponding controllers in
/controllers - Register new routes in
/routes/router.go - Add models to the migration list in
main.go
The application can be deployed in several ways:
-
Standard Go deployment
- Build the binary with
go build - Deploy with proper environment variables
- Build the binary with
-
Docker deployment
- Use the included Dockerfile
- Configure with environment variables
For detailed instructions, see the Deployment Guide.
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License with an attribution clause - see the LICENSE file for details.
