Skip to content

VVSaltykov/awesomeProject

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Go Authentication API with PostgreSQL

A complete authentication system built with Go, featuring user registration, login, logout, and JWT token-based authentication with PostgreSQL database. The project follows clean architecture principles with a well-organized folder structure.

πŸ—οΈ Project Structure

awesomeProject/
β”œβ”€β”€ internal/
β”‚   β”œβ”€β”€ auth/           # Authentication logic (JWT, password hashing)
β”‚   β”œβ”€β”€ config/         # Configuration management
β”‚   β”œβ”€β”€ database/       # Database operations and connection
β”‚   β”œβ”€β”€ handlers/       # HTTP request handlers
β”‚   β”œβ”€β”€ models/         # Data structures and types
β”‚   └── routes/         # Route definitions and middleware
β”œβ”€β”€ main.go             # Application entry point
β”œβ”€β”€ go.mod              # Go module dependencies
β”œβ”€β”€ Dockerfile          # Docker containerization
β”œβ”€β”€ docker-compose.yml  # Docker Compose for development
β”œβ”€β”€ Makefile           # Build and development commands
β”œβ”€β”€ .dockerignore      # Docker build exclusions
β”œβ”€β”€ test_api.http      # API testing requests
└── README.md          # Project documentation

✨ Features

  • βœ… Clean Architecture - Well-organized code structure
  • βœ… User Registration - Create new accounts with username, email, and password
  • βœ… Secure Password Hashing - Bcrypt encryption for security
  • βœ… JWT Authentication - Secure token-based authentication
  • βœ… User Login/Logout - Complete authentication flow
  • βœ… Protected Routes - Middleware for secure endpoints
  • βœ… PostgreSQL Integration - Full database support
  • βœ… Input Validation - Comprehensive error handling
  • βœ… Docker Support - Containerized deployment
  • βœ… Environment Configuration - Flexible configuration management

πŸš€ Quick Start

Option 1: Using Docker Compose (Recommended)

  1. Clone and navigate to the project:

    cd awesomeProject
  2. Start the application with Docker Compose:

    docker-compose up --build

    This will start both PostgreSQL and the Go API automatically.

  3. Test the API:

    curl http://localhost:8080/health

Option 2: Local Development

  1. Install dependencies:

    make deps
    # or
    go mod tidy
  2. Set up PostgreSQL database:

    make db-setup

    Then create the database manually:

    CREATE DATABASE auth_db;
    CREATE USER postgres WITH PASSWORD 'password';
    GRANT ALL PRIVILEGES ON DATABASE auth_db TO postgres;
  3. Create environment file:

    # Create .env file with your configuration
    echo "DATABASE_URL=postgres://postgres:password@localhost:5432/auth_db?sslmode=disable" > .env
    echo "JWT_SECRET=your-super-secret-jwt-key-change-this-in-production" >> .env
  4. Run the application:

    make run
    # or
    go run main.go

πŸ› οΈ Development Commands

The project includes a Makefile with useful commands:

make help        # Show all available commands
make deps        # Install dependencies
make run         # Run the application
make build       # Build the application
make test        # Run tests
make clean       # Clean build artifacts
make lint        # Run linter
make docker      # Build Docker image
make docker-run  # Run with Docker

πŸ“‘ API Endpoints

Public Endpoints

1. Register User

  • POST /api/register
  • Body:
    {
      "username": "john_doe",
      "email": "john@example.com",
      "password": "securepassword123"
    }

2. Login User

  • POST /api/login
  • Body:
    {
      "username": "john_doe",
      "password": "securepassword123"
    }

3. Health Check

  • GET /health

Protected Endpoints

Note: All protected endpoints require the Authorization header with the JWT token.

1. Logout User

  • POST /api/logout
  • Headers: Authorization: Bearer <token>

2. Get User Profile

  • GET /api/profile
  • Headers: Authorization: Bearer <token>

πŸ§ͺ Testing the API

Use the provided test_api.http file with VS Code REST Client or similar tools:

# Test health endpoint
curl http://localhost:8080/health

# Register a new user
curl -X POST http://localhost:8080/api/register \
  -H "Content-Type: application/json" \
  -d '{
    "username": "testuser",
    "email": "test@example.com",
    "password": "password123"
  }'

# Login
curl -X POST http://localhost:8080/api/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "testuser",
    "password": "password123"
  }'

πŸ›οΈ Architecture Overview

Package Structure

  • internal/models/ - Data structures and request/response types
  • internal/database/ - Database connection and operations
  • internal/auth/ - JWT token management and password hashing
  • internal/handlers/ - HTTP request handlers
  • internal/routes/ - Route definitions and middleware setup
  • internal/config/ - Configuration and environment management

Key Components

  1. Models - Define data structures for users, requests, and responses
  2. Database - Handle all database operations with proper error handling
  3. Auth - Manage JWT tokens, password hashing, and authentication middleware
  4. Handlers - Process HTTP requests and return appropriate responses
  5. Routes - Define API endpoints and apply middleware
  6. Config - Manage environment variables and configuration

πŸ”’ Security Features

  • Password Hashing - Bcrypt with default cost
  • JWT Tokens - Secure token-based authentication with 24-hour expiration
  • Input Validation - Comprehensive validation for all user inputs
  • SQL Injection Protection - Parameterized queries
  • Environment Variables - Sensitive configuration stored securely

πŸ—„οΈ Database Schema

The application automatically creates the following table:

CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

🐳 Docker Support

Build and Run with Docker

# Build the image
docker build -t auth-api .

# Run the container
docker run -p 8080:8080 --env-file .env auth-api

Docker Compose

# Start all services
docker-compose up --build

# Stop all services
docker-compose down

# View logs
docker-compose logs -f auth-api

πŸ”§ Configuration

Environment Variables

Variable Description Default
DATABASE_URL PostgreSQL connection string postgres://postgres:password@localhost:5432/auth_db?sslmode=disable
JWT_SECRET Secret key for JWT signing your-secret-key

Database Connection String Format

postgres://username:password@host:port/database_name?sslmode=disable

πŸš€ Production Deployment

Considerations

  1. Change JWT Secret - Use a strong, unique secret key
  2. Database Security - Use SSL connections and strong passwords
  3. HTTPS - Always use HTTPS in production
  4. Rate Limiting - Implement rate limiting for auth endpoints
  5. Token Blacklisting - Implement token blacklisting for logout
  6. Logging - Add comprehensive logging
  7. Monitoring - Add health checks and monitoring

Environment Setup

# Production environment variables
export DATABASE_URL="postgres://user:password@host:5432/dbname?sslmode=require"
export JWT_SECRET="your-production-secret-key"

πŸ› Troubleshooting

Common Issues

  1. Database Connection Error

    • Ensure PostgreSQL is running
    • Check connection string in .env file
    • Verify database credentials
  2. Port Already in Use

    • Change port in code or kill existing process
    • Use different port with Docker: -p 8081:8080
  3. Missing Dependencies

    • Run make deps or go mod tidy
  4. Docker Issues

    • Ensure Docker and Docker Compose are installed
    • Check if ports are available
    • Use docker-compose logs to debug

πŸ“ License

This project is open source and available under the MIT License.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors