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

View File

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

View File

@ -33,7 +33,7 @@ def generate_poem(db: Session):
rand_id = random.randint(1, 102) rand_id = random.randint(1, 102)
poem = db.query(Poems).filter(Poems.id == rand_id).first() 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. # Функция, создающая сессию БД при каждом запросе к нашему API.

View File

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