Skip to content

Commit

Permalink
a little auth for the endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
Unischneider committed Nov 2, 2024
1 parent 5a55917 commit 9ba0afc
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 6 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,8 @@ jobs:
echo "COHERE_API_KEY=${{ secrets.COHERE_API_KEY }}" >> /home/${{ vars.VM_USERNAME }}/${{ github.repository }}/.env.prod
echo "COHERE_API_KEY_MULTI=${{ secrets.COHERE_API_KEY_MULTI }}" >> /home/${{ vars.VM_USERNAME }}/${{ github.repository }}/.env.prod
echo "COHERE_API_KEY_EN=${{ secrets.COHERE_API_KEY_EN }}" >> /home/${{ vars.VM_USERNAME }}/${{ github.repository }}/.env.prod
echo "ANGELOS_APP_API_KEY=${{ secrets.ANGELOS_APP_API_KEY }}" >> /home/${{ vars.VM_USERNAME }}/${{ github.repository }}/.env.prod
echo "API_ENDPOINT_KEY=${{ secrets.API_ENDPOINT_KEY }}" >> /home/${{ vars.VM_USERNAME }}/${{ github.repository }}/.env.prod
- name: SSH to VM and Execute Docker-Compose Up
Expand Down
56 changes: 50 additions & 6 deletions app/api/question_router.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import logging
from datetime import datetime, timezone, timedelta

from fastapi import HTTPException, APIRouter, status, Response
import jwt
from fastapi import HTTPException, APIRouter, status, Response, Header, Depends
from pydantic import BaseModel

from app.data.user_requests import UserChat
Expand All @@ -15,7 +17,49 @@ class UserRequest(BaseModel):
language: str


router = APIRouter(prefix="/api/v1/question", tags=["response"])
SECRET_KEY = config.API_ENDPOINT_KEY
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 60


def create_access_token(data: dict):
"""
Generates a JWT token with an expiration time.
"""
to_encode = data.copy()
expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": expire})
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)


async def verify_api_key(x_api_key: str = Header(None)):
if x_api_key != config.ANGELOS_APP_API_KEY:
raise HTTPException(status_code=403, detail="Unauthorized access")


async def verify_token(authorization: str = Header(...)):
"""
Dependency to validate the JWT token in the Authorization header.
"""
try:
token = authorization.split(" ")[1]
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
except jwt.ExpiredSignatureError:
raise HTTPException(status_code=403, detail="Token has expired")
except jwt.PyJWTError:
raise HTTPException(status_code=403, detail="Invalid token")


router = APIRouter(prefix="/api/v1/question", tags=["response"], dependencies=[Depends(verify_token)])
auth = APIRouter(prefix="/api", tags=["response"], dependencies=[Depends(verify_api_key)])


@auth.post("/token")
async def login():
token_data = {"sub": "angular_app"}
access_token = create_access_token(data=token_data)
return {"access_token": access_token, "token_type": "bearer"}


@router.post("/ask")
async def ask(request: UserRequest):
Expand All @@ -24,15 +68,15 @@ async def ask(request: UserRequest):
language = request.language
if not question or not classification:
raise HTTPException(status_code=400, detail="No question or classification provided")

if len(question) > config.MAX_MESSAGE_LENGTH:
raise HTTPException(
status_code=400,
detail=f"Question length exceeds the allowed limit of {config.MAX_MESSAGE_LENGTH} characters"
)

logging.info(f"Received question: {question} with classification: {classification}")

if config.TEST_MODE:
answer, used_tokens, general_context, specific_context = request_handler.handle_question_test_mode(question,
classification,
Expand All @@ -49,14 +93,14 @@ async def chat(request: UserChat):
messages = request.messages
if not messages:
raise HTTPException(status_code=400, detail="No messages have been provided")

last_message = messages[-1].message
if len(last_message) > config.MAX_MESSAGE_LENGTH:
raise HTTPException(
status_code=400,
detail=f"Message length exceeds the allowed limit of {config.MAX_MESSAGE_LENGTH} characters"
)

logging.info(f"Received messages.")
answer = request_handler.handle_chat(messages, study_program=request.study_program)
return {"answer": answer}
Expand Down
4 changes: 4 additions & 0 deletions app/utils/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,9 @@ class Config:
COHERE_API_KEY_MULTI = os.getenv("COHERE_API_KEY_MULTI")
COHERE_API_KEY_EN = os.getenv("COHERE_API_KEY_EN")

# safeguard
API_ENDPOINT_KEY = os.getenv("API_ENDPOINT_KEY")
ANGELOS_APP_API_KEY = os.getenv("ANGELOS_APP_API_KEY")


config = Config()
2 changes: 2 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ services:
- COHERE_API_KEY
- COHERE_API_KEY_MULTI
- COHERE_API_KEY_EN
- API_ENDPOINT_KEY
- ANGELOS_APP_API_KEY
networks:
- angelos-network

Expand Down

0 comments on commit 9ba0afc

Please sign in to comment.