Skip to content

#140854 #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 16 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,23 +95,26 @@ At the moment, there are 4 types of message history management available for LLM

4. Copy `.env_example` as `.env` and fill in required fields

5. Generate encryption key with:
```
poetry run generate_key
```

5. Setting up credentials:
1. Copy `mint_agent/credentials.json_example` as `mint_agent/credentials.json`.

2. Fill in the required fields:
Open mint_agent/credentials.json in a text editor and replace the placeholder values: `<user_id>`, `<mint_user_id>`, `<client_id>`, `<client_secret>` with your actual information.
* `_id`: The unique identifier for the user in the Agent mongoDB database.
* `mint_user_id`: The user’s ID within the MintHCM system.
* `client_id`: The API client ID for accessing MintHCM.
* `secret`: The API secret key associated with the client ID.
1. Follow this <a href="https://minthcm.org/support/how-to-use-mint-api/" target="_blank">instruction</a> on how to get `client_id` and `secret` for your user.

1. Run script to add user credentials to agent database:
```
poetry run generate_credentials
```

* `user name`: The user_name used in MintHCM
* `mint_user_id`: The user’s ID within the MintHCM system.
* `client_id`: The API client ID for accessing MintHCM.
* `client secret`: The API secret key associated with the client ID.


Follow this <a href="https://minthcm.org/support/how-to-use-mint-api/" target="_blank">instruction</a> on how to get `client_id` and `secret` for your user.

2. Run script to populate database:
```sh
poetry run generate_credentials
```

### MintHCM Agent package

Expand Down
5 changes: 4 additions & 1 deletion mint_agent/agent_api/CredentialManager.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os

from cryptography.fernet import Fernet
from dotenv import load_dotenv
from pymongo import MongoClient

Expand Down Expand Up @@ -48,6 +49,8 @@ def get_system_credentials(
and credential type or tuple of None if not found or error occurred.

"""
KEY = os.getenv("FERNET_KEY").encode()
f = Fernet(KEY)
try:
match system:
case "MintHCM":
Expand All @@ -74,7 +77,7 @@ def get_system_credentials(
credential = user_data["user_credentials"][0]
client_id = credential["credentials"]["client_id"]
secret = credential["credentials"]["secret"]
return client_id, secret
return client_id, f.decrypt(secret).decode()
raise ValueError("Credentials not found")
case _:
raise ValueError(f"System '{system}' not supported")
Expand Down
16 changes: 0 additions & 16 deletions mint_agent/credentials.json_example

This file was deleted.

98 changes: 76 additions & 22 deletions mint_agent/utils/generate_credentials.py
Original file line number Diff line number Diff line change
@@ -1,42 +1,96 @@
import json
import os

from dotenv import load_dotenv
import inquirer
from cryptography.fernet import Fernet
from dotenv import load_dotenv, set_key
from pymongo import MongoClient
from termcolor import colored

load_dotenv()

def generate_credentials():
try:
load_dotenv()

def generate_encryption_key():
key = os.getenv("FERNET_KEY")
if key:
print("Encryption key already exists in .env file")
return
key = Fernet.generate_key()
set_key(".env", "FERNET_KEY", key.decode())
print("Encryption key generated and saved to .env file")


def connect_to_db():
try:
db_uri = os.getenv("MONGO_URI")
db_name = os.getenv("MONGO_DB_NAME")
client = MongoClient(db_uri)
db = client[db_name]
return db
except Exception as e:
raise ConnectionError(f"Failed to connect to database: {e}")

current_dir = os.path.dirname(os.path.abspath(__file__))
credential_path = os.path.join(current_dir, "../credentials.json")

with open(credential_path, encoding="UTF-8") as f:
credentials = json.load(f)
def collect_user_data():
KEY = os.getenv("FERNET_KEY").encode()
user_id = inquirer.text(message="Enter user name")
mint_user_id = inquirer.text(message="Enter user id from MintHCM")

client = MongoClient(db_uri)
db = client[db_name]
print(f"Generating credentials in {db_name} database")
credentials = []
add_credentials = inquirer.confirm(
message=f"Add system credentials for {colored(user_id,"yellow")}?",
default=False,
)

for user in credentials:
collection_name = user["_id"]
collection = db[collection_name]
if add_credentials:
client_id = inquirer.text(message="Enter API client_id")
secret = inquirer.text(message="Enter API client secret")

query = {"_id": user["_id"], "auth_token": user["mint_user_id"]}
f = Fernet(KEY)
secret = f.encrypt(secret.encode())

credentials.append(
{
"system": "MintHCM",
"credential_type": "APIv8",
"credentials": {
"client_id": client_id,
"secret": secret,
},
}
)

return {
"_id": user_id,
"mint_user_id": mint_user_id,
"user_credentials": credentials,
}


def generate_credentials():
db = connect_to_db()

while True:
user_data = collect_user_data()

try:
collection_name = user_data["_id"]
collection = db[collection_name]
query = {"_id": user_data["_id"], "mint_user_id": user_data["mint_user_id"]}

credentials_to_save = (
user["user_credentials"] if "user_credentials" in user else {}
user_data["user_credentials"] if "user_credentials" in user_data else {}
)

update = {"$set": {"user_credentials": credentials_to_save}}

collection.update_one(query, update, upsert=True)
print(f"Credentials generated for user: {user['_id']}")
print(f"Credentials generated for user: {user_data['_id']}")
except Exception as e:
print(f"Error while generating credentials: {e}")

client.close()
except Exception as e:
print(f"Error while generating credentials: {e}")
add_more_users = inquirer.confirm(
message="Add credentials for another user?", default=False
)
if not add_more_users:
break

db.client.close()
Loading