Auth Docker Postgres JWT Example
This example demonstrates a boilerplate setup for a Go Fiber application that uses Docker, PostgreSQL, and JWT for authentication.
Description
This project provides a starting point for building a web application with user authentication using JWT. It leverages Docker for containerization and PostgreSQL as the database.
Requirements
- Docker
- Docker Compose
- Go 1.18 or higher
Setup
-
Clone the repository:
git clone https://github.com/gofiber/recipes.git
cd recipes/auth-docker-postgres-jwt -
Set the environment variables in a
.env
file:DB_PORT=5432
DB_USER=example_user
DB_PASSWORD=example_password
DB_NAME=example_db
SECRET=example_secret -
Build and start the Docker containers:
docker-compose build
docker-compose up
The API and the database should now be running.
Database Management
You can manage the database via psql
with the following command:
docker-compose exec db psql -U <DB_USER>
Replace <DB_USER>
with the value from your .env
file.
API Endpoints
The following endpoints are available in the API:
- POST /api/auth/register: Register a new user.
- POST /api/auth/login: Authenticate a user and return a JWT.
- GET /api/user/:id: Get a user (requires a valid JWT).
- PATCH /api/user/:id: Update a user (requires a valid JWT).
- DELETE /api/user/:id: Delete a user (requires a valid JWT).
Example Usage
-
Register a new user:
curl -X POST http://localhost:3000/api/auth/register -d '{"username":"testuser", "password":"testpassword"}' -H "Content-Type: application/json"
-
Login to get a JWT:
curl -X POST http://localhost:3000/api/auth/login -d '{"username":"testuser", "password":"testpassword"}' -H "Content-Type: application/json"
-
Access a protected route:
curl -H "Authorization: Bearer <JWT>" http://localhost:3000/api/user/1
Replace <JWT>
with the token received from the login endpoint.
Conclusion
This example provides a basic setup for a Go Fiber application with Docker, PostgreSQL, and JWT authentication. It can be extended and customized further to fit the needs of more complex applications.