Skip to content

Commit

Permalink
add depdency injection to all routes
Browse files Browse the repository at this point in the history
  • Loading branch information
Suraj1089 committed Feb 3, 2024
1 parent a0d0910 commit fbc503d
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 30 deletions.
21 changes: 16 additions & 5 deletions ai-interviewer/app/api/deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="users/token")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="users/login")


def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
Expand All @@ -18,10 +18,21 @@ def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = supabase.auth.get_user(token).model_dump()
username: str = payload['user']['id']
if username is None:
user = supabase.auth.get_user(token).model_dump()
if user is None:
raise credentials_exception
return username
return {'id': user['user']['id']}
except JWTError:
raise credentials_exception


def get_current_active_user(current_user: dict = Depends(get_current_user)):
if not current_user:
raise HTTPException(status_code=403, detail='Unauthorized')
# fetch user from data from profile table using user_id
print(current_user)
data, count = supabase.table('profile').select(
"*").eq('user_id', current_user['id']).execute()
if not data:
raise HTTPException(status_code=404, detail='User not found')
return data[1][0]
16 changes: 10 additions & 6 deletions ai-interviewer/app/api/endpoints/meetings.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import base64

import requests
from app.api.deps import get_current_user
from app.api.deps import get_current_active_user, get_current_user
from app.core.session import supabase
from app.schemas.requests import InterviewCreateRequest
from app.schemas.responses import InterviewCreateResponse, UserResponse
Expand All @@ -15,22 +15,26 @@
@router.post("/", response_model=InterviewCreateResponse)
async def create_interview(
interview: InterviewCreateRequest,
current_user: str = Depends(get_current_active_user)
):
try:
interview = interview.model_dump()
interview['hr'] = current_user['user_id']
data, count = supabase.table('interviews').insert(
interview.model_dump()).execute()
interview).execute()
return data[1][0]
except Exception as e:
return JSONResponse(content={"message": f"Unexpected Error. Try Again", "error": str(e)}, status_code=400)


@router.get("/")
async def get_interviews(current_user: str = Depends(get_current_user)):
async def get_interviews(current_user: str = Depends(get_current_active_user)):
print(current_user)
try:
data, count = supabase.table('interviews').select('*').execute()
print(count)
return data
# fetch interviews from data from interviews table using user_id
data, count = supabase.table('interviews').select(
"*").eq(str(current_user['role']), current_user['user_id']).execute()
return data[1]
except Exception as e:
return JSONResponse(content={"message": f"Unexpected Error. Try Again", "error": str(e)}, status_code=401)

Expand Down
25 changes: 9 additions & 16 deletions ai-interviewer/app/api/endpoints/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from typing import Annotated

import requests
from app.api.deps import get_current_user
from app.api.deps import get_current_active_user, get_current_user
from app.core.session import supabase
from app.schemas.requests import (
UserCreateRequest,
Expand Down Expand Up @@ -46,25 +46,13 @@ async def register_new_user(
res = supabase.auth.sign_up(new_user.model_dump()).model_dump()
create_profile(UserProfileCreateRequest(
user_id=res['user']['id'], first_name=new_user.first_name, last_name=new_user.last_name))
return UserResponse(access_token=res['session']['access_token'], refresh_token=res['session']['refresh_token'])
return UserResponse(id=res['user']['id'], access_token=res['session']['access_token'], refresh_token=res['session']['refresh_token'])
except AuthApiError as e:
return JSONResponse(content={"message": f"User already exist with {new_user.email}", "error": str(e)}, status_code=401)
except Exception as e:
return JSONResponse(content={"message": f"Unexpected Error. Try Again", "error": str(e)}, status_code=401)


@router.post("/login", response_model=UserResponse)
async def login(
new_user: UserLoginRequest,
):
try:
res = supabase.auth.sign_in_with_password(
new_user.model_dump()).model_dump()
return UserResponse(access_token=res['session']['access_token'], refresh_token=res['session']['refresh_token'])
except AuthApiError as e:
return JSONResponse(content={"message": f"User does not exist with {new_user.email}", "error": str(e)}, status_code=401)


@router.post("/profile")
async def create_user_profile(
user: UserProfileCreateRequest,
Expand Down Expand Up @@ -108,7 +96,7 @@ async def update_user_profile(
return JSONResponse(content={"message": f"Unexpected Error. Try Again", "error": str(e)}, status_code=401)


@router.post("/token")
@router.post("/login", response_model=UserResponse)
async def login_for_access_token(
form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):
user = supabase.auth.sign_in_with_password({
Expand All @@ -122,4 +110,9 @@ async def login_for_access_token(
headers={"WWW-Authenticate": "Bearer"},
)

return UserResponse(access_token=user['session']['access_token'], refresh_token=user['session']['refresh_token'])
return UserResponse(id=user['user']['id'], access_token=user['session']['access_token'], refresh_token=user['session']['refresh_token'])


@router.get('/users/me')
def get_user_me(current_user: dict = Depends(get_current_active_user)):
return current_user
4 changes: 1 addition & 3 deletions ai-interviewer/app/schemas/requests.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from datetime import datetime
from typing import List, Literal

from typing import Dict
from pydantic import BaseModel, EmailStr, Field, ValidationError, field_validator


Expand All @@ -13,7 +13,6 @@ class UserCreateRequest(BaseUserRequest):
first_name: str
last_name: str
role: Literal['candidate', 'hr'] = 'candidate'
profile: int | str | EmailStr | None = None


class UserLoginRequest(BaseUserRequest):
Expand Down Expand Up @@ -74,7 +73,6 @@ class InterviewBaseRequest(BaseModel):
class InterviewCreateRequest(InterviewBaseRequest):
start_datetime: datetime | str
end_datetime: datetime | str
hr: str
candidate: str
status: Literal['scheduled', 'completed',
'cancelled', 'live'] = 'scheduled'
Expand Down
1 change: 1 addition & 0 deletions ai-interviewer/app/schemas/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ class BaseResponse(BaseModel):


class UserResponse(BaseResponse):
id: str
access_token: str
refresh_token: str

Expand Down

0 comments on commit fbc503d

Please sign in to comment.