A multi-tenant backend API for logging and managing chat sessions, supporting both authenticated and unauthenticated usage with analytics capabilities.
- Multi-tenancy: Separate organizations with isolated data
- Dual Authentication: API key for chat plugins and JWT for dashboard users
- Role-based Access Control: Superadmin, admin, user, and viewer roles with specific permissions
- Analytics: Usage metrics per organization with customizable reporting
- Export Capabilities: Export chat data in multiple formats (CSV, JSON) with both sync and async options
- Clean Architecture: Separation of concerns with layered design (handler → service → repository)
- Strategy Pattern: Used for exporter formats (JSON, CSV) and other pluggable components
- Dependency Injection: Constructor-based DI for improved testability and maintainability
- Asynchronous Jobs: Background processing with Redis and Asynq for resource-intensive tasks
The API is documented using Swagger/OpenAPI:
- Generate documentation:
./scripts/docs_generate.sh
or./scripts/docs_generate.ps1
- Start the server:
go run cmd/server/main.go
- Open browser:
http://localhost:8080/openapi/index.html
Tip
View the package documentation for more details on the API endpoints and usage. godoc.org The API documentation is also available online at chatlogger-api-docs.kjanat.com.
- Language: Go 1.24.2+
- Web Framework: Gin
- ORM: GORM with PostgreSQL
- Authentication: JWT using golang-jwt/jwt
- Password Hashing: bcrypt
- Configuration: Environment-based loading
- Queue System: Asynq with Redis (for async exports)
- Containerization: Docker & Docker Compose
- Go 1.24.2 or higher
- PostgreSQL 14+
- Redis (optional, for async exports)
- Docker & Docker Compose (optional for containerized deployment)
The easiest way to get started is using Docker Compose:
# Clone the repository
git clone https://github.com/kjanat/chatlogger-api-go.git
cd chatlogger-api-go
# Start the application and database
docker-compose up -d
The API will be available at http://localhost:8080
.
# Clone the repository
git clone https://github.com/kjanat/chatlogger-api-go.git
cd chatlogger-api-go
# Install dependencies
go mod download
# Setup environment variables (copy example and modify)
cp .env.example .env
# Edit .env with your database credentials and settings
# Run migrations
psql -U postgres -d chatlogger -f migrations/001_initial_schema.sql
psql -U postgres -d chatlogger -f migrations/002_ensure_defaults.sql
psql -U postgres -d chatlogger -f migrations/003_add_exports_table.sql
# Run the server
go run cmd/server/main.go
# Run the worker (optional, for async exports)
go run cmd/worker/main.go
Uses API key authentication via the x-organization-api-key
header:
curl -X POST \
http://localhost:8080/v1/orgs/acme/chats \
-H 'x-organization-api-key: your-api-key' \
-H 'Content-Type: application/json' \
-d '{
"title": "Support Chat",
"tags": ["support", "billing"],
"metadata": {
"browser": "Chrome",
"platform": "Windows"
}
}'
Uses email/password login with JWT authentication:
# Login and get JWT cookie
curl -X POST \
http://localhost:8080/auth/login \
-H 'Content-Type: application/json' \
-d '{
"email": "admin@example.com",
"password": "your-password"
}' \
-c cookies.txt
# Use the JWT cookie for authenticated requests
curl -X GET \
http://localhost:8080/users/me \
-b cookies.txt
The API implements a comprehensive role-based access control system:
Role | Description | Capabilities |
---|---|---|
superadmin |
System-wide administrator with unrestricted access | Full access to all endpoints and organizations |
admin |
Organization administrator | Full access within their organization including API keys |
user |
Regular organization user | Access to own chats/messages and basic functionality |
viewer |
Read-only user | View-only access to permitted resources |
RBAC is implemented via middleware that checks the user's role before allowing access to protected resources.
/cmd
/server → Main API server entry point
/tools → Utility tools
/worker → Background job worker for async exports
/internal
/api → Gin router and setup
/config → Configuration loading
/domain → Core models and interfaces
/handler → Request handlers
/hash → Password hashing utilities
/jobs → Queue and processor for async tasks
/middleware → Auth, RBAC, logging middleware
/repository → Database access layer
/service → Business logic layer
/strategy → Strategy pattern implementations (exporters)
/version → Version information
/migrations → SQL schema migrations
/scripts → Utility scripts
Method | Endpoint | Description |
---|---|---|
GET |
/health |
Health check endpoint |
GET |
/version |
API version information |
GET |
/openapi/*any |
Swagger UI documentation |
GET |
/openapi/*any |
OpenAPI documentation |
Method | Endpoint | Description |
---|---|---|
POST |
/auth/login |
Login and get JWT cookie |
POST |
/auth/register |
Register a new user |
POST |
/auth/logout |
Logout and clear JWT cookie |
Method | Endpoint | Description |
---|---|---|
GET |
/v1/users/me |
Get current user profile |
PATCH |
/v1/users/me |
Update current user profile |
POST |
/v1/users/me/password |
Change current user's password |
POST |
/v1/chats |
Create a new chat |
GET |
/v1/chats |
List user's chats |
GET |
/v1/chats/:chatID |
Get a specific chat |
PATCH |
/v1/chats/:chatID |
Update a chat |
DELETE |
/v1/chats/:chatID |
Delete a chat |
GET |
/v1/chats/:chatID/messages |
Get messages from a chat |
GET |
/v1/analytics/messages |
Get message analytics |
Method | Endpoint | Description |
---|---|---|
GET |
/v1/orgs/me/apikeys |
List organization API keys |
POST |
/v1/orgs/me/apikeys |
Generate a new API key |
DELETE |
/v1/orgs/me/apikeys/:id |
Revoke an API key |
Method | Endpoint | Description |
---|---|---|
POST |
/v1/exports |
Create async export job |
GET |
/v1/exports |
List export jobs |
GET |
/v1/exports/:id |
Get export job status |
GET |
/v1/exports/:id/download |
Download completed export |
POST |
/v1/exports/sync |
Create synchronous export |
Method | Endpoint | Description |
---|---|---|
POST |
/v1/orgs/:slug/chats |
Create a new chat session |
POST |
/v1/orgs/:slug/chats/:chatID/messages |
Add a message to a chat |
The application is configured using environment variables:
Variable | Description | Default |
---|---|---|
PORT |
Server port | 8080 |
DATABASE_URL |
PostgreSQL connection string | Required |
JWT_SECRET |
Secret for JWT signing | Required |
REDIS_ADDR |
Redis address for job queue | localhost:6379 |
EXPORT_DIR |
Directory to store export files | ./exports |
The application supports both synchronous and asynchronous exports:
- Immediate response with download
- Good for small data sets
- Available at
/exports/orgs/me/sync
- Works without Redis
- Queued processing with status tracking
- Better for large data sets
- Requires Redis and worker process
- Creates a job at
/exports/orgs/me
- Check status at
/exports/orgs/me/:id
- Download at
/exports/orgs/me/:id/download
Both export types support JSON and CSV formats.
# Run all tests
go test ./...
# Run tests with coverage
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out
# Run linting checks
golangci-lint run
The application includes version information that can be injected during build:
# Build with version information
docker build -t chatlogger-api \
--build-arg VERSION=0.5.0 \
--build-arg BUILD_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ") \
--build-arg GIT_COMMIT=$(git rev-parse HEAD) \
.
All container images are signed using Sigstore cosign. You can verify the authenticity of the images using the following command:
# Verify the container image signature
cosign verify \
--key=cosign.pub \
ghcr.io/kjanat/chatlogger-api-server:0.5.0
# Or use the public key URL
cosign verify \
--key=https://raw.githubusercontent.com/kjanat/chatlogger-api-go/master/cosign.pub \
ghcr.io/kjanat/chatlogger-api-worker:0.5.0
The public key for verification (cosign.pub
) is available in the root of the repository. For production deployments, we recommend verifying image signatures as part of your CI/CD pipeline to ensure supply chain security.
The project includes GitHub Actions workflows for CI/CD:
- Build Workflow: Builds, tests, and tags versions on pushes to main
- Release Workflow: Creates GitHub releases when tags are pushed
Here are some potential enhancements planned for future development:
- Export Features: Implemented export functionality as a strategy pattern (JSON/CSV)
- Async Exports: Added background processing for large exports
- Documentation: Generated API documentation with Swagger/OpenAPI
- Pagination: Add cursor-based pagination to list endpoints
- Enhanced Testing: Expand unit and integration test coverage
- Monitoring: Add structured logging and metrics collection
- Real-time notifications: Add WebSocket support for live updates
- Multi-factor Authentication: Add 2FA support for dashboard users
- Improved Analytics: More detailed analytics dashboards and reports
- Search Capabilities: Add full-text search for chat messages
This project is licensed under the MIT License - see the LICENSE file for details.
Contributions are welcome! Please feel free to submit a Pull Request.
- 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