{"id":48166435,"url":"https://github.com/finettt/auth-service","last_synced_at":"2026-04-04T17:29:59.037Z","repository":{"id":313597174,"uuid":"1050973012","full_name":"finettt/auth-service","owner":"finettt","description":"A FastAPI-based authentication service that provides user registration, login, account deletion, and JWT token management with secure password hashing using bcrypt. The service runs behind a Premier gateway with SSL termination, rate limiting, and monitoring capabilities.","archived":false,"fork":false,"pushed_at":"2025-11-02T06:57:09.000Z","size":183,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-11-02T08:28:53.107Z","etag":null,"topics":["authentication"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"agpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/finettt.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":"CODE-OF-CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-09-05T08:35:36.000Z","updated_at":"2025-11-02T06:56:57.000Z","dependencies_parsed_at":"2025-09-07T08:24:55.298Z","dependency_job_id":"0803bbd6-3579-46d4-ba09-e1483abcf3c9","html_url":"https://github.com/finettt/auth-service","commit_stats":null,"previous_names":["finettt/auth-service"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/finettt/auth-service","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/finettt%2Fauth-service","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/finettt%2Fauth-service/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/finettt%2Fauth-service/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/finettt%2Fauth-service/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/finettt","download_url":"https://codeload.github.com/finettt/auth-service/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/finettt%2Fauth-service/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31407644,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-04T10:20:44.708Z","status":"ssl_error","status_checked_at":"2026-04-04T10:20:06.846Z","response_time":60,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["authentication"],"created_at":"2026-04-04T17:29:58.406Z","updated_at":"2026-04-04T17:29:59.020Z","avatar_url":"https://github.com/finettt.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Auth Service\n\nA FastAPI-based authentication service that provides user registration, login, account deletion, and JWT token management with secure password hashing using bcrypt. The service runs behind a Premier gateway with SSL termination, rate limiting, and monitoring capabilities.\n\n**Version**: 0.1.0\n**Python**: 3.12+\n**Package Manager**: UV\n\n## Features\n\n- **User Registration**: Create new user accounts with login and password\n- **User Login**: Authenticate existing users and receive JWT tokens\n- **Account Deletion**: Remove user accounts securely\n- **JWT Authentication**: Secure token-based authentication with Redis session management\n- **Password Security**: Uses bcrypt hashing for password encryption\n- **Database Integration**: PostgreSQL database with proper DAO pattern implementation\n- **Redis Session Management**: Token storage and validation\n- **REST API**: Clean RESTful API endpoints with proper HTTP status codes\n- **User Profile**: Retrieve current user profile information\n- **Logout**: Secure token revocation\n\n## Tech Stack\n\n- **Framework**: FastAPI\n- **Gateway**: Premier (ASGI Gateway with rate limiting, monitoring)\n- **Database**: PostgreSQL\n- **Cache/Session**: Redis\n- **Password Hashing**: bcrypt\n- **Authentication**: JWT (JSON Web Tokens)\n- **Data Validation**: Pydantic\n- **Server**: Uvicorn\n- **Python**: 3.12+\n- **SSL/TLS**: HTTPS with certificate termination\n\n## API Endpoints\n\n### Register User\n- **POST** `/api/register`\n- **Request Body**:\n  ```json\n  {\n    \"login\": \"user\",\n    \"password\": \"securepassword123\"\n  }\n  ```\n- **Response**: `201 Created` with user ID\n- **Description**: Creates a new user account with the provided login and password\n\n### Login User\n- **POST** `/api/login`\n- **Request Body**:\n  ```json\n  {\n    \"login\": \"user\",\n    \"password\": \"securepassword123\"\n  }\n  ```\n- **Response**:\n  - `200 OK` with JWT token for valid credentials\n  - `401 Unauthorized` if credentials are invalid\n- **Description**: Authenticates a user and returns a JWT access token\n\n### Logout User\n- **POST** `/api/logout`\n- **Headers**: `Authorization: Bearer \u003ctoken\u003e`\n- **Response**: `200 OK` with success message\n- **Description**: Logs out the user by revoking their token\n\n### Get User Profile\n- **GET** `/api/profile`\n- **Headers**: `Authorization: Bearer \u003ctoken\u003e`\n- **Response**: `200 OK` with user profile data\n- **Description**: Retrieves the current authenticated user's profile\n\n### Delete Account\n- **POST** `/api/delete`\n- **Request Body**:\n  ```json\n  {\n    \"login\": \"user\",\n    \"password\": \"securepassword123\"\n  }\n  ```\n- **Headers**: `Authorization: Bearer \u003ctoken\u003e` (optional for security)\n- **Response**:\n  - `200 OK` with success message for valid credentials\n  - `401 Unauthorized` if credentials are invalid\n- **Description**: Deletes a user account after verifying credentials\n\n### Health Check\n- **GET** `/health`\n- **Response**: `200 OK` with service status\n- **Description**: Health check endpoint for monitoring\n\n## Project Structure\n\n```\nsrc/\n├── app.py                 # FastAPI application entry point\n├── routes/\n│   ├── api.py            # Main API routes (auth, profile, etc.)\n│   └── health.py         # Health check endpoint\n├── database/\n│   ├── connection.py     # Database connection management\n│   ├── settings.py       # Database and application settings\n│   ├── schema.sql        # Database schema\n│   ├── dao/\n│   │   ├── users.py      # Data Access Object for users\n│   │   └── tokens.py     # Data Access Object for tokens\n│   └── redis_connection.py # Redis connection management\n├── crypto/\n│   └── utils.py          # Password encryption utilities (bcrypt)\n└── dto/\n    └── api.py            # Data Transfer Objects for API\n```\n\n## Installation\n\n### Prerequisites\n- Python 3.12+\n- PostgreSQL database\n- Redis server\n\n### Local Development\n\n1. Clone the repository\n2. Install dependencies using UV (recommended):\n   ```bash\n   uv sync\n   ```\n   Or using pip:\n   ```bash\n   pip install -e .\n   ```\n3. Set up environment variables (create a `.env` file):\n   ```bash\n   # Database\n   DB_HOST=localhost\n   DB_PORT=5432\n   DB_USER=auth_user\n   DB_PASSWORD=password\n   DB_TABLE=auth\n\n   # Redis\n   REDIS_HOST=localhost\n   REDIS_PORT=6379\n   REDIS_DB=0\n\n   # JWT\n   SECRET_KEY=your-secret-key-here\n\n   # SSL (for local development with HTTPS)\n   SSL_CERTFILE=.ssl/cert.pem\n   SSL_KEYFILE=.ssl/key.pem\n   ```\n4. Set up the database:\n   - Create the PostgreSQL database\n   - Run the schema from `src/database/schema.sql`\n5. Generate SSL certificates (for HTTPS):\n   ```bash\n   mkdir -p .ssl\n   openssl req -x509 -newkey rsa:4096 -keyout .ssl/key.pem -out .ssl/cert.pem -days 365 -nodes\n   ```\n\n### Docker Development\n\n1. Copy and configure environment variables:\n   ```bash\n   cp .db.env.example .db.env\n   # Edit .db.env with your configuration\n   ```\n2. Set up SSL certificates:\n   ```bash\n   mkdir -p .ssl\n   # Place your SSL certificate files at:\n   # - .ssl/cert.pem\n   # - .ssl/key.pem\n   ```\n3. Start the services:\n   ```bash\n   docker-compose up -d\n   ```\n\nThe API will be available at `https://localhost:443` (HTTPS)\n\n## Running the Application\n\n### Local Development\n\n```bash\n# Using UV (recommended)\nuv run gateway.py\n\n# Or using uvicorn directly\nuvicorn gateway:gateway --host 0.0.0.0 --port 443 --ssl-certfile .ssl/cert.pem --ssl-keyfile .ssl/key.pem --workers 4\n```\n\nThe API will be available at `https://localhost:443` (HTTPS)\n\n### Premier Gateway Setup\n\nThe application uses a Premier gateway configuration defined in [`gateway.py`](gateway.py:1) and [`premier.yml`](premier.yml:1). The gateway provides:\n\n- **ASGI Gateway**: Integration with FastAPI through Premier\n- **Redis Caching**: AsyncRedisCache for token management\n- **Configuration**: GatewayConfig loaded from premier.yml file\n- **Load Balancing**: Built-in support for multiple instances\n\nTo run with the Premier gateway:\n```bash\nuv run gateway.py\n```\n\n### Production\n\n```bash\nuvicorn gateway:gateway --host 0.0.0.0 --port 443 --ssl-certfile .ssl/cert.pem --ssl-keyfile .ssl/key.pem --workers 4\n```\n\n## API Documentation\n\nOnce running, you can access:\n- Interactive API documentation at `https://localhost:443/docs`\n- Alternative API documentation at `https://localhost:443/redoc`\n\n## Premier Gateway Configuration\n\nThe service is configured with a Premier gateway that provides:\n\n- **Rate Limiting**: 100 requests per minute per endpoint\n- **Monitoring**: Request logging with 5.0 second threshold\n- **SSL Termination**: HTTPS support with certificate management\n- **ASGI Compatibility**: Full async support with FastAPI\n\nConfiguration is managed through `premier.yml`:\n\n```yaml\npremier:\n  paths:\n    - pattern: \"/api/*\"\n      features:\n        rate_limit:\n          quota: 100\n          duration: 60\n        monitoring:\n          log_threshold: 5.0\n```\n\n## Security Features\n\n- **Password Security**: Passwords are hashed using bcrypt with salt\n- **JWT Authentication**: Stateless authentication with configurable expiration\n- **Session Management**: Token validation and storage in Redis\n- **Input Validation**: Request/response validation using Pydantic models\n- **Secure Token Handling**: Automatic token validation and refresh\n- **Database Security**: Proper connection management and transaction handling\n- **Error Handling**: Comprehensive error handling with appropriate HTTP status codes\n- **SSL/TLS**: HTTPS encryption with proper certificate handling\n- **Rate Limiting**: Protection against brute force attacks\n\n## Development\n\n### Package Management\n\nThis project uses **UV**, a modern Python package manager for fast and reliable dependency management:\n\n```bash\n# Install dependencies\nuv sync\n\n# Install development dependencies\nuv sync --dev\n\n# Run the application\nuv run gateway.py\n\n# Run tests\nuv run pytest\n\n# Run with coverage\nuv run pytest --cov=src --cov-report=html\n```\n\n### Running Tests\n\n```bash\n# Run all tests\npytest\n\n# Run tests with coverage\npytest --cov=src --cov-report=html\n\n# Run specific test file\npytest test/test_app.py\n\n# Run tests with verbose output\npytest -v\n```\n\n### Code Quality\n\nThe project uses various tools for code quality:\n- **Ruff**: For linting and formatting\n- **Bandit**: For security linting\n- **Coverage**: For test coverage analysis\n- **Pydantic**: For data validation and serialization\n\n### Pre-commit Hooks\n\nThe project includes pre-commit hooks for code quality:\n```bash\npre-commit install\npre-commit run --all-files\n```\n\n### Development Tools\n\n- **UV**: Modern Python package manager\n- **Bandit**: Security linting\n- **Ruff**: Fast Python linter and formatter\n- **HTTPX**: For testing HTTP endpoints\n- **Pytest**: Test framework with coverage support\n\n### Dependencies\n\n**Core Dependencies:**\n- FastAPI \u003e= 0.116.1\n- PyJWT \u003e= 2.9.0\n- bcrypt \u003e= 4.2.1\n- psycopg-binary \u003e= 3.2.10\n- redis \u003e= 6.4.0\n- premier \u003e= 0.4.10\n\n**Development Dependencies:**\n- pytest \u003e= 8.0.0\n- ruff \u003e= 0.12.11\n- bandit \u003e= 1.8.6\n- httpx \u003e= 0.28.1\n- pre-commit \u003e= 3.8.0\n\n### Environment Variables\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `DB_HOST` | PostgreSQL host | `localhost` |\n| `DB_PORT` | PostgreSQL port | `5432` |\n| `DB_USER` | PostgreSQL username | `auth_user` |\n| `DB_PASSWORD` | PostgreSQL password | `password` |\n| `DB_TABLE` | PostgreSQL database name | `auth` |\n| `REDIS_HOST` | Redis host | `localhost` |\n| `REDIS_PORT` | Redis port | `6379` |\n| `REDIS_DB` | Redis database number | `0` |\n| `SECRET_KEY` | JWT secret key | - |\n| `SSL_CERTFILE` | SSL certificate file path | `.ssl/cert.pem` |\n| `SSL_KEYFILE` | SSL private key file path | `.ssl/key.pem` |\n| `LOG_LEVEL` | Application logging level | `INFO` |\n\n### Production Environment Variables\n\n| Variable | Description | Required |\n|----------|-------------|----------|\n| `DB_HOST` | PostgreSQL host | Yes |\n| `DB_PORT` | PostgreSQL port | `5432` |\n| `DB_USER` | PostgreSQL username | Yes |\n| `DB_PASSWORD` | PostgreSQL password | Yes |\n| `DB_TABLE` | PostgreSQL database name | `auth` |\n| `REDIS_HOST` | Redis host | Yes |\n| `REDIS_PORT` | Redis port | `6379` |\n| `REDIS_DB` | Redis database number | `0` |\n| `SECRET_KEY` | JWT secret key (min 32 chars) | Yes |\n| `LOG_LEVEL` | Application logging level | `INFO` |\n| `SSL_CERTFILE` | SSL certificate file path | `/app/.ssl/cert.pem` |\n| `SSL_KEYFILE` | SSL private key file path | `/app/.ssl/key.pem` |\n\n## Production Deployment\n\n### Docker Compose\n\nFor production deployment, use the provided [`compose.prod.yml`](compose.prod.yml:1) with advanced features:\n\n```bash\n# Copy and configure environment variables\ncp .prod.env.example .prod.env\n# Edit .prod.env with production configuration\n\n# Set up SSL certificates\nmkdir -p ssl\n# Place your SSL certificate files at:\n# - ssl/cert.pem\n# - ssl/key.pem\n# Set proper permissions: chmod 600 ssl/cert.pem ssl/key.pem\n\n# Start services\ndocker-compose -f compose.prod.yml up -d\n\n# View logs\ndocker-compose -f compose.prod.yml logs -f auth_api\n```\n\n### Production Features\n\nThe production configuration includes:\n\n- **Resource Limits**: CPU and memory limits for each service\n- **Health Checks**: Automated health monitoring for all services\n- **Scaling**: Multiple replicas with rolling updates\n- **Network**: Dedicated bridge network for service isolation\n- **SSL Certificate Mounting**: Read-only SSL certificate volumes\n- **Restart Policies**: Automatic restart on failure\n- **Database Persistence**: Named volumes for data persistence\n\n### SSL Certificate Setup\n\nFor production, use proper SSL certificates:\n\n```bash\n# Using Let's Encrypt (recommended for production)\nsudo certbot certonly --standalone -d your-domain.com\n\n# Copy certificates to the project\nsudo cp /etc/letsencrypt/live/your-domain.com/fullchain.pem ssl/cert.pem\nsudo cp /etc/letsencrypt/live/your-domain.com/privkey.pem ssl/key.pem\n\n# Set proper permissions\nchmod 600 ssl/cert.pem ssl/key.pem\n```\n\n### Health Monitoring\n\nThe service includes health check endpoints:\n- **Health Check**: `GET /health` - Returns service status (internal port 8000)\n- **Docker Health Check**: Built into the Docker image with 30-second intervals\n- **Service Dependencies**: Waits for PostgreSQL and Redis health checks before starting\n\n### Scaling Configuration\n\nThe production configuration supports:\n- **Multiple Replicas**: 2 replicas for the auth_api service\n- **Resource Limits**:\n  - Auth API: 2.0 CPU cores, 2GB memory (limits), 1.0 CPU core, 1GB memory (reservations)\n  - PostgreSQL: 1.0 CPU core, 1GB memory (limits), 0.5 CPU core, 512MB memory (reservations)\n  - Redis: 0.5 CPU core, 512MB memory (limits), 0.2 CPU core, 256MB memory (reservations)\n- **Rolling Updates**: Parallelism of 1 with 10-second delays\n- **Restart Policies**: Automatic restart with exponential backoff\n\n### Environment Configuration\n\nProduction environment should include:\n\n```bash\n# Database (use production values)\nDB_HOST=your-db-host\nDB_PORT=5432\nDB_USER=auth_user\nDB_PASSWORD=secure-password\nDB_TABLE=auth\n\n# Redis (use production values)\nREDIS_HOST=your-redis-host\nREDIS_PORT=6379\nREDIS_DB=0\n\n# JWT (use a strong, randomly generated key)\nSECRET_KEY=your-very-secure-secret-key-here\n\n# SSL (point to your production certificates)\nSSL_CERTFILE=/path/to/your/cert.pem\nSSL_KEYFILE=/path/to/your/key.pem\n```\n\n### Health Monitoring\n\nThe service includes health check endpoints:\n- **Health Check**: `GET /health` - Returns service status\n- **Docker Health Check**: Built into the Docker image\n\n### Scaling\n\nFor production scaling:\n- Use multiple workers: `--workers 4`\n- Consider load balancing multiple instances\n- Monitor Redis and PostgreSQL performance\n\n## License\n\nThis project is licensed under the APGL-3.0 License - see the [LICENSE](LICENSE) file for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffinettt%2Fauth-service","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffinettt%2Fauth-service","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffinettt%2Fauth-service/lists"}