-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain_basic_auth_etape0.py
More file actions
41 lines (35 loc) · 1.28 KB
/
main_basic_auth_etape0.py
File metadata and controls
41 lines (35 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
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
from fastapi import FastAPI, Depends
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from sqlalchemy.orm import Session
from contextlib import asynccontextmanager
from db import get_db
from init_db1 import init_db
from models import User
# Lifespan handler (remplace on_event)
@asynccontextmanager
async def lifespan(app: FastAPI):
init_db()
print("DB initialisée")
yield
print("App arrêtée")
app = FastAPI(lifespan=lifespan)
security = HTTPBasic()
def basic_auth_noop(credentials: HTTPBasicCredentials = Depends(security)):
"""
Utilise security pour déclencher l'apparition d'une popup d'authentification
:param credentials: contient le username et le password
:return: Données d'authentification
"""
return {"username": credentials.username, "password": credentials.password}
@app.get("/users")
def users(db: Session = Depends(get_db)):
return db.query(User).all()
@app.get("/protected/users")
def protected(db: Session = Depends(get_db), _user=Depends(basic_auth_noop)):
"""
Fournit la liste des utilisateurs mais le user/mot de passe de l'utilisateur ne sont pas vérifiées
:param db: accès base de données
:param _user: le user est fourni par la fonction basic_auth_noop
:return:
"""
return db.query(User).all()