Auth. was fixed. Problem is in getting curr. user

This commit is contained in:
DmitryGantimurov 2023-07-26 00:56:22 +03:00 committed by Dmitry Gantimurov
parent 904b00059f
commit dd719a20ec
4 changed files with 62 additions and 40 deletions

View File

@ -39,15 +39,15 @@ app.mount("/uploads", StaticFiles(directory = "./uploads"))
# Функция, создающая сессию БД при каждом запросе к нашему API. # Функция, создающая сессию БД при каждом запросе к нашему API.
# Срабатывает до запуска остальных функций. # Срабатывает до запуска остальных функций.
# Всегда закрывает сессию при окончании работы с ней # Всегда закрывает сессию при окончании работы с ней
@app.middleware("http") # @app.middleware("http")
async def db_session_middleware(request: Request, call_next): # async def db_session_middleware(request: Request, call_next):
response = Response("Internal server error", status_code=500) # response = Response("Internal server error", status_code=500)
try: # try:
request.state.db = SessionLocal() # request.state.db = SessionLocal()
response = await call_next(request) # response = await call_next(request)
finally: # finally:
request.state.db.close() # request.state.db.close()
return response # return response
@app.get("/api/announcements")#адрес объявлений @app.get("/api/announcements")#адрес объявлений
@ -150,10 +150,12 @@ def change_book_status(data: schema.Book):
return {"Success": False} return {"Success": False}
# reginstration # reginstration
# {"id":1, "email":"poopka@mail.ru", "password":"good", "name":"Vasya", "surname":"Poopkin"}
@app.post("/api/signup") @app.post("/api/signup")
def create_user(data = Body()): def create_user(data = Body()):
if database.query(UserDatabase).filter(UserDatabase.email == data["email"]).first() == None: if database.query(UserDatabase).filter(UserDatabase.email == data["email"]).first() == None:
new_user = UserDatabase(id=data["id"], email=data["email"], password=data["password"], name=data["name"], surname=data["surname"]) new_user = UserDatabase(id=data["id"], email=data["email"], password=data["password"],
hashed_password=get_password_hash(data["password"]), name=data["name"], surname=data["surname"])
database.add(new_user) database.add(new_user)
database.commit() database.commit()
database.refresh(new_user) # обновляем состояние объекта database.refresh(new_user) # обновляем состояние объекта
@ -177,21 +179,21 @@ async def login_for_access_token(
access_token = create_access_token( access_token = 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 return {"access_token":access_token}
@app.get("/api/users/me/", response_model=schema.User) # @app.get("/api/users/me/", response_model=schema.User)
async def read_users_me( #!!!!!!!!!!! # async def read_users_me( #!!!!!!!!!!!
current_user: Annotated[User, Depends(get_current_active_user)] # current_user: Annotated[schema.User, Depends(get_current_active_user)]
): # ):
return current_user # return {"data": 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[User, Depends(get_current_active_user)] # current_user: Annotated[schema.User, Depends(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}]

View File

@ -1,11 +1,11 @@
from sqlalchemy import Column, Integer, String from sqlalchemy import Column, Integer, String
from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase
from fastapi import Depends from fastapi import Depends
from .db import Base from .db import Base, engine
class User(SQLAlchemyBaseUserTableUUID, Base): # class User(SQLAlchemyBaseUserTableUUID, Base):
pass # name = Column(String, nullable=True)#имя пользователя

View File

@ -1,3 +1,20 @@
# import uuid
# from fastapi_users import schemas
# class UserRead(schema.BaseUser[uuid.UUID]):
# pass
# class UserCreate(schema.BaseUserCreate):
# pass
# class UserUpdate(schema.BaseUserUpdate):
# pass
from pydantic import BaseModel from pydantic import BaseModel
from typing import Annotated, Union from typing import Annotated, Union
@ -7,7 +24,7 @@ class Book(BaseModel):
class Token(BaseModel): class Token(BaseModel):
access_token: str access_token: str
token_type: str # token_type: str
class TokenData(BaseModel): class TokenData(BaseModel):

View File

@ -9,20 +9,20 @@ 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 .models import UserDatabase from .models import UserDatabase
from .schema import Token, TokenData, UserInDB, User from .schema import Token, TokenData, UserInDB, User
SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
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="token")
def verify_password(plain_password, hashed_password): def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password) return pwd_context.verify(plain_password, hashed_password)
@ -33,11 +33,7 @@ def get_password_hash(password):
# проблема здесь # проблема здесь
def get_user(db: Session, email: str): def get_user(db: Session, email: str):
user_with_required_email = db.query(UserDatabase).filter(UserDatabase.email == email).first() return db.query(UserDatabase).filter(UserDatabase.email == email).first()
print(user_with_required_email)
if user_with_required_email:
return user_with_required_email
return None
def authenticate_user(db: Session, email: str, password: str): def authenticate_user(db: Session, email: str, password: str):
@ -74,8 +70,8 @@ async def get_current_user(db: Session, token: Annotated[str, Depends(oauth2_sch
token_data = TokenData(email=email) token_data = TokenData(email=email)
except JWTError: except JWTError:
raise credentials_exception raise credentials_exception
user = get_user(db, email=token_data.email) user = get_user(db=db, email=token_data.email)
if user == None: if user is None:
raise credentials_exception raise credentials_exception
return user return user
@ -88,5 +84,12 @@ async def get_current_active_user(
return current_user return current_user
def get_db(request: Request): # def get_db(request: Request):
return request.state.db # return request.state.db
# def get_db():
# db = SessionLocal()
# try:
# yield db
# finally:
# db.close()