Skip to content

Commit

Permalink
feat: add token authentication and refactor code
Browse files Browse the repository at this point in the history
  • Loading branch information
IgnacioHeredia committed Nov 5, 2024
1 parent dbef4f6 commit 22bd845
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 60 deletions.
55 changes: 39 additions & 16 deletions ai4papi/routers/v1/catalog/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,22 +22,30 @@
This means you cannot name your modules like those names (eg. tags, detail, etc)
"""

import os
import re
from typing import Tuple, Union
import yaml

import ai4_metadata.validate
from cachetools import cached, TTLCache
from fastapi import HTTPException, Query
from fastapi import Depends, HTTPException, Query
from fastapi.security import HTTPBearer
import requests

from ai4papi import utils


security = HTTPBearer()

JENKINS_TOKEN = os.getenv('PAPI_JENKINS_TOKEN')


class Catalog:

def __init__(self) -> None:
pass

def __init__(self, item_type='item') -> None:
self.item_type = item_type


@cached(cache=TTLCache(maxsize=1024, ttl=6*60*60))
Expand Down Expand Up @@ -80,6 +88,7 @@ def get_filtered_list(
# ValueError: [ValueError('dictionary update sequence element #0 has length 1; 2 is required'), TypeError('vars() argument must have __dict__ attribute')]
return modules


@cached(cache=TTLCache(maxsize=1024, ttl=6*60*60))
def get_summary(
self,
Expand Down Expand Up @@ -246,22 +255,38 @@ def get_metadata(

return metadata

def refresh_metadata_cache_entry(self, item_name: str):
if item_name in self.get_items().keys():
try:
self.get_metadata.cache.pop(item_name, None)
self.get_metadata(item_name)

return {"message": "Cache refreshed successfully"}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
def refresh_metadata_cache_entry(
self,
item_name: str,
authorization=Depends(security),
):
"""
Expire the metadata cache of a given item and recompute new cache value.
"""
# Check if token is valid
if authorization.credentials != JENKINS_TOKEN:
raise HTTPException(
status_code=401,
detail="Invalid authorization token.",
)

else:
# Check if the item is indeed valid
if item_name not in self.get_items().keys():
raise HTTPException(
status_code=400,
detail=f"{item_name} is not an available tool or metadata.",
detail=f"{item_name} is not an available {self.item_type}.",
)


# Refresh cache
try:
self.get_metadata.cache.pop(item_name, None)
self.get_metadata(item_name)
return {"message": "Cache refreshed successfully"}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))


def get_config(
self,
):
Expand Down Expand Up @@ -292,5 +317,3 @@ def retrieve_docker_tags(
)
tags = [i["name"] for i in r["results"]]
return tags


6 changes: 3 additions & 3 deletions ai4papi/routers/v1/catalog/modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def get_config(
return conf


Modules = Catalog()
Modules = Catalog(item_type='module')
Modules.get_items = types.MethodType(get_items, Modules)
Modules.get_config = types.MethodType(get_config, Modules)

Expand Down Expand Up @@ -129,7 +129,7 @@ def get_config(
)

router.add_api_route(
"/refresh",
"/{item_name}/refresh",
Modules.refresh_metadata_cache_entry,
methods=["GET"],
methods=["PUT"],
)
38 changes: 0 additions & 38 deletions ai4papi/routers/v1/catalog/refresh.py

This file was deleted.

6 changes: 3 additions & 3 deletions ai4papi/routers/v1/catalog/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def get_config(
return conf


Tools = Catalog()
Tools = Catalog(item_type='tool')
Tools.get_items = types.MethodType(get_items, Tools)
Tools.get_config = types.MethodType(get_config, Tools)

Expand Down Expand Up @@ -105,7 +105,7 @@ def get_config(
methods=["GET"],
)
router.add_api_route(
"/refresh",
"/{item_name}/refresh",
Tools.refresh_metadata_cache_entry,
methods=["GET"],
methods=["PUT"],
)

0 comments on commit 22bd845

Please sign in to comment.