Skip to content

Commit

Permalink
Merge pull request #14 from 4l3j0Ok/basic-auth-for-update-endpoints
Browse files Browse the repository at this point in the history
Basic auth for update endpoints
  • Loading branch information
4l3j0Ok authored Mar 30, 2024
2 parents c77b45f + 77187f0 commit 1f9005a
Show file tree
Hide file tree
Showing 6 changed files with 45 additions and 31 deletions.
2 changes: 1 addition & 1 deletion src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ async def home() -> responses.RedirectResponse:
@app.get("/alive", tags=["Main"])
async def alive() -> str:
"Chequea si la aplicación está viva."
return "Estoy vivo!"
return "BCRA Scraper API se encuentra funcionando."


if __name__ == "__main__":
Expand Down
9 changes: 0 additions & 9 deletions src/modules/bank.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from modules.logger import logger
from models.bank import Bank
from db.client import client
import os


db = client.bcra_scraper.banks
Expand Down Expand Up @@ -35,11 +34,3 @@ def add_bank(bank):
logger.info("Agregando un nuevo banco...")
result = db.insert_one(bank.dict())
return True, messages.MSG_SUCCESS_SAVE


def validate_admin(credentials):
if not credentials.username == os.getenv("ADMIN_USER"):
return False
if not credentials.password == os.getenv("ADMIN_PASS"):
return False
return True
3 changes: 3 additions & 0 deletions src/modules/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,6 @@

APP_TITLE = "BCRA Scraper API"
APP_DESCRIPTION = "API de bancos."

ADMIN_USER = os.getenv("ADMIN_USER")
ADMIN_PASS = os.getenv("ADMIN_PASS")
23 changes: 23 additions & 0 deletions src/modules/security.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import secrets
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from typing import Annotated
from modules.logger import logger
from modules import config


security = HTTPBasic()


def validate_admin(
credentials: Annotated[HTTPBasicCredentials, Depends(security)],
):
is_correct_username = secrets.compare_digest(
credentials.username.encode("utf8"),
config.ADMIN_USER.encode("utf8")
)
is_correct_password = secrets.compare_digest(
credentials.password.encode("utf8"),
config.ADMIN_PASS.encode("utf8")
)
return (is_correct_username and is_correct_password)
37 changes: 17 additions & 20 deletions src/routers/bank.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from fastapi import APIRouter, HTTPException
from fastapi import APIRouter, HTTPException, Depends, HTTPException, status
from typing import Annotated
import modules.bank as functions
from models.response import Success, Detail
from modules import messages
from models.bank import Bank, AdminCredentials
from modules import messages, security
from models.bank import Bank


router = APIRouter()
Expand All @@ -14,7 +15,7 @@ async def get(bcra_id: str = None) -> Success:
success, result = functions.get_banks(bcra_id, as_dict=True)
if not success:
raise HTTPException(
status_code=404,
status_code=status.HTTP_400_BAD_REQUEST,
detail=Detail(
payload=None,
message=result
Expand All @@ -29,20 +30,18 @@ async def get(bcra_id: str = None) -> Success:


@router.post("/update")
async def update_banks_list(credentials: AdminCredentials) -> Success:
async def update_banks_list(authorized: Annotated[str, Depends(security.validate_admin)]) -> Success:
"Actualiza la lista de bancos en la base de datos usando Web Scraping."
if not functions.validate_admin(credentials):
if not authorized:
raise HTTPException(
status_code=401,
detail=Detail(
payload=None,
message=messages.MSG_ERROR_UNAUTHORIZED
)
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Usuario o contraseña incorrectos.",
headers={"WWW-Authenticate": "Basic"},
)
success, result = functions.update_banks()
if not success:
raise HTTPException(
status_code=400,
status_code=status.HTTP_400_BAD_REQUEST,
detail=Detail(
payload=None,
message=result
Expand All @@ -57,20 +56,18 @@ async def update_banks_list(credentials: AdminCredentials) -> Success:


@router.post("/add")
def add_bank(bank: Bank, credentials: AdminCredentials) -> Success:
def add_bank(bank: Bank, authorized: Annotated[str, Depends(security.validate_admin)]) -> Success:
"Agrega el banco indicado."
if not functions.validate_admin(credentials):
if not authorized:
raise HTTPException(
status_code=401,
detail=Detail(
payload=None,
message=messages.MSG_ERROR_UNAUTHORIZED
)
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Usuario o contraseña incorrectos.",
headers={"WWW-Authenticate": "Basic"},
)
success, result = functions.add_bank(bank)
if not success:
raise HTTPException(
status_code=400,
status_code=status.HTTP_400_BAD_REQUEST,
detail=Detail(
payload=None,
message=result
Expand Down
2 changes: 1 addition & 1 deletion stack/dev.compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ services:
dockerfile: ../src/Dockerfile
volumes:
- ../src:/app/src
restart: unless-stopped
restart: no
ports:
- "8080:8080"
env_file:
Expand Down

0 comments on commit 1f9005a

Please sign in to comment.