Spaces:
Sleeping
Sleeping
fixe
Browse files- app.py +120 -0
- requirements.txt +7 -0
app.py
ADDED
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, Depends, HTTPException, status
|
2 |
+
from sqlalchemy.orm import Session
|
3 |
+
from sqlalchemy import create_engine, Column, Integer, String, Boolean, Enum
|
4 |
+
from sqlalchemy.ext.declarative import declarative_base
|
5 |
+
from sqlalchemy.orm import sessionmaker
|
6 |
+
from passlib.context import CryptContext
|
7 |
+
from jose import JWTError, jwt
|
8 |
+
import openai
|
9 |
+
from fastapi.middleware.cors import CORSMiddleware
|
10 |
+
|
11 |
+
# Configuration de la base de données MySQL
|
12 |
+
DATABASE_URL = "mysql+mysqlconnector://root:password@localhost/mobile_app"
|
13 |
+
engine = create_engine(DATABASE_URL)
|
14 |
+
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
15 |
+
Base = declarative_base()
|
16 |
+
app.add_middleware(
|
17 |
+
CORSMiddleware,
|
18 |
+
allow_origins=["*"],
|
19 |
+
allow_credentials=True,
|
20 |
+
allow_methods=["*"],
|
21 |
+
allow_headers=["*"],
|
22 |
+
)
|
23 |
+
|
24 |
+
# Configuration JWT et hachage de mot de passe
|
25 |
+
SECRET_KEY = "your_secret_key"
|
26 |
+
ALGORITHM = "HS256"
|
27 |
+
ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
28 |
+
|
29 |
+
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
30 |
+
|
31 |
+
# Modèle pour les utilisateurs
|
32 |
+
class User(Base):
|
33 |
+
__tablename__ = "users"
|
34 |
+
id = Column(Integer, primary_key=True, index=True)
|
35 |
+
name = Column(String(255), unique=True, index=True)
|
36 |
+
passcode = Column(String(255))
|
37 |
+
accept_terms = Column(Boolean)
|
38 |
+
sex = Column(Enum('male', 'female'))
|
39 |
+
age = Column(Integer)
|
40 |
+
|
41 |
+
Base.metadata.create_all(bind=engine)
|
42 |
+
|
43 |
+
app = FastAPI()
|
44 |
+
|
45 |
+
# Créer une session pour la base de données
|
46 |
+
def get_db():
|
47 |
+
db = SessionLocal()
|
48 |
+
try:
|
49 |
+
yield db
|
50 |
+
finally:
|
51 |
+
db.close()
|
52 |
+
|
53 |
+
# Fonction pour vérifier le mot de passe haché
|
54 |
+
def verify_password(plain_password, hashed_password):
|
55 |
+
return pwd_context.verify(plain_password, hashed_password)
|
56 |
+
|
57 |
+
# Fonction pour hacher le mot de passe
|
58 |
+
def get_password_hash(password):
|
59 |
+
return pwd_context.hash(password)
|
60 |
+
|
61 |
+
# Fonction pour créer un JWT token
|
62 |
+
def create_access_token(data: dict):
|
63 |
+
to_encode = data.copy()
|
64 |
+
token = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
65 |
+
return token
|
66 |
+
|
67 |
+
# Schéma de données pour la création d'utilisateurs
|
68 |
+
from pydantic import BaseModel
|
69 |
+
class UserCreate(BaseModel):
|
70 |
+
name: str
|
71 |
+
passcode: str
|
72 |
+
accept_terms: bool
|
73 |
+
sex: str
|
74 |
+
age: int
|
75 |
+
|
76 |
+
# Schéma de données pour l'authentification
|
77 |
+
class Token(BaseModel):
|
78 |
+
access_token: str
|
79 |
+
token_type: str
|
80 |
+
|
81 |
+
class UserLogin(BaseModel):
|
82 |
+
name: str
|
83 |
+
passcode: str
|
84 |
+
|
85 |
+
# Inscription d'un utilisateur
|
86 |
+
@app.post("/register/")
|
87 |
+
def register(user: UserCreate, db: Session = Depends(get_db)):
|
88 |
+
hashed_password = get_password_hash(user.passcode)
|
89 |
+
db_user = User(name=user.name, passcode=hashed_password, accept_terms=user.accept_terms, sex=user.sex, age=user.age)
|
90 |
+
db.add(db_user)
|
91 |
+
db.commit()
|
92 |
+
db.refresh(db_user)
|
93 |
+
return {"message": "User registered successfully"}
|
94 |
+
|
95 |
+
# Connexion d'un utilisateur
|
96 |
+
@app.post("/login/", response_model=Token)
|
97 |
+
def login(user: UserLogin, db: Session = Depends(get_db)):
|
98 |
+
db_user = db.query(User).filter(User.name == user.name).first()
|
99 |
+
if not db_user:
|
100 |
+
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
|
101 |
+
if not verify_password(user.passcode, db_user.passcode):
|
102 |
+
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
|
103 |
+
|
104 |
+
access_token = create_access_token(data={"sub": db_user.name})
|
105 |
+
return {"access_token": access_token, "token_type": "bearer"}
|
106 |
+
|
107 |
+
# API protégée utilisant OpenAI après connexion
|
108 |
+
@app.post("/use_openai/")
|
109 |
+
def use_openai(db: Session = Depends(get_db), token: str = Depends(create_access_token)):
|
110 |
+
# Appel à l'API OpenAI en utilisant la clé d'accès
|
111 |
+
openai.api_key = "YOUR_OPENAI_API_KEY"
|
112 |
+
|
113 |
+
# Exemple de requête OpenAI
|
114 |
+
response = openai.Completion.create(
|
115 |
+
engine="text-davinci-003",
|
116 |
+
prompt="Hello, how are you?",
|
117 |
+
max_tokens=50
|
118 |
+
)
|
119 |
+
|
120 |
+
return {"openai_response": response["choices"][0]["text"].strip()}
|
requirements.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
fastapi
|
2 |
+
uvicorn[standard]
|
3 |
+
sqlalchemy
|
4 |
+
mysql-connector-python
|
5 |
+
passlib[bcrypt]
|
6 |
+
python-jose
|
7 |
+
openai
|