Skip to content

Commit

Permalink
UPDATE: security
Browse files Browse the repository at this point in the history
  • Loading branch information
mazzasaverio committed Apr 5, 2024
1 parent d269d0b commit 4f34181
Show file tree
Hide file tree
Showing 13 changed files with 303 additions and 272 deletions.
12 changes: 3 additions & 9 deletions backend/app/api/deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@

from app.models.user_model import TokenPayload, User
from sqlmodel import Session, create_engine, select

from fastapi.security import OAuth2PasswordBearer
from fastapi_nextauth_jwt import NextAuthJWT
from starlette.requests import Request

engine = create_engine(str(settings.SYNC_DATABASE_URI))

Expand Down Expand Up @@ -58,11 +60,3 @@ def get_current_active_superuser(current_user: CurrentUser) -> User:
status_code=400, detail="The user doesn't have enough privileges"
)
return current_user


def verify_password_reset_token(token: str) -> str | None:
try:
decoded_token = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
return str(decoded_token["sub"])
except JWTError:
return None
3 changes: 2 additions & 1 deletion backend/app/api/main.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from fastapi import APIRouter

from app.api.routes import qa
from app.api.routes import qa, login

api_router = APIRouter()

api_router.include_router(login.router, tags=["login"])
api_router.include_router(
qa.router,
prefix="/qa",
Expand Down
18 changes: 5 additions & 13 deletions backend/app/api/routes/login.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,15 @@
from datetime import timedelta
from typing import Annotated, Any
from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import HTMLResponse
from fastapi.security import OAuth2PasswordRequestForm

from app.crud import user_crud
from app.api.deps import (
CurrentUser,
SessionDep,
get_current_active_superuser,
verify_password_reset_token,
)
from app.api.deps import SessionDep
from app.core import security
from app.core.config import settings
from app.core.security import get_password_hash
from app.models.user_model import Message, NewPassword, Token, UserOut
from app.core.config import logger
from app.models.user_model import Token


router = APIRouter()

Expand All @@ -31,12 +24,11 @@ def login_access_token(
user = user_crud.authenticate(
session=session, email=form_data.username, password=form_data.password
)
logger.info(f"User {user} logged in")
if not user:
raise HTTPException(status_code=400, detail="Incorrect email or password")
elif not user.is_active:
raise HTTPException(status_code=400, detail="Inactive user")
access_token_expires = timedelta(minutes=100000)
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
return Token(
access_token=security.create_access_token(
user.id, expires_delta=access_token_expires
Expand Down
14 changes: 7 additions & 7 deletions backend/app/api/routes/qa.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
from app.core.db import SessionLocal
import os
import yaml

from app.core.config import logger, settings


from operator import itemgetter
from typing import Annotated

from langchain_community.vectorstores import FAISS
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableLambda, RunnablePassthrough
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_core.messages import AIMessage, HumanMessage, get_buffer_string
from langchain_core.messages import get_buffer_string
from langchain_core.prompts import format_document
from langchain_core.runnables import RunnableParallel

from langchain_community.vectorstores.pgvector import PGVector
from langchain.memory import ConversationBufferMemory

from langchain.prompts.prompt import PromptTemplate
from app.schemas.chat_schema import ChatBody
from fastapi import APIRouter, Depends
from app.api.deps import get_current_user
from app.api.deps import CurrentUser, get_current_user
from app.models.user_model import User

from dotenv import load_dotenv

load_dotenv()
router = APIRouter()

config_path = os.path.join(os.path.dirname(__file__), "..", "..", "config/chat.yml")
Expand All @@ -36,7 +36,7 @@

@router.post("/chat")
async def chat_action(
request: ChatBody, current_user: Annotated[User, Depends(get_current_user)]
request: ChatBody, current_user: User = Depends(get_current_user)
):

embeddings = OpenAIEmbeddings()
Expand Down
223 changes: 0 additions & 223 deletions backend/app/api/routes/users.py

This file was deleted.

12 changes: 3 additions & 9 deletions backend/app/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,12 @@ class Settings(BaseSettings):
REDIS_HOST: str
REDIS_PORT: str

TAVILY_API_KEY: str

FIRST_SUPERUSER: str
FIRST_SUPERUSER_PASSWORD: str

BACKEND_CORS_ORIGINS: Annotated[list[AnyUrl] | str, BeforeValidator(parse_cors)] = (
[]
)
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8

BACKEND_CORS_ORIGINS: List[str] = []

@property
def ASYNC_DATABASE_URI(self) -> str:
Expand All @@ -56,10 +54,6 @@ def ASYNC_DATABASE_URI(self) -> str:
def SYNC_DATABASE_URI(self) -> str:
return f"postgresql+psycopg2://{self.DB_USER}:{self.DB_PASS}@{self.DB_HOST}:{self.DB_PORT}/{self.DB_NAME}"

FIRST_SUPERUSER: str
FIRST_SUPERUSER_PASSWORD: str
USERS_OPEN_REGISTRATION: bool = False

class Config:
env_file = "../.env"

Expand Down
4 changes: 2 additions & 2 deletions backend/app/core/security.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from datetime import datetime, timedelta, timezone
from datetime import datetime, timedelta
from typing import Any

from jose import jwt
Expand All @@ -13,7 +13,7 @@


def create_access_token(subject: str | Any, expires_delta: timedelta) -> str:
expire = datetime.now(timezone.utc) + expires_delta
expire = datetime.utcnow() + expires_delta
to_encode = {"exp": expire, "sub": str(subject)}
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
Expand Down
2 changes: 1 addition & 1 deletion backend/app/models/user_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class UserCreate(UserBase):


# TODO replace email str with EmailStr when sqlmodel supports it
class UserCreateOpen(SQLModel):
class UserRegister(SQLModel):
email: str
password: str
full_name: str | None = None
Expand Down
Loading

0 comments on commit 4f34181

Please sign in to comment.