{"id":34501323,"url":"https://github.com/samanshafagh/python-fastapi-auth-microservice","last_synced_at":"2025-12-31T00:43:56.365Z","repository":{"id":329955047,"uuid":"1121120449","full_name":"samanshafagh/python-fastapi-auth-microservice","owner":"samanshafagh","description":"Production-ready authentication microservice built with FastAPI. Features JWT auth, Google \u0026 GitHub OAuth2, role-based access control, PostgreSQL, Dockerized deployment, Alembic migrations, and 95%+ test coverage. Designed for secure, scalable backend systems.","archived":false,"fork":false,"pushed_at":"2025-12-22T13:45:04.000Z","size":30,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-12-24T00:32:27.022Z","etag":null,"topics":["api-security","backend","docker","fastapi","jwt","microservice","oauth2","postgresql","pytest","python","sqlalchemy"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/samanshafagh.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"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-12-22T13:21:48.000Z","updated_at":"2025-12-22T13:53:31.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/samanshafagh/python-fastapi-auth-microservice","commit_stats":null,"previous_names":["samanshafagh/python-fastapi-auth-microservice"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/samanshafagh/python-fastapi-auth-microservice","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/samanshafagh%2Fpython-fastapi-auth-microservice","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/samanshafagh%2Fpython-fastapi-auth-microservice/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/samanshafagh%2Fpython-fastapi-auth-microservice/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/samanshafagh%2Fpython-fastapi-auth-microservice/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/samanshafagh","download_url":"https://codeload.github.com/samanshafagh/python-fastapi-auth-microservice/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/samanshafagh%2Fpython-fastapi-auth-microservice/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":27992996,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-12-24T02:00:07.193Z","response_time":83,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"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":["api-security","backend","docker","fastapi","jwt","microservice","oauth2","postgresql","pytest","python","sqlalchemy"],"created_at":"2025-12-24T02:00:53.338Z","updated_at":"2025-12-24T02:01:43.762Z","avatar_url":"https://github.com/samanshafagh.png","language":"Python","readme":"# FastAPI Authentication Microservice\n\n[![Python](https://img.shields.io/badge/Python-3.8+-blue.svg)](https://python.org)\n[![FastAPI](https://img.shields.io/badge/FastAPI-0.104+-green.svg)](https://fastapi.tiangolo.com)\n[![PostgreSQL](https://img.shields.io/badge/PostgreSQL-13+-blue.svg)](https://postgresql.org)\n[![License](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)\n\nA production-ready authentication microservice built with FastAPI, featuring JWT authentication, OAuth2 integration (Google \u0026 GitHub), user management, and comprehensive security features.\n\n## 🚀 Features\n\n- **🔐 JWT Authentication** - Secure token-based auth with access \u0026 refresh tokens\n- **🌐 OAuth2 Integration** - Google \u0026 GitHub OAuth providers\n- **👥 User Management** - Complete CRUD operations with role-based access\n- **🛡️ Security First** - bcrypt password hashing, CORS protection, input validation\n- **🐳 Docker Ready** - Containerized deployment with Docker Compose\n- **🧪 Well Tested** - Comprehensive test suite with 95%+ coverage\n- **📚 Auto Docs** - Interactive API documentation with Swagger UI\n\n## 🏗️ Architecture\n\nClean layered architecture following domain-driven design:\n\n```\n├── app/                    # Main application package\n│   ├── main.py            # FastAPI app \u0026 lifespan management\n│   ├── config.py          # Environment configuration\n│   ├── database.py        # SQLAlchemy setup\n│   ├── models/            # Database models\n│   ├── schemas/           # Pydantic models\n│   ├── routers/           # API endpoints\n│   ├── services/          # Business logic\n│   └── utils/             # Utilities (auth, validation)\n├── tests/                 # Test suite (19 tests, 95%+ coverage)\n├── alembic/               # Database migrations\n├── docker-compose.yml     # Docker services\n├── Dockerfile            # Container definition\n├── Makefile              # Development commands\n├── pytest.ini            # Test configuration\n├── requirements.txt      # Python dependencies\n└── README.md            # This file\n```\n\n## 🛠️ Tech Stack\n\n- **Framework**: [FastAPI](https://fastapi.tiangolo.com) - Modern async web framework\n- **Database**: [PostgreSQL](https://postgresql.org) with [SQLAlchemy](https://sqlalchemy.org) ORM\n- **Auth**: JWT tokens with [python-jose](https://github.com/mpdavis/python-jose)\n- **Security**: [bcrypt](https://github.com/pyca/bcrypt) via [passlib](https://passlib.readthedocs.io)\n- **OAuth2**: [Authlib](https://authlib.org) for Google \u0026 GitHub integration\n- **Validation**: [Pydantic](https://pydantic-docs.helpmanual.io) with custom validators\n- **Testing**: [pytest](https://pytest.org) with async support\n- **Containerization**: [Docker](https://docker.com) \u0026 [Docker Compose](https://docs.docker.com/compose)\n\n## 📋 Prerequisites\n\n- **Python**: 3.8 or higher\n- **Docker \u0026 Docker Compose**: For containerized deployment\n- **PostgreSQL**: 13+ (for local development)\n- **OAuth Credentials**: Google/GitHub (optional, for OAuth features)\n\n## 🚀 Quick Start\n\n### 🐳 Docker (Recommended)\n\n```bash\n# Clone repository\ngit clone https://github.com/samanshafagh/python-fastapi-auth-microservice.git\ncd fastapi-auth-microservice\n\n# Copy environment configuration\ncp env.example .env\n\n# Start services (app + PostgreSQL + PgAdmin)\ndocker-compose up -d\n\n# Access the application\n# API: http://localhost:8000\n# Docs: http://localhost:8000/docs\n# PgAdmin: http://localhost:5050\n```\n\n### 💻 Local Development\n\n```bash\n# Install dependencies\npip install -r requirements.txt\n\n# Set up PostgreSQL database\ncreatedb auth_db\ncreateuser auth_user\n\n# Configure environment\ncp env.example .env\n# Edit .env with your database credentials\n\n# Run migrations\nalembic upgrade head\n\n# Start development server\nuvicorn app.main:app --reload --host 127.0.0.1 --port 8000\n```\n\n## ⚙️ Configuration\n\nCreate a `.env` file from the provided template:\n\n```bash\ncp env.example .env\n```\n\n### Required Environment Variables\n\n| Variable | Description | Example |\n|----------|-------------|---------|\n| `DATABASE_URL` | PostgreSQL connection string | `postgresql://user:pass@localhost:5432/auth_db` |\n| `SECRET_KEY` | JWT signing secret (use strong random key) | `your-256-bit-secret-key-here` |\n\n### Optional Environment Variables\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `DEBUG` | Debug mode | `true` |\n| `ACCESS_TOKEN_EXPIRE_MINUTES` | JWT expiration time | `30` |\n| `REFRESH_TOKEN_EXPIRE_DAYS` | Refresh token validity | `7` |\n| `CORS_ORIGINS` | Allowed origins (comma-separated) | `http://localhost:3000,http://localhost:8000` |\n| `RATE_LIMIT_ENABLED` | Enable rate limiting | `true` |\n| `RATE_LIMIT_PER_MINUTE` | General rate limit | `60` |\n| `RATE_LIMIT_AUTH_PER_MINUTE` | Auth endpoint rate limit | `5` |\n\n### OAuth2 Configuration (Optional)\n\n```env\n# Google OAuth2\nGOOGLE_CLIENT_ID=your-google-client-id\nGOOGLE_CLIENT_SECRET=your-google-client-secret\n\n# GitHub OAuth2\nGITHUB_CLIENT_ID=your-github-client-id\nGITHUB_CLIENT_SECRET=your-github-client-secret\n```\n\n## 📖 API Documentation\n\nThe API is fully documented with interactive Swagger UI:\n\n- **📚 Swagger UI**: http://localhost:8000/docs\n- **📋 ReDoc**: http://localhost:8000/redoc\n- **🔍 OpenAPI Schema**: http://localhost:8000/openapi.json\n\n### 🔑 Core Endpoints\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| `POST` | `/api/v1/auth/register` | User registration |\n| `POST` | `/api/v1/auth/login` | User authentication |\n| `POST` | `/api/v1/auth/refresh` | Refresh access tokens |\n| `GET` | `/api/v1/auth/me` | Get current user profile |\n| `GET` | `/api/v1/auth/google/login` | Google OAuth login |\n| `GET` | `/api/v1/auth/github/login` | GitHub OAuth login |\n| `GET` | `/api/v1/users/` | List users (paginated) |\n| `GET` | `/api/v1/users/{id}` | Get user by ID |\n| `PUT` | `/api/v1/users/{id}` | Update user |\n| `DELETE` | `/api/v1/users/{id}` | Delete user |\n| `GET` | `/health` | Health check endpoint |\n\n## 🔐 Security Features\n\n- **JWT Tokens**: Secure token-based authentication\n- **Password Hashing**: bcrypt with salt for secure password storage\n- **Token Expiration**: Configurable access token expiration\n- **Refresh Tokens**: Secure token refresh mechanism\n- **CORS Protection**: Configurable Cross-Origin Resource Sharing\n- **Input Validation**: Comprehensive request validation with Pydantic\n- **Role-Based Access**: Superuser permissions for administrative operations\n\n## 🧪 Testing \u0026 Development\n\n### Run Tests\n\n```bash\n# Run all tests\nmake test\n\n# Run with coverage report\nmake test-cov\n\n# Run specific test file\npytest tests/test_auth.py -v\n```\n\n### Development Commands\n\n```bash\n# Install dependencies\nmake install\n\n# Start development server\nmake start\n\n# Run database migrations\nmake migrate\n\n# Create new migration\nmake migrate-create MESSAGE=\"add new feature\"\n\n# Format code\nmake format\n\n# Lint code\nmake lint\n\n# Clean up generated files\nmake clean\n```\n\n## 🗄️ Database Schema\n\nPostgreSQL database with the following tables:\n\n- **`users`** - User accounts with authentication and profile information\n- **`refresh_tokens`** - JWT refresh tokens for secure token management\n- **`alembic_version`** - Database migration tracking\n\n## 🐳 Docker Deployment\n\n### Production Setup\n\n1. Update `.env` with production values\n2. Set `DEBUG=false` for production\n3. Configure production database credentials\n4. Update CORS origins for your domain\n\n### Docker Commands\n\n```bash\n# Start all services\ndocker-compose up -d\n\n# View application logs\ndocker-compose logs -f app\n\n# Rebuild and restart\ndocker-compose up -d --build\n\n# Stop services\ndocker-compose down\n```\n\n## 🔄 Database Migrations\n\nUses [Alembic](https://alembic.sqlalchemy.org) for schema migrations:\n\n```bash\n# Apply all migrations\nalembic upgrade head\n\n# Create new migration\nalembic revision --autogenerate -m \"add new feature\"\n\n# Rollback last migration\nalembic downgrade -1\n\n# View migration history\nalembic history\n```\n\n\n## 🤝 Contributing\n\nWe welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.\n\n1. Fork the repository\n2. Create a feature branch (`git checkout -b feature/amazing-feature`)\n3. Make your changes with tests\n4. Ensure all tests pass (`make test`)\n5. Submit a Pull Request\n\n## 📄 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## 🆘 Support \u0026 Documentation\n\n- 📖 **API Documentation**: http://localhost:8000/docs\n- 🐛 **Bug Reports**: [GitHub Issues](https://github.com/samanshafagh/python-fastapi-auth-microservice/issues)\n- 💬 **Discussions**: [GitHub Discussions](https://github.com/samanshafagh/python-fastapi-auth-microservice/discussions)\n- 📧 **Contact**: Create an issue for support questions\n\n## 🙏 Acknowledgments\n\nBuilt with ❤️ using [FastAPI](https://fastapi.tiangolo.com), [SQLAlchemy](https://sqlalchemy.org), and other amazing open-source tools.\n\n## 🔮 Future Enhancements\n\n- [ ] Email verification for new accounts\n- [ ] Password reset functionality\n- [ ] Two-factor authentication (2FA)\n- [ ] Audit logging for security events\n- [ ] Additional OAuth providers (Facebook, Twitter, etc.)\n- [ ] GraphQL API support\n- [ ] WebSocket support for real-time features\n- [ ] Admin dashboard UI\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsamanshafagh%2Fpython-fastapi-auth-microservice","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsamanshafagh%2Fpython-fastapi-auth-microservice","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsamanshafagh%2Fpython-fastapi-auth-microservice/lists"}