Skip to content

Commit

Permalink
updated authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
codekansas committed Dec 29, 2024
1 parent 2a54605 commit 0572798
Show file tree
Hide file tree
Showing 17 changed files with 86 additions and 331 deletions.
1 change: 0 additions & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ jobs:
environment: ${{ github.ref == 'refs/heads/master' && 'production' || 'staging' }}

env:
JWT_SECRET: test
AWS_ACCESS_KEY_ID: test
AWS_SECRET_ACCESS_KEY: test
AWS_ENDPOINT_URL_DYNAMODB: http://localhost:8000
Expand Down
1 change: 1 addition & 0 deletions env.sh.example
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Specifies a local environment versus production environment.
export ENVIRONMENT='local'
export MIDDLEWARE_SECRET_KEY='test'

# For AWS
export AWS_DEFAULT_REGION='us-east-1'
Expand Down
18 changes: 17 additions & 1 deletion www/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
from fastapi import Depends, FastAPI, HTTPException, Request, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.security import APIKeyCookie, APIKeyHeader
from fastapi.security import APIKeyCookie, APIKeyHeader, OAuth2AuthorizationCodeBearer
from starlette.middleware.sessions import SessionMiddleware

from www.app.db import create_tables
from www.app.errors import (
Expand All @@ -27,6 +28,7 @@
from www.app.routers.robots import router as robots_router
from www.app.routers.teleop import router as teleop_router
from www.app.routers.users import router as users_router
from www.settings import settings
from www.utils import get_cors_origins


Expand Down Expand Up @@ -63,6 +65,20 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
allow_headers=["*"],
)

# Add authentication middleware.
app.add_middleware(
SessionMiddleware,
secret_key=settings.middleware.secret_key,
)

oauth2_scheme = OAuth2AuthorizationCodeBearer(
authorizationUrl="https://accounts.google.com/o/oauth2/auth",
tokenUrl="https://accounts.google.com/o/oauth2/token",
refreshUrl="https://accounts.google.com/o/oauth2/token",
scopes={"openid": "Access your OpenAI information"},
auto_error=False,
)


@app.exception_handler(ValueError)
async def value_error_exception_handler(request: Request, exc: ValueError) -> JSONResponse:
Expand Down
56 changes: 56 additions & 0 deletions www/app/routers/auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"""Defines the API endpoint for authenticating the user."""

import logging

from authlib.integrations.starlette_client import OAuth
from fastapi import APIRouter
from fastapi.requests import Request
from fastapi.responses import RedirectResponse
from starlette.config import Config as StarletteConfig

from www.settings import settings

logger = logging.getLogger(__name__)

router = APIRouter()

# Set up authlib OAuth.
starlette_config = StarletteConfig(
environ={
"GOOGLE_CLIENT_ID": settings.oauth.google_client_id,
"GOOGLE_CLIENT_SECRET": settings.oauth.google_client_secret,
"SECRET_KEY": settings.middleware.secret_key,
},
)

oauth = OAuth(starlette_config)

# Register Google authentication.
google = oauth.register(
name="google",
client_id=settings.oauth.google_client_id,
client_secret=settings.oauth.google_client_secret,
access_token_url="https://accounts.google.com/o/oauth2/token",
access_token_params=None,
authorize_url="https://accounts.google.com/o/oauth2/auth",
authorize_params={
"scope": "openid email profile",
"prompt": "consent",
},
api_base_url="https://www.googleapis.com/oauth2/v1/",
client_kwargs={"scope": "openid email profile"},
)


@router.get("/login")
async def login_via_google(request: Request) -> RedirectResponse:
redirect_uri = request.url_for("auth_callback")
return await google.authorize_redirect(request, redirect_uri)


@router.get("/callback")
async def auth_callback(request: Request) -> RedirectResponse:
token = await google.authorize_access_token(request)
user_info = await google.parse_id_token(request, token)
request.session["user"] = dict(user_info)
return RedirectResponse(url="/profile")
18 changes: 0 additions & 18 deletions www/app/routers/auth/__init__.py

This file was deleted.

19 changes: 0 additions & 19 deletions www/app/routers/auth/api.py

This file was deleted.

99 changes: 0 additions & 99 deletions www/app/routers/auth/github.py

This file was deleted.

64 changes: 0 additions & 64 deletions www/app/routers/auth/google.py

This file was deleted.

43 changes: 0 additions & 43 deletions www/app/routers/auth/test.py

This file was deleted.

4 changes: 2 additions & 2 deletions www/app/routers/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,8 +186,8 @@ async def get_user_info_by_id_endpoint(id: str, crud: Annotated[Crud, Depends(Cr
@router.get("/public/me", response_model=UserPublic)
async def get_my_public_user_info_endpoint(
user: User = Depends(get_session_user_with_read_permission),
) -> UserPublic: # Change return type to UserPublic
return UserPublic(**user.model_dump()) # Return UserPublic instance directly
) -> UserPublic:
return UserPublic(**user.model_dump())


@router.get("/public/{id}", response_model=UserPublic)
Expand Down
1 change: 1 addition & 0 deletions www/app/security/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from typing import Annotated

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2AuthorizationCodeBearer

from www.app.db import Crud
from www.app.errors import ItemNotFoundError, NotAuthenticatedError
Expand Down
Loading

0 comments on commit 0572798

Please sign in to comment.