A comprehensive boilerplate designed to empower developers to rapidly build secure and scalable FastAPI applications with fine-grained access control. This project leverages JSON Web Tokens (JWT) for authentication and a PostgreSQL database to implement a robust Role-Based Access Control (RBAC) system.
- JWT-based Authentication: Securely authenticate users using JSON Web Tokens (JWT), providing a stateless and scalable authentication mechanism.
- Bcrypt Password Hashing: Employ industry-standard bcrypt for strong password hashing, safeguarding user credentials.
- Token Expiration and Refresh: Manage token lifetimes with configurable expiration times and a built-in refresh mechanism for enhanced user experience.
- Role Management: Create and manage roles to define user groups within your application (e.g., admin, moderator, user).
- Permission Management: Define granular permissions for each role, granting or restricting access to specific API endpoints and actions (e.g., create_user, read_article, update_product).
- Flexible Role-Permission Relationships: Establish a many-to-many relationship between roles and permissions, enabling complex access control scenarios.
- Endpoint-Level Authorization: Easily enforce access control on FastAPI endpoints using the provided
role_required
andpermission_required
dependencies.
- Simplified Setup: Streamline database initialization, schema creation, and population of default roles and permissions with the
manage_db.py
script. - TODO: Future-Proof Migrations: Utilize Alembic for managing database schema changes as your application evolves.
- Data Security: Safeguard your data with built-in backup and restore functionalities.
- User Management: Comprehensive API endpoints for creating, retrieving, updating, and deleting user accounts.
- Role & Permission Management: Full control over roles and permissions via intuitive API endpoints.
- Pydantic Models: Ensure data integrity and validation with Pydantic models for user, role, and permission schemas.
- Example Flask Application: Included as a starting point, demonstrates how to interact with the API to manage users.
- Easily Extendable: Customize and expand the frontend to build a full-featured user management interface or integrate with your existing frontend framework.
- Logging: Detailed logging of authentication events (login attempts, user creation, etc.) for debugging and security auditing.
- Customizable: Easily tailor the boilerplate to fit the specific requirements of your project.
- Open Source: Freely use, modify, and distribute under the MIT License.
- FastAPI: The high-performance web framework for building the backend API.
- PostgreSQL: The robust and scalable relational database for storing user data, roles, and permissions.
- SQLAlchemy: The Object-Relational Mapper (ORM) that simplifies database interactions.
- PyJWT: The library responsible for JWT token generation, validation, and decoding.
- Passlib: The library providing bcrypt password hashing.
- Pydantic: The data validation and serialization library.
- Flask (optional): A lightweight web framework for creating the example frontend.
Installation, Configuration, Database Management, Running the Application, API Documentation, Contributing
-
Clone the repository:
git clone REPO_URL cd REPO_NAME
-
Install dependencies:
pip install -r requirements.txt
-
Set up your
.env
file with the necessary environment variables:SECRET_KEY=your_secret_key DATABASE_URL=postgresql://username:password@localhost:5432/db
Replace
your_secret_key
with a strong secret key. Update the database URL with your actual credentials and database name. -
Configure PostgreSQL: Refer to the
manage_db.py
script for detailed instructions:python manage_db.py -h
- Start the FastAPI application:
Your application should now be running on http://127.0.0.1:8000.
uvicorn app.main:app --reload
FastAPI automatically generates interactive API documentation. You can access it at:
Use the manage_db.py
script for database-related operations. Here are some common commands:
- Create the PostgreSQL user:
python manage_db.py --create-pg-user
- Drop the PostgreSQL user:
python manage_db.py --drop-pg-user
- Create the database:
python manage_db.py --create-db
- Drop the database:
python manage_db.py --drop-db
- Create database tables:
python manage_db.py --create-tables
- Reset the database (drop and create tables):
python manage_db.py --reset-db
For a complete list of available commands, run:
python manage_db.py -h
- Secret Key Management: Rotate your
SECRET_KEY
regularly and store it securely (e.g., using environment variables or a secrets manager). - HTTPS: Deploy your application over HTTPS to encrypt traffic and prevent the interception of JWT tokens.
- Rate Limiting: Mitigate brute-force attacks by implementing rate limiting on authentication endpoints.
- Input Validation: Rigorously validate all user input to protect against common security vulnerabilities like SQL injection and cross-site scripting (XSS).
- Least Privilege: Adhere to the principle of least privilege by granting users only the permissions necessary for their roles.
Contributions are welcome! Please follow these steps:
- Fork the repository.
- Create a new feature branch (
git checkout -b feature/your-feature
). - Commit your changes (
git commit -m 'Add some feature'
). - Push to the branch (
git push origin feature/your-feature
). - Create a new pull request.
This project is licensed under the License – see the LICENSE.md file for details.