2023-06-14 22:21:13 +03:00
|
|
|
from datetime import datetime
|
2023-08-21 13:45:32 +03:00
|
|
|
from uuid import UUID
|
2023-06-14 22:21:13 +03:00
|
|
|
|
2023-06-17 00:36:53 +03:00
|
|
|
from fastapi import HTTPException
|
2023-08-03 21:24:42 +03:00
|
|
|
from models.settings import get_supabase_db
|
2023-07-04 18:56:54 +03:00
|
|
|
from models.users import User
|
2023-06-14 22:21:13 +03:00
|
|
|
from pydantic import DateError
|
|
|
|
|
|
|
|
|
2023-06-23 11:36:55 +03:00
|
|
|
async def verify_api_key(
|
|
|
|
api_key: str,
|
2023-07-04 18:56:54 +03:00
|
|
|
) -> bool:
|
2023-06-14 22:21:13 +03:00
|
|
|
try:
|
|
|
|
# Use UTC time to avoid timezone issues
|
|
|
|
current_date = datetime.utcnow().date()
|
2023-08-03 21:24:42 +03:00
|
|
|
supabase_db = get_supabase_db()
|
2023-08-21 13:45:32 +03:00
|
|
|
result = supabase_db.get_active_api_key(UUID(api_key))
|
2023-08-02 00:03:47 +03:00
|
|
|
|
2023-06-14 22:21:13 +03:00
|
|
|
if result.data is not None and len(result.data) > 0:
|
2023-06-20 10:54:23 +03:00
|
|
|
api_key_creation_date = datetime.strptime(
|
|
|
|
result.data[0]["creation_time"], "%Y-%m-%dT%H:%M:%S"
|
|
|
|
).date()
|
2023-06-14 22:21:13 +03:00
|
|
|
|
2023-07-02 03:19:30 +03:00
|
|
|
# Check if the API key was created in the month of the current date
|
|
|
|
if (api_key_creation_date.month == current_date.month) and (
|
|
|
|
api_key_creation_date.year == current_date.year
|
|
|
|
):
|
2023-06-14 22:21:13 +03:00
|
|
|
return True
|
|
|
|
return False
|
|
|
|
except DateError:
|
|
|
|
return False
|
2023-06-20 10:54:23 +03:00
|
|
|
|
|
|
|
|
2023-06-23 11:36:55 +03:00
|
|
|
async def get_user_from_api_key(
|
|
|
|
api_key: str,
|
2023-07-04 18:56:54 +03:00
|
|
|
) -> User:
|
2023-08-03 21:24:42 +03:00
|
|
|
supabase_db = get_supabase_db()
|
2023-06-23 11:36:55 +03:00
|
|
|
|
2023-06-14 22:21:13 +03:00
|
|
|
# Lookup the user_id from the api_keys table
|
2023-08-21 13:45:32 +03:00
|
|
|
user_id_data = supabase_db.get_user_id_by_api_key(UUID(api_key))
|
2023-06-20 10:54:23 +03:00
|
|
|
|
|
|
|
if not user_id_data.data:
|
|
|
|
raise HTTPException(status_code=400, detail="Invalid API key.")
|
|
|
|
|
|
|
|
user_id = user_id_data.data[0]["user_id"]
|
2023-06-14 22:21:13 +03:00
|
|
|
|
2023-06-20 10:54:23 +03:00
|
|
|
# Lookup the email from the users table. Todo: remove and use user_id for credentials
|
2023-08-03 21:24:42 +03:00
|
|
|
user_email_data = supabase_db.get_user_email(user_id)
|
2023-07-04 18:56:54 +03:00
|
|
|
email = user_email_data.data[0]["email"] if user_email_data.data else None
|
|
|
|
|
|
|
|
return User(email=email, id=user_id)
|