get current user(using email) completed

This commit is contained in:
DmitryGantimurov 2023-08-02 00:39:46 +03:00
parent 0145ed8f44
commit 26e42d874e
4 changed files with 34 additions and 42 deletions

View File

@ -7,7 +7,7 @@ from fastapi.templating import Jinja2Templates
from fastapi.requests import Request
from pydantic import json
from typing import Any
from typing import Any, Annotated
from starlette.staticfiles import StaticFiles
import requests
@ -18,10 +18,9 @@ import pathlib
import shutil
import os
from .utils import *
from .db import Base, engine, SessionLocal, database
from .service import add_poems_to_db, generate_poem
from . import schemas, models
from . import schemas, models, utils
Base.metadata.create_all(bind=engine)
@ -154,34 +153,30 @@ def create_user(data = Body()):
async def login_for_access_token(
form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
):
user = authenticate_user(database, form_data.username, form_data.password)
user = utils.authenticate_user(database, form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
access_token_expires = utils.timedelta(minutes=utils.ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = utils.create_access_token(
data={"user_id": user.id}, expires_delta=access_token_expires
)
return {"access_token":access_token}
# @app.get("/api/users/me/", response_model=schemas.User) #
# async def read_users_me(current_user: Annotated[schemas.User, Depends(get_current_active_user)]):
# return current_user #schemas.User(id=current_user.id, email=current_user.email, name=current_user.name, surname=current_user.surname, disabled=current_user.disabled, items=current_user.items)
@app.get("/api/users/me/", response_model=schemas.User) #
async def read_users_me(current_user: Annotated[schemas.User, Depends(get_current_active_user)]) -> Any:
return current_user #schemas.User(id=current_user.id, email=current_user.email, name=current_user.name, surname=current_user.surname, disabled=current_user.disabled, items=current_user.items)
async def read_users_me(current_user: Annotated[schemas.User, Depends(utils.get_current_active_user)]):
return current_user
# @app.get("/api/users/me/items/")
# async def read_own_items(
# current_user: Annotated[schemas.User, Depends(get_current_active_user)]
# ):
# return [{"Current user name": current_user.name, "Current user surname": current_user.surname}]
@app.get("/api/users/me/items/")
async def read_own_items(
current_user: Annotated[schemas.User, Depends(utils.get_current_active_user)]
):
return [{"Current user name": current_user.name, "Current user surname": current_user.surname}]
@app.get("/api/trashbox")

View File

@ -32,7 +32,7 @@ class Token(BaseModel):
class TokenData(BaseModel):
email: Union[str, None] = None
user_id: Union[int, None] = None
class User(BaseModel):

View File

@ -33,7 +33,7 @@ def generate_poem(db: Session):
rand_id = random.randint(1, 102)
poem = db.query(Poems).filter(Poems.id == rand_id).first()
# возвращаем название и текст стихотворения
return {"poem_name": poem.poem_name, "poem_text": poem.poem_text}
return {"name": poem.poem_name, "text": poem.poem_text, "author":""} # добавить поле author в Poems
# Функция, создающая сессию БД при каждом запросе к нашему API.

View File

@ -9,17 +9,24 @@ from passlib.context import CryptContext
from sqlalchemy.orm import Session
from sqlalchemy import select
# from .db import Session, database
from .db import Session, database
from . import models, schemas
SECRET_KEY = "SECRET"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/token")
def get_db():
db = database
try:
yield db
finally:
db.close()
def verify_password(plain_password, hashed_password):
@ -30,15 +37,15 @@ def get_password_hash(password):
return pwd_context.hash(password)
def get_user(db: Session, email: str):
user_with_required_email = db.query(models.User).filter(models.User.email == email).first()
if user_with_required_email:
return user_with_required_email
def get_user(db: Session, user_id: int):
user_with_required_id = db.query(models.User).filter(models.User.id == user_id).first()
if user_with_required_id:
return user_with_required_id
return None
def authenticate_user(db: Session, email: str, password: str):
user = get_user(db, email)
user = get_user(db, user_id)
if not user:
return False
if not verify_password(password, user.hashed_password):
@ -57,7 +64,7 @@ def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None
return encoded_jwt
async def get_current_user(db: Session, token: Annotated[str, Depends(oauth2_scheme)]):
async def get_current_user(db: Annotated[Session, Depends(get_db)], token: Annotated[str, Depends(oauth2_scheme)]):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
@ -65,13 +72,13 @@ async def get_current_user(db: Session, token: Annotated[str, Depends(oauth2_sch
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
email: str = payload.get("sub")
if email is None:
user_id: int = payload.get("user_id")
if user_id is None:
raise credentials_exception
token_data = schemas.TokenData(email=email)
token_data = schemas.TokenData(user_id=user_id)
except JWTError:
raise credentials_exception
user = get_user(db, email=token_data.email)
user = get_user(db, user_id=token_data.user_id)
if user is None:
raise credentials_exception
return schemas.User(id=user.id, email=user.email, name=user.name, surname=user.surname, disabled=user.disabled, items=user.items)
@ -85,13 +92,3 @@ async def get_current_active_user(
raise HTTPException(status_code=400, detail="Inactive user")
return current_user
# def get_db(request: Request):
# return request.state.db
# def get_db():
# db = SessionLocal()
# try:
# yield db
# finally:
# db.close()