From a7e1aae7445b6041c3ec676914153c93c94abd26 Mon Sep 17 00:00:00 2001 From: sunwoo1524 Date: Sun, 3 Nov 2024 17:44:18 +0900 Subject: [PATCH] Refactor: user handle validation function --- main.py | 11 +++++++---- utils/feed_generator.py | 18 ++++-------------- 2 files changed, 11 insertions(+), 18 deletions(-) diff --git a/main.py b/main.py index d4de20f..9c3bfa4 100644 --- a/main.py +++ b/main.py @@ -1,10 +1,10 @@ from fastapi import FastAPI, HTTPException, Response, Depends from sqlmodel import Session, select from typing import Annotated -import datetime +import datetime, re from database.feed import Feed, FeedCreate, FeedPublic, FeedUpdate -from utils.feed_generator import generate_feed_of_user, USER_NOT_FOUND, CANNOT_ACCESS_INSTANCE, INVALID_HANDLE +from utils.feed_generator import generate_feed_of_user, USER_NOT_FOUND, CANNOT_ACCESS_INSTANCE from utils.database import get_session, create_db_and_tables app = FastAPI() @@ -18,6 +18,11 @@ def on_startup(): @app.get("/feed/{user_handle}") def get_feed_of_user(user_handle: str, session: SessionDep): + # validate user's handle + HANDLE_PATTERN = "@[a-zA-Z0-9_]+@[^\t\n\r\f\v]+" + if re.match(HANDLE_PATTERN, user_handle) is None: + return HTTPException(status_code=400, detail="The handle is invalid.") + # get feed on database feed_db = session.exec(select(Feed).where(Feed.handle == user_handle)).first() @@ -31,8 +36,6 @@ def get_feed_of_user(user_handle: str, session: SessionDep): return HTTPException(status_code=404, detail="The user cannot be found.") if feed == CANNOT_ACCESS_INSTANCE: return HTTPException(status_code=400, detail="Cannot access the instance.") - if feed == INVALID_HANDLE: - return HTTPException(status_code=400, detail="The handle is invalid.") # cache new feed if feed_db: diff --git a/utils/feed_generator.py b/utils/feed_generator.py index 4d36b15..fdd680e 100644 --- a/utils/feed_generator.py +++ b/utils/feed_generator.py @@ -6,21 +6,11 @@ CANNOT_ACCESS_INSTANCE = 2 INVALID_HANDLE = 3 -def parse_handle(user_handle: str) -> list[str] | None: - # validate user's handle - HANDLE_PATTERN = "@[a-zA-Z0-9_]+@[^\t\n\r\f\v]+" - if re.match(HANDLE_PATTERN, user_handle) is None: - return None - - # parse user's handle - return user_handle.split("@")[1:] - - def get_statuses_of_user(user_handle: str) -> list[dict] | str: - parsed_handle = parse_handle(user_handle) - if parsed_handle is None: - return INVALID_HANDLE - [username, instance] = parsed_handle + # parsed_handle = parse_handle(user_handle) + # if parsed_handle is None: + # return INVALID_HANDLE + [username, instance] = user_handle.split("@")[1:] try: account_lookup = requests.get(f"https://{instance}/api/v1/accounts/lookup?acct={username}")