Skip to content

Commit

Permalink
refactor a bunch of stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
codekansas committed Nov 7, 2024
1 parent aa30c79 commit 6e8a529
Show file tree
Hide file tree
Showing 20 changed files with 198 additions and 180 deletions.
4 changes: 2 additions & 2 deletions store/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
NotAuthorizedError,
)
from store.app.routers.artifacts import artifacts_router
from store.app.routers.authenticate import auth_router
from store.app.routers.auth import router
from store.app.routers.email import email_router
from store.app.routers.kernel_images import kernel_images_router
from store.app.routers.keys import keys_router
Expand Down Expand Up @@ -182,7 +182,7 @@ async def validate_auth_token(auth_token: str = Depends(api_key_header)) -> str:
return auth_token


app.include_router(auth_router, prefix="/auth", tags=["auth"])
app.include_router(router, prefix="/auth", tags=["auth"])
app.include_router(artifacts_router, prefix="/artifacts", tags=["artifacts"])
app.include_router(email_router, prefix="/email", tags=["email"])
app.include_router(kernel_images_router, prefix="/kernel-images", tags=["kernel-images"])
Expand Down
5 changes: 1 addition & 4 deletions store/app/routers/artifacts.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,7 @@
get_artifact_url,
get_artifact_urls,
)
from store.app.routers.users import (
get_session_user_with_write_permission,
maybe_get_user_from_api_key,
)
from store.app.security.user import get_session_user_with_write_permission, maybe_get_user_from_api_key
from store.settings import settings

artifacts_router = APIRouter()
Expand Down
15 changes: 15 additions & 0 deletions store/app/routers/auth/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
"""Defines the authentication endpoints for the API."""

from fastapi import APIRouter

from store.app.routers.auth.api import router as api_router
from store.app.routers.auth.email import router as email_router
from store.app.routers.auth.github import router as github_router
from store.app.routers.auth.google import router as google_router

router = APIRouter()

router.include_router(api_router, prefix="/api")
router.include_router(github_router, prefix="/github")
router.include_router(google_router, prefix="/google")
router.include_router(email_router, prefix="/email")
19 changes: 19 additions & 0 deletions store/app/routers/auth/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"""Defines authentication endpoints for API-related activities."""

from typing import Annotated

from fastapi import APIRouter, Depends

from store.app.db import Crud
from store.app.security.requests import get_request_api_key_id

router = APIRouter()


@router.delete("/logout")
async def logout_user_endpoint(
token: Annotated[str, Depends(get_request_api_key_id)],
crud: Annotated[Crud, Depends(Crud.get)],
) -> bool:
await crud.delete_api_key(token)
return True
Original file line number Diff line number Diff line change
@@ -1,54 +1,16 @@
"""This module defines the FastAPI routes for authentication related API routes."""
"""Defines the authentication endpoints for email-based authentication."""

from typing import Annotated, Literal, Mapping, Self, overload
from typing import Annotated, Self

from fastapi import APIRouter, Depends, HTTPException, Request, status
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, EmailStr

from store.app.crud.users import UserCrud
from store.app.db import Crud
from store.app.model import APIKeySource, User
from store.app.routers.auth.github import github_auth_router
from store.app.routers.auth.google import google_auth_router
from store.app.utils.password import verify_password

auth_router = APIRouter()


@overload
async def get_api_key_from_header(headers: Mapping[str, str], require_header: Literal[True]) -> str: ...


@overload
async def get_api_key_from_header(headers: Mapping[str, str], require_header: Literal[False]) -> str | None: ...


async def get_api_key_from_header(headers: Mapping[str, str], require_header: bool) -> str | None:
authorization = headers.get("Authorization") or headers.get("authorization")
if not authorization:
if require_header:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
return None

# Check if the authorization header starts with "Bearer "
if authorization.startswith("Bearer "):
credentials = authorization[7:] # Remove "Bearer " prefix
else:
# If "Bearer " is missing, assume the entire header is the token
credentials = authorization

if not credentials:
raise HTTPException(status_code=status.HTTP_406_NOT_ACCEPTABLE, detail="Authorization header is invalid")

return credentials


async def get_request_api_key_id(request: Request) -> str:
return await get_api_key_from_header(request.headers, True)


async def maybe_get_request_api_key_id(request: Request) -> str | None:
return await get_api_key_from_header(request.headers, False)
router = APIRouter()


class UserSignup(BaseModel):
Expand Down Expand Up @@ -83,7 +45,7 @@ class LoginResponse(BaseModel):
token: str


@auth_router.post("/signup", response_model=UserInfoResponseItem)
@router.post("/signup", response_model=UserInfoResponseItem)
async def register_user(data: UserSignup, crud: Annotated[Crud, Depends(Crud.get)]) -> UserInfoResponseItem:
signup_token = await crud.get_email_signup_token(data.signup_token_id)
if not signup_token:
Expand All @@ -96,7 +58,7 @@ async def register_user(data: UserSignup, crud: Annotated[Crud, Depends(Crud.get
return UserInfoResponseItem(id=user.id, email=user.email)


@auth_router.post("/login", response_model=LoginResponse)
@router.post("/login", response_model=LoginResponse)
async def login_user(data: LoginRequest, user_crud: UserCrud = Depends()) -> LoginResponse:
async with user_crud:
# Fetch user by email
Expand Down Expand Up @@ -124,16 +86,3 @@ async def login_user(data: LoginRequest, user_crud: UserCrud = Depends()) -> Log
)

return LoginResponse(user_id=user.id, token=api_key.id)


auth_router.include_router(github_auth_router, prefix="/github")
auth_router.include_router(google_auth_router, prefix="/google")


@auth_router.delete("/logout")
async def logout_user_endpoint(
token: Annotated[str, Depends(get_request_api_key_id)],
crud: Annotated[Crud, Depends(Crud.get)],
) -> bool:
await crud.delete_api_key(token)
return True
6 changes: 3 additions & 3 deletions store/app/routers/auth/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@

logger = logging.getLogger(__name__)

github_auth_router = APIRouter()
router = APIRouter()


class ClientIdResponse(BaseModel):
client_id: str


@github_auth_router.get("/client-id", response_model=ClientIdResponse)
@router.get("/client-id", response_model=ClientIdResponse)
async def github_client_id_endpoint() -> ClientIdResponse:
return ClientIdResponse(client_id=settings.oauth.github_client_id)

Expand Down Expand Up @@ -51,7 +51,7 @@ class GithubAuthResponse(BaseModel):
api_key: str


@github_auth_router.post("/code", response_model=GithubAuthResponse)
@router.post("/code", response_model=GithubAuthResponse)
async def github_code(
data: GithubAuthRequest,
crud: Annotated[Crud, Depends(Crud.get)],
Expand Down
6 changes: 3 additions & 3 deletions store/app/routers/auth/google.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

logger = logging.getLogger(__name__)

google_auth_router = APIRouter()
router = APIRouter()


class GoogleLogin(BaseModel):
Expand All @@ -35,7 +35,7 @@ class ClientIdResponse(BaseModel):
client_id: str


@google_auth_router.get("/client-id", response_model=ClientIdResponse)
@router.get("/client-id", response_model=ClientIdResponse)
async def google_client_id_endpoint() -> ClientIdResponse:
return ClientIdResponse(client_id=settings.oauth.google_client_id)

Expand All @@ -44,7 +44,7 @@ class AuthResponse(BaseModel):
api_key: str


@google_auth_router.post("/login", response_model=AuthResponse)
@router.post("/login", response_model=AuthResponse)
async def google_login_endpoint(
data: GoogleLogin,
crud: Annotated[Crud, Depends(Crud.get)],
Expand Down
2 changes: 1 addition & 1 deletion store/app/routers/kernel_images.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

from store.app.db import Crud
from store.app.model import User
from store.app.routers.users import (
from store.app.security.user import (
get_session_user_with_read_permission,
get_session_user_with_write_permission,
maybe_get_user_from_api_key,
Expand Down
2 changes: 1 addition & 1 deletion store/app/routers/keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from store.app.db import Crud
from store.app.model import APIKeyPermission, User
from store.app.routers.users import get_session_user_with_admin_permission
from store.app.security.user import get_session_user_with_admin_permission

logger = logging.getLogger(__name__)

Expand Down
2 changes: 1 addition & 1 deletion store/app/routers/listings.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from store.app.db import Crud
from store.app.model import Listing, User, can_write_listing
from store.app.routers.artifacts import SingleArtifactResponse
from store.app.routers.users import (
from store.app.security.user import (
get_session_user_with_read_permission,
get_session_user_with_write_permission,
maybe_get_user_from_api_key,
Expand Down
2 changes: 1 addition & 1 deletion store/app/routers/onshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

from store.app.db import Crud
from store.app.model import User, can_write_listing
from store.app.routers.users import get_session_user_with_write_permission
from store.app.security.user import get_session_user_with_write_permission

onshape_router = APIRouter()

Expand Down
13 changes: 9 additions & 4 deletions store/app/routers/orders.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from store.app.db import Crud
from store.app.model import Order, User
from store.app.routers.stripe import get_product
from store.app.routers.users import get_session_user_with_read_permission
from store.app.security.user import get_session_user_with_read_permission

orders_router = APIRouter()

Expand Down Expand Up @@ -40,7 +40,9 @@ async def get_user_orders(

@orders_router.get("/order/{order_id}", response_model=Order)
async def get_order(
order_id: str, user: User = Depends(get_session_user_with_read_permission), crud: Crud = Depends(Crud.get)
order_id: str,
user: User = Depends(get_session_user_with_read_permission),
crud: Crud = Depends(Crud.get),
) -> Order:
order = await crud.get_order(order_id)
if order is None or order.user_id != user.id:
Expand All @@ -50,7 +52,9 @@ async def get_order(

@orders_router.get("/order-with-product/{order_id}", response_model=OrderWithProduct)
async def get_order_with_product(
order_id: str, user: User = Depends(get_session_user_with_read_permission), crud: Crud = Depends(Crud.get)
order_id: str,
user: User = Depends(get_session_user_with_read_permission),
crud: Crud = Depends(Crud.get),
) -> OrderWithProduct:
order = await crud.get_order(order_id)
if order is None or order.user_id != user.id:
Expand All @@ -65,7 +69,8 @@ async def get_order_with_product(

@orders_router.get("/user-orders-with-products", response_model=List[OrderWithProduct])
async def get_user_orders_with_products(
user: User = Depends(get_session_user_with_read_permission), crud: Crud = Depends(Crud.get)
user: User = Depends(get_session_user_with_read_permission),
crud: Crud = Depends(Crud.get),
) -> List[OrderWithProduct]:
try:
orders = await crud.get_orders_by_user_id(user.id)
Expand Down
2 changes: 1 addition & 1 deletion store/app/routers/robots.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from store.app.crud.base import ItemNotFoundError
from store.app.db import Crud
from store.app.model import Listing, Robot, User, get_artifact_url
from store.app.routers.users import (
from store.app.security.user import (
get_session_user_with_read_permission,
get_session_user_with_write_permission,
)
Expand Down
2 changes: 1 addition & 1 deletion store/app/routers/stripe.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

from store.app.db import Crud
from store.app.model import Order, User
from store.app.routers.users import get_session_user_with_read_permission
from store.app.security.user import get_session_user_with_read_permission
from store.settings import settings

logger = logging.getLogger(__name__)
Expand Down
9 changes: 9 additions & 0 deletions store/app/routers/teleop/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
"""Defines the teleoperation endpoints for the API."""

from fastapi import APIRouter

from store.app.routers.teleop.webrtc import webrtc_router

teleop_router = APIRouter()

teleop_router.include_router(webrtc_router, prefix="/rtc")
Loading

0 comments on commit 6e8a529

Please sign in to comment.