2023-06-14 22:21:13 +03:00
|
|
|
from datetime import datetime
|
|
|
|
|
2023-06-17 00:36:53 +03:00
|
|
|
from fastapi import HTTPException
|
2023-06-23 11:36:55 +03:00
|
|
|
from models.settings import common_dependencies
|
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-06-23 11:36:55 +03:00
|
|
|
commons = common_dependencies()
|
2023-06-20 10:54:23 +03:00
|
|
|
result = (
|
|
|
|
commons["supabase"]
|
|
|
|
.table("api_keys")
|
|
|
|
.select("api_key", "creation_time")
|
|
|
|
.filter("api_key", "eq", api_key)
|
|
|
|
.filter("is_active", "eq", True)
|
|
|
|
.execute()
|
|
|
|
)
|
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-06-23 11:36:55 +03:00
|
|
|
commons = common_dependencies()
|
|
|
|
|
2023-06-14 22:21:13 +03:00
|
|
|
# Lookup the user_id from the api_keys table
|
2023-06-20 10:54:23 +03:00
|
|
|
user_id_data = (
|
|
|
|
commons["supabase"]
|
|
|
|
.table("api_keys")
|
|
|
|
.select("user_id")
|
|
|
|
.filter("api_key", "eq", api_key)
|
|
|
|
.execute()
|
|
|
|
)
|
|
|
|
|
|
|
|
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
|
|
|
|
user_email_data = (
|
|
|
|
commons["supabase"]
|
|
|
|
.table("users")
|
|
|
|
.select("email")
|
|
|
|
.filter("user_id", "eq", user_id)
|
|
|
|
.execute()
|
|
|
|
)
|
2023-06-14 22:21:13 +03:00
|
|
|
|
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)
|