-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #166 from ArtrenH/main
2023-09-22 2
- Loading branch information
Showing
3 changed files
with
69 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
import abc | ||
import json | ||
import logging | ||
from pathlib import Path | ||
|
||
import pymongo.database | ||
from dotenv.main import DotEnv, find_dotenv | ||
|
||
|
||
class CredsProvider(abc.ABC): | ||
@abc.abstractmethod | ||
def get_creds(self) -> dict: | ||
pass | ||
|
||
|
||
class FileCredsProvider(CredsProvider): | ||
def __init__(self, path: Path): | ||
self.path = path | ||
|
||
def get_creds(self) -> dict: | ||
with open(self.path, "r", encoding="utf-8") as f: | ||
return json.load(f) | ||
|
||
|
||
class MongoDbCredsProvider(CredsProvider): | ||
def __init__(self, collection: pymongo.database.Collection): | ||
self.collection = collection | ||
|
||
def get_creds(self) -> dict: | ||
pipeline = [ | ||
{ | ||
"$sort": {"count": pymongo.DESCENDING} | ||
}, | ||
{ | ||
"$project": { | ||
"count": False, | ||
"comment": False, | ||
} | ||
} | ||
] | ||
|
||
out = self.collection.aggregate(pipeline) | ||
|
||
return {elem["short_name"]: elem for elem in out} | ||
|
||
|
||
def creds_provider_factory(creds_filepath: Path | None) -> CredsProvider: | ||
dotenv = DotEnv(dotenv_path=find_dotenv()) | ||
|
||
if (mongo_uri := dotenv.get("MONGO_URL")) is not None: | ||
collection = pymongo.MongoClient(mongo_uri).get_database("vplan").get_collection("creds") | ||
logging.info("Using MongoDB as credentials source.") | ||
return MongoDbCredsProvider(collection) | ||
else: | ||
logging.debug("No MONGO_URI found in .env file.") | ||
|
||
if creds_filepath.exists(): | ||
logging.info(f"Using {creds_filepath!r} as credentials source.") | ||
return FileCredsProvider(creds_filepath) | ||
else: | ||
logging.debug(f"Creds file {creds_filepath!r} does not exist.") | ||
|
||
raise FileNotFoundError(f"Could not find a credentials source.") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters