Spaces:
Runtime error
Runtime error
BuildTools
commited on
Commit
·
1c05df2
1
Parent(s):
80f0f4d
nouveau Back
Browse files- __pycache__/main.cpython-312.pyc +0 -0
- main.py +88 -54
- requirements.txt +2 -3
__pycache__/main.cpython-312.pyc
CHANGED
|
Binary files a/__pycache__/main.cpython-312.pyc and b/__pycache__/main.cpython-312.pyc differ
|
|
|
main.py
CHANGED
|
@@ -1,58 +1,92 @@
|
|
| 1 |
-
|
| 2 |
-
from fastapi import
|
| 3 |
-
from fastapi.responses import HTMLResponse, RedirectResponse
|
| 4 |
-
from fastapi.staticfiles import StaticFiles
|
| 5 |
-
from fastapi.templating import Jinja2Templates
|
| 6 |
from pymongo import MongoClient
|
| 7 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
app = FastAPI()
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
})
|
| 46 |
if not user:
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Depends, HTTPException, status
|
| 2 |
+
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
|
|
|
|
|
|
|
|
|
|
| 3 |
from pymongo import MongoClient
|
| 4 |
+
from pymongo.errors import DuplicateKeyError
|
| 5 |
+
from bson import ObjectId
|
| 6 |
+
from datetime import datetime, timedelta
|
| 7 |
+
import jwt
|
| 8 |
+
from passlib.context import CryptContext
|
| 9 |
|
| 10 |
app = FastAPI()
|
| 11 |
+
|
| 12 |
+
# Configuration de la base de données MongoDB
|
| 13 |
+
client = MongoClient("mongodb://localhost:27017/")
|
| 14 |
+
db = client["user_db"]
|
| 15 |
+
users_collection = db["users"]
|
| 16 |
+
|
| 17 |
+
# Configuration de la sécurité
|
| 18 |
+
SECRET_KEY = "your_secret_key"
|
| 19 |
+
ALGORITHM = "HS256"
|
| 20 |
+
ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
| 21 |
+
|
| 22 |
+
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
| 23 |
+
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
|
| 24 |
+
|
| 25 |
+
# Fonction pour vérifier le mot de passe
|
| 26 |
+
def verify_password(plain_password, hashed_password):
|
| 27 |
+
return pwd_context.verify(plain_password, hashed_password)
|
| 28 |
+
|
| 29 |
+
# Fonction pour hasher le mot de passe
|
| 30 |
+
def get_password_hash(password):
|
| 31 |
+
return pwd_context.hash(password)
|
| 32 |
+
|
| 33 |
+
# Fonction pour créer un token JWT
|
| 34 |
+
def create_access_token(data: dict, expires_delta: timedelta = None):
|
| 35 |
+
to_encode = data.copy()
|
| 36 |
+
if expires_delta:
|
| 37 |
+
expire = datetime.utcnow() + expires_delta
|
| 38 |
+
else:
|
| 39 |
+
expire = datetime.utcnow() + timedelta(minutes=15)
|
| 40 |
+
to_encode.update({"exp": expire})
|
| 41 |
+
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
| 42 |
+
return encoded_jwt
|
| 43 |
+
|
| 44 |
+
# Fonction pour authentifier un utilisateur
|
| 45 |
+
def authenticate_user(email: str, password: str):
|
| 46 |
+
user = users_collection.find_one({"email": email})
|
| 47 |
if not user:
|
| 48 |
+
return False
|
| 49 |
+
if not verify_password(password, user["hashed_password"]):
|
| 50 |
+
return False
|
| 51 |
+
return user
|
| 52 |
+
|
| 53 |
+
# Route pour s'inscrire
|
| 54 |
+
@app.post("/register")
|
| 55 |
+
async def register(email: str, password: str):
|
| 56 |
+
hashed_password = get_password_hash(password)
|
| 57 |
+
try:
|
| 58 |
+
users_collection.insert_one({"email": email, "hashed_password": hashed_password})
|
| 59 |
+
return {"message": "User created successfully"}
|
| 60 |
+
except DuplicateKeyError:
|
| 61 |
+
raise HTTPException(status_code=400, detail="Email already registered")
|
| 62 |
+
|
| 63 |
+
# Route pour se connecter
|
| 64 |
+
@app.post("/token")
|
| 65 |
+
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
|
| 66 |
+
user = authenticate_user(form_data.username, form_data.password)
|
| 67 |
+
if not user:
|
| 68 |
+
raise HTTPException(
|
| 69 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 70 |
+
detail="Incorrect email or password",
|
| 71 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 72 |
+
)
|
| 73 |
+
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
| 74 |
+
access_token = create_access_token(
|
| 75 |
+
data={"sub": user["email"]}, expires_delta=access_token_expires
|
| 76 |
+
)
|
| 77 |
+
return {"access_token": access_token, "token_type": "bearer"}
|
| 78 |
+
|
| 79 |
+
# Route protégée
|
| 80 |
+
@app.get("/protected")
|
| 81 |
+
async def protected_route(token: str = Depends(oauth2_scheme)):
|
| 82 |
+
try:
|
| 83 |
+
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
| 84 |
+
email = payload.get("sub")
|
| 85 |
+
if email is None:
|
| 86 |
+
raise HTTPException(status_code=400, detail="Invalid token")
|
| 87 |
+
user = users_collection.find_one({"email": email})
|
| 88 |
+
if user is None:
|
| 89 |
+
raise HTTPException(status_code=404, detail="User not found")
|
| 90 |
+
return {"message": "You are authenticated", "user": email}
|
| 91 |
+
except jwt.PyJWTError:
|
| 92 |
+
raise HTTPException(status_code=401, detail="Invalid token")
|
requirements.txt
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
fastapi
|
| 2 |
-
uvicorn
|
| 3 |
-
pymongo
|
| 4 |
-
python-multipart
|
|
|
|
| 1 |
fastapi
|
| 2 |
+
uvicorn
|
| 3 |
+
pymongo
|
|
|