Auth. was fixed. Problem is in getting curr. user
This commit is contained in:
parent
904b00059f
commit
dd719a20ec
44
back/main.py
44
back/main.py
@ -39,15 +39,15 @@ app.mount("/uploads", StaticFiles(directory = "./uploads"))
|
||||
# Функция, создающая сессию БД при каждом запросе к нашему API.
|
||||
# Срабатывает до запуска остальных функций.
|
||||
# Всегда закрывает сессию при окончании работы с ней
|
||||
@app.middleware("http")
|
||||
async def db_session_middleware(request: Request, call_next):
|
||||
response = Response("Internal server error", status_code=500)
|
||||
try:
|
||||
request.state.db = SessionLocal()
|
||||
response = await call_next(request)
|
||||
finally:
|
||||
request.state.db.close()
|
||||
return response
|
||||
# @app.middleware("http")
|
||||
# async def db_session_middleware(request: Request, call_next):
|
||||
# response = Response("Internal server error", status_code=500)
|
||||
# try:
|
||||
# request.state.db = SessionLocal()
|
||||
# response = await call_next(request)
|
||||
# finally:
|
||||
# request.state.db.close()
|
||||
# return response
|
||||
|
||||
|
||||
@app.get("/api/announcements")#адрес объявлений
|
||||
@ -150,10 +150,12 @@ def change_book_status(data: schema.Book):
|
||||
return {"Success": False}
|
||||
|
||||
# reginstration
|
||||
# {"id":1, "email":"poopka@mail.ru", "password":"good", "name":"Vasya", "surname":"Poopkin"}
|
||||
@app.post("/api/signup")
|
||||
def create_user(data = Body()):
|
||||
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.commit()
|
||||
database.refresh(new_user) # обновляем состояние объекта
|
||||
@ -177,21 +179,21 @@ async def login_for_access_token(
|
||||
access_token = create_access_token(
|
||||
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)
|
||||
async def read_users_me( #!!!!!!!!!!!
|
||||
current_user: Annotated[User, Depends(get_current_active_user)]
|
||||
):
|
||||
return current_user
|
||||
# @app.get("/api/users/me/", response_model=schema.User)
|
||||
# async def read_users_me( #!!!!!!!!!!!
|
||||
# current_user: Annotated[schema.User, Depends(get_current_active_user)]
|
||||
# ):
|
||||
# return {"data": current_user}
|
||||
|
||||
|
||||
@app.get("/api/users/me/items/")
|
||||
async def read_own_items(
|
||||
current_user: Annotated[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[schema.User, Depends(get_current_active_user)]
|
||||
# ):
|
||||
# return [{"Current user name": current_user.name, "Current user surname": current_user.surname}]
|
||||
|
||||
|
||||
|
||||
|
@ -1,11 +1,11 @@
|
||||
from sqlalchemy import Column, Integer, String
|
||||
from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase
|
||||
from fastapi import Depends
|
||||
from .db import Base
|
||||
from .db import Base, engine
|
||||
|
||||
|
||||
class User(SQLAlchemyBaseUserTableUUID, Base):
|
||||
pass
|
||||
# class User(SQLAlchemyBaseUserTableUUID, Base):
|
||||
# name = Column(String, nullable=True)#имя пользователя
|
||||
|
||||
|
||||
|
||||
|
@ -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 typing import Annotated, Union
|
||||
|
||||
@ -7,7 +24,7 @@ class Book(BaseModel):
|
||||
|
||||
class Token(BaseModel):
|
||||
access_token: str
|
||||
token_type: str
|
||||
# token_type: str
|
||||
|
||||
|
||||
class TokenData(BaseModel):
|
||||
|
@ -9,20 +9,20 @@ 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 .models import UserDatabase
|
||||
|
||||
from .schema import Token, TokenData, UserInDB, User
|
||||
|
||||
SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
|
||||
|
||||
|
||||
|
||||
SECRET_KEY = "SECRET"
|
||||
ALGORITHM = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
||||
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
|
||||
|
||||
|
||||
def verify_password(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):
|
||||
user_with_required_email = 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
|
||||
return db.query(UserDatabase).filter(UserDatabase.email == email).first()
|
||||
|
||||
|
||||
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)
|
||||
except JWTError:
|
||||
raise credentials_exception
|
||||
user = get_user(db, email=token_data.email)
|
||||
if user == None:
|
||||
user = get_user(db=db, email=token_data.email)
|
||||
if user is None:
|
||||
raise credentials_exception
|
||||
return user
|
||||
|
||||
@ -88,5 +84,12 @@ async def get_current_active_user(
|
||||
return current_user
|
||||
|
||||
|
||||
def get_db(request: Request):
|
||||
return request.state.db
|
||||
# def get_db(request: Request):
|
||||
# return request.state.db
|
||||
|
||||
# def get_db():
|
||||
# db = SessionLocal()
|
||||
# try:
|
||||
# yield db
|
||||
# finally:
|
||||
# db.close()
|
Loading…
x
Reference in New Issue
Block a user