Skip to content

Commit eb9cff2

Browse files
authored
Update README.md
1 parent e9ad3c9 commit eb9cff2

File tree

1 file changed

+113
-29
lines changed

1 file changed

+113
-29
lines changed

README.md

Lines changed: 113 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,31 @@
11
# FastAPI User Authentication
2-
<p><em>Python and FastAPI for User Authentication module focuses on security and standard.</em></p>
2+
<p><em><strong>Python and FastAPI for User Authentication, focuses on security, performance, and standard.</strong></em></p>
33

4-
An open-source user authentication module for applications built with Python and FastAPI, designed to handle user registration, email verification, authentication, reset password, device detection, rate limiting, account lockout, IP blacklisting, and refresh token rotation.
4+
An open-source Python and FastAPI project for user authentication, designed to handle user authentication system with role-based access control (RBAC), scheduled jobs, device and IP address detection, rate limiting, account lockout, IP blacklisting, refresh token rotation, uses Alembic for database migrations to ensure smooth schema updates and more. It leverages Async SQLAlchemy for asynchronous database operations, allowing for improved performance and scalability in handling multiple concurrent requests.
55

66
## Features
7-
- **User Registration**: Allows new users to create an account and verify with 6-digit code via email verification.
8-
- **User Authentication**: Enables users to log in securely using their credentials.
9-
- **Password Reset**: Facilitates password recovery and verify with 6-digit code via email verification.
10-
- **Device Limitation**: Allows users to log in on up to 5 devices per account, removing the oldest device upon exceeding the limit.
11-
- **Rate Limiting**: Restricts repeated requests within a defined period to prevent abuse.
12-
- **Account Lockout**: Temporarily locks user accounts after multiple failed login attempts.
13-
- **IP Blacklisting**: Blocks requests from specific IPs to enhance security.
14-
- **Refresh Token Rotation**: Provides secure, rotating access and refresh tokens for session management.
7+
1. **User Registration**: Allows new users to create an account and verify with 6-digit code via email verification.
8+
2. **User Authentication**: Enables users to log in securely using their credentials.
9+
3. **Password Reset**: Facilitates password recovery and verify with 6-digit code via email verification.
10+
4. **Device Limitation**: Allows users to log in on up to specific number of devices per account (e.g., 5 devices log in on 1 account), removing the oldest device upon exceeding the limit.
11+
5. **Refresh Token Rotation**: Provides secure, rotating access and refresh tokens for session management.
12+
6. **Role Base Acess Control (RBAC)**: Permissions and access levels within the application
13+
7. **Rate Limiting**: Restricts repeated requests within a defined period to prevent abuse.
14+
8. **Account Lockout**: Temporarily locks user accounts after multiple failed login attempts.
15+
9. **IP Blacklisting**: Blocks requests from specific IPs to enhance security.
16+
10. **Periodic Cleanup**: Schedule background jobs for tasks like cleanup. This keeps the database clean and prevents it from growing uncontrollably.
17+
11. **Temporary Storage**: Store registration data in a temporary location (e.g., a separate database table) until the user verifies their email. Once verified, move the data to the main user table. This keeps the primary user table free from unverified accounts.
18+
12. **Async SQLAlchemy**: for asynchronous database operations, allowing for improved performance and scalability in handling multiple concurrent requests.
1519

1620
## Table of Contents
1721
1. [Installation](#installation)
1822
- [Redis Setup](#redis-setup)
1923
2. [Configuration](#configuration)
24+
- [Roles Setup](#role-setup)
25+
- [Periodic Cleanup Setup](#periodic-cleanup-setup)
26+
- [Environment Variables](#environment-variables)
2027
3. [Usage](#usage)
28+
- [Alembic](#alembic)
2129
- [Postman Collection](#postman-collection)
2230
- [Check Rate Limit and Account Lockout](#check-rate-limit-and-account-lockout)
2331
4. [Project Structure](#project-structure)
@@ -76,8 +84,65 @@ To install Redis, follow the instructions for your operating system:
7684
```
7785

7886
## Configuration
79-
You can configure database, email, rate limits, lockout settings, token secret, and other settings via environment variables or by modifying the `.env` file format.
8087

88+
### Role Setup
89+
#### Initialize Roles
90+
In app/config/role.py
91+
```python
92+
def initialize_roles(session: Session):
93+
print("Generating role")
94+
roles = ["normal_user", "education_user", "business_user", "admin"]
95+
for role_name in roles:
96+
role = session.query(Role).filter_by(role_name=role_name).first()
97+
98+
if not role:
99+
new_role = Role(role_name=role_name)
100+
session.add(new_role)
101+
102+
session.commit()
103+
```
104+
#### Routes Dependencies
105+
In app/routes/user.py
106+
```python
107+
auth_router = APIRouter(
108+
prefix="/users",
109+
tags=["Users"],
110+
responses={404: {"description": "Not found"}},
111+
dependencies=[Depends(oauth2_scheme), Depends(get_current_user)]
112+
)
113+
114+
business_router = APIRouter(
115+
prefix="/business",
116+
tags=["Business"],
117+
responses={404: {"description": "Not found"}},
118+
dependencies=[Depends(oauth2_scheme), Depends(get_role_dependency(required_role="business_user"))]
119+
)
120+
121+
admin_router = APIRouter(
122+
prefix="/admin",
123+
tags=["Admin"],
124+
responses={404: {"description": "Not found"}},
125+
dependencies=[Depends(oauth2_scheme), Depends(get_role_dependency(required_role="admin"))]
126+
)
127+
```
128+
129+
### Periodic Cleanup Setup
130+
**Start the background jobs scheduler**
131+
132+
In app/main.py
133+
```python
134+
from app.jobs.scheduler import start_scheduler, shutdown_scheduler
135+
136+
start_scheduler()
137+
138+
@app.on_event("shutdown")
139+
def shutdown_event():
140+
shutdown_scheduler()
141+
```
142+
143+
### Environment Variables
144+
You can configure database, email, rate limits, lockout settings, token secret, and other settings via environment variables or by modifying the `.env` file format.
145+
#### App Environment Variables
81146
**Sample `.env` File**:
82147
```ini
83148
APP_NAME=APP_NAME
@@ -90,20 +155,7 @@ ACCESS_TOKEN_EXPIRE_MINUTES=3
90155
REFRESH_TOKEN_EXPIRE_MINUTES=25920 #18 days = 25920 minutes
91156
```
92157
93-
**Sample `.env.mail` File**:
94-
```ini
95-
96-
MAIL_PASSWORD=REPLACE_THIS_WITH_YOUR_EMAIL_PASSWORD
97-
MAIL_PORT=EMAIL_PORT
98-
MAIL_SERVER=YOUR_EMAIL_SERVER
99-
MAIL_STARTTLS=True
100-
MAIL_SSL_TLS=False
101-
MAIL_DEBUG=True
102-
103-
MAIL_FROM_NAME=APP_NAME
104-
USE_CREDENTIALS=True
105-
```
106-
158+
#### Secret Environment Variables
107159
**Sample `.env.settings` File**:
108160
```ini
109161
DATABASE_HOSTNAME=localhost
@@ -119,8 +171,24 @@ JWT_SECRET=355fa9f6f9c491417c53b701b26dd97df5825d4abd02957ce3bb1b9658593d9a
119171
SECRET_KEY=9a35f82513e1cdf2748afbd4681ff2eda8fc29a46df52cc8c4cdd561c0632400
120172
```
121173
174+
#### Mail Environment Variables
175+
**Sample `.env.mail` File**:
176+
```ini
177+
178+
MAIL_PASSWORD=REPLACE_THIS_WITH_YOUR_EMAIL_PASSWORD
179+
MAIL_PORT=EMAIL_PORT
180+
MAIL_SERVER=YOUR_EMAIL_SERVER
181+
MAIL_STARTTLS=True
182+
MAIL_SSL_TLS=False
183+
MAIL_DEBUG=True
184+
185+
MAIL_FROM_NAME=APP_NAME
186+
USE_CREDENTIALS=True
187+
```
188+
189+
#### Rate Limiting Environment Variables
122190
**Sample `.env.ratelimiting` File**:
123-
By using the value below, rate limit will apply after the operation reach
191+
By using the value below, the cooldown will apply after the operation exceed the limit
124192
- Device: 4 requests in 30 seconds will cooldown for 5 minutes
125193
- IP Address: 10 requests in 30 seconds will cooldown for 10 minutes
126194
```ini
@@ -131,8 +199,9 @@ OPERATION_IP_RATE_LIMIT=10
131199
OPERATION_IP_COOLDOWN=600
132200
```
133201
202+
#### Lockout Environment Variables
134203
**Sample `.env.lockout` File**:
135-
By using the value below, lockout will apply after the operation reach
204+
By using the value below, lockout will apply after the operation exceed the limit
136205
- Device: 5 failed in 3 minutes will lockout for 30 minutes
137206
- IP Address: 15 failed in 3 minutes will lockout for 3 hours
138207
```ini
@@ -144,6 +213,13 @@ OPERATION_IP_LOCKOUT_PERIOD=10800
144213
```
145214
146215
## Usage
216+
217+
### Alembic
218+
To manage database schema changes, this project utilizes Alembic. Ensure you have Alembic installed and configured. You can run migrations with the following command:
219+
```bash
220+
alembic revision --autogenerate -m "Your message here"
221+
alembic upgrade head
222+
```
147223
This module can be tested and used via Postman. Below is example of how to interact with the user authentication API using Postman.
148224
149225
### Register a User
@@ -190,7 +266,7 @@ fastapi-user-authentication/
190266
├── .github/ # GitHub templates and settings
191267
├── alembic/ # Database migrations
192268
├── app/ # Main application code
193-
│ ├── config/ # Configuration files (database, email, security)
269+
│ ├── config/ # Configuration files (database, email, roles, security)
194270
│ ├── jobs/ # Background tasks and schedulers
195271
│ ├── models/ # Database models
196272
│ ├── responses/ # API response schemas
@@ -235,4 +311,12 @@ Contributions are welcome! If you’d like to contribute, please follow these gu
235311
Please review the `CODE_OF_CONDUCT.md` file for community guidelines and best practices when contributing.
236312
237313
## License
238-
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
314+
`VannySothea/fastapi-user-authentication` is open source and free to use based on `MIT License` and can be used for commercial purposes for free, but please clearly display the copyright information about VannySothea/fastapi-user-authentication in the display interface.
315+
- This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
316+
317+
## Thanks
318+
Thanks to the following developers for their contributions to fastapi-user-authentication:
319+
320+
<a href="https://github.com/VannySothea/fastapi-user-authentication/graphs/contributors">
321+
<img src="https://contrib.rocks/image?repo=VannySothea/fastapi-user-authentication" alt="Project Contributor"/>
322+
</a>

0 commit comments

Comments
 (0)