Skip to content

Commit 01499cc

Browse files
committed
refactor: migrate CoderAPI configuration to centralized config module
- Replaced dotenv loading in CoderAPI with centralized configuration from config.py, enhancing consistency and maintainability. - Updated CoderAPI initialization to use environment variables directly from the config module. - Adjusted error messages to reflect the new configuration approach, improving clarity for required variables. - Streamlined imports across various modules to utilize the new configuration structure, promoting better organization.
1 parent d1756da commit 01499cc

File tree

5 files changed

+52
-44
lines changed

5 files changed

+52
-44
lines changed

src/backend/coder.py

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,22 @@
11
import os
22
import requests
3-
from dotenv import load_dotenv
3+
from config import CODER_API_KEY, CODER_URL, CODER_TEMPLATE_ID, CODER_DEFAULT_ORGANIZATION, CODER_WORKSPACE_NAME
44

55
class CoderAPI:
66
"""
7-
A class for interacting with the Coder API using credentials from .env file
7+
A class for interacting with the Coder API using credentials from config
88
"""
99

1010
def __init__(self):
11-
# Load environment variables from .env file
12-
load_dotenv()
11+
# Get configuration from config
12+
self.api_key = CODER_API_KEY
13+
self.coder_url = CODER_URL
14+
self.template_id = CODER_TEMPLATE_ID
15+
self.default_organization_id = CODER_DEFAULT_ORGANIZATION
1316

14-
# Get configuration from environment variables
15-
self.api_key = os.getenv("CODER_API_KEY")
16-
self.coder_url = os.getenv("CODER_URL")
17-
self.user_id = os.getenv("USER_ID")
18-
self.template_id = os.getenv("CODER_TEMPLATE_ID")
19-
self.default_organization_id = os.getenv("CODER_DEFAULT_ORGANIZATION")
20-
21-
# Check if required environment variables are set
17+
# Check if required configuration variables are set
2218
if not self.api_key or not self.coder_url:
23-
raise ValueError("CODER_API_KEY and CODER_URL must be set in .env file")
19+
raise ValueError("CODER_API_KEY and CODER_URL must be set in environment variables")
2420

2521
# Set up common headers for API requests
2622
self.headers = {
@@ -56,9 +52,9 @@ def create_workspace(self, user_id, parameter_values=None):
5652
template_id = self.template_id
5753

5854
if not template_id:
59-
raise ValueError("template_id must be provided or TEMPLATE_ID must be set in .env")
55+
raise ValueError("template_id must be provided or TEMPLATE_ID must be set in environment variables")
6056

61-
name = os.getenv("CODER_WORKSPACE_NAME", "ubuntu")
57+
name = CODER_WORKSPACE_NAME
6258

6359
# Prepare the request data
6460
data = {
@@ -201,7 +197,7 @@ def get_workspace_status_for_user(self, username):
201197
Returns:
202198
dict: Workspace status data if found, None otherwise
203199
"""
204-
workspace_name = os.getenv("CODER_WORKSPACE_NAME", "ubuntu")
200+
workspace_name = CODER_WORKSPACE_NAME
205201

206202
endpoint = f"{self.coder_url}/api/v2/users/{username}/workspace/{workspace_name}"
207203
response = requests.get(endpoint, headers=self.headers)
@@ -282,4 +278,4 @@ def stop_workspace(self, workspace_id):
282278
headers['Content-Type'] = 'application/json'
283279
response = requests.post(endpoint, headers=headers, json=data)
284280
response.raise_for_status()
285-
return response.json()
281+
return response.json()

src/backend/config.py

Lines changed: 28 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,29 +7,46 @@
77
from typing import Optional, Dict, Any, Tuple
88
from dotenv import load_dotenv
99

10+
# Load environment variables once
1011
load_dotenv()
1112

13+
# ===== Application Configuration =====
1214
STATIC_DIR = os.getenv("STATIC_DIR")
1315
ASSETS_DIR = os.getenv("ASSETS_DIR")
16+
FRONTEND_URL = os.getenv('FRONTEND_URL')
1417

15-
OIDC_CONFIG = {
16-
'client_id': os.getenv('OIDC_CLIENT_ID'),
17-
'client_secret': os.getenv('OIDC_CLIENT_SECRET'),
18-
'server_url': os.getenv('OIDC_SERVER_URL'),
19-
'realm': os.getenv('OIDC_REALM'),
20-
'redirect_uri': os.getenv('REDIRECT_URI'),
21-
'frontend_url': os.getenv('FRONTEND_URL')
22-
}
18+
# ===== PostHog Configuration =====
19+
POSTHOG_API_KEY = os.getenv("VITE_PUBLIC_POSTHOG_KEY")
20+
POSTHOG_HOST = os.getenv("VITE_PUBLIC_POSTHOG_HOST")
21+
22+
# ===== OIDC Configuration =====
23+
OIDC_CLIENT_ID = os.getenv('OIDC_CLIENT_ID')
24+
OIDC_CLIENT_SECRET = os.getenv('OIDC_CLIENT_SECRET')
25+
OIDC_SERVER_URL = os.getenv('OIDC_SERVER_URL')
26+
OIDC_REALM = os.getenv('OIDC_REALM')
27+
OIDC_REDIRECT_URI = os.getenv('REDIRECT_URI')
28+
29+
# ===== Redis Configuration =====
30+
REDIS_HOST = os.getenv('REDIS_HOST', 'localhost')
31+
REDIS_PASSWORD = os.getenv('REDIS_PASSWORD', None)
32+
REDIS_PORT = int(os.getenv('REDIS_PORT', 6379))
2333

2434
# Redis connection
2535
redis_client = redis.Redis(
26-
host=os.getenv('REDIS_HOST', 'localhost'),
27-
password=os.getenv('REDIS_PASSWORD', None),
28-
port=int(os.getenv('REDIS_PORT', 6379)),
36+
host=REDIS_HOST,
37+
password=REDIS_PASSWORD,
38+
port=REDIS_PORT,
2939
db=0,
3040
decode_responses=True
3141
)
3242

43+
# ===== Coder API Configuration =====
44+
CODER_API_KEY = os.getenv("CODER_API_KEY")
45+
CODER_URL = os.getenv("CODER_URL")
46+
CODER_TEMPLATE_ID = os.getenv("CODER_TEMPLATE_ID")
47+
CODER_DEFAULT_ORGANIZATION = os.getenv("CODER_DEFAULT_ORGANIZATION")
48+
CODER_WORKSPACE_NAME = os.getenv("CODER_WORKSPACE_NAME", "ubuntu")
49+
3350
# Session management functions
3451
def get_session(session_id: str) -> Optional[Dict[str, Any]]:
3552
"""Get session data from Redis"""

src/backend/main.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,9 @@
88
from fastapi.responses import FileResponse
99
from fastapi.middleware.cors import CORSMiddleware
1010
from fastapi.staticfiles import StaticFiles
11-
from dotenv import load_dotenv
1211

1312
from database import init_db
14-
from config import STATIC_DIR, ASSETS_DIR
13+
from config import STATIC_DIR, ASSETS_DIR, POSTHOG_API_KEY, POSTHOG_HOST
1514
from dependencies import UserSession, optional_auth
1615
from routers.auth_router import auth_router
1716
from routers.user_router import user_router
@@ -21,11 +20,7 @@
2120
from database.service import TemplatePadService
2221
from database.database import async_session
2322

24-
load_dotenv()
25-
26-
POSTHOG_API_KEY = os.environ.get("VITE_PUBLIC_POSTHOG_KEY")
27-
POSTHOG_HOST = os.environ.get("VITE_PUBLIC_POSTHOG_HOST")
28-
23+
# Initialize PostHog if API key is available
2924
if POSTHOG_API_KEY:
3025
posthog.project_api_key = POSTHOG_API_KEY
3126
posthog.host = POSTHOG_HOST

src/backend/routers/auth_router.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
from fastapi.responses import RedirectResponse, FileResponse, JSONResponse
66
import os
77

8-
from config import get_auth_url, get_token_url, OIDC_CONFIG, set_session, delete_session, STATIC_DIR, get_session
8+
from config import (get_auth_url, get_token_url, set_session, delete_session, get_session,
9+
FRONTEND_URL, OIDC_CLIENT_ID, OIDC_CLIENT_SECRET, OIDC_SERVER_URL, OIDC_REALM, OIDC_REDIRECT_URI, STATIC_DIR)
910
from dependencies import get_coder_api
1011
from coder import CoderAPI
1112

@@ -47,10 +48,10 @@ async def callback(
4748
get_token_url(),
4849
data={
4950
'grant_type': 'authorization_code',
50-
'client_id': OIDC_CONFIG['client_id'],
51-
'client_secret': OIDC_CONFIG['client_secret'],
51+
'client_id': OIDC_CLIENT_ID,
52+
'client_secret': OIDC_CLIENT_SECRET,
5253
'code': code,
53-
'redirect_uri': OIDC_CONFIG['redirect_uri']
54+
'redirect_uri': OIDC_REDIRECT_URI
5455
}
5556
)
5657

@@ -91,9 +92,8 @@ async def logout(request: Request):
9192
delete_session(session_id)
9293

9394
# Create the Keycloak logout URL with redirect back to our app
94-
logout_url = f"{OIDC_CONFIG['server_url']}/realms/{OIDC_CONFIG['realm']}/protocol/openid-connect/logout"
95-
redirect_uri = OIDC_CONFIG['frontend_url'] # Match the frontend redirect URI
96-
full_logout_url = f"{logout_url}?id_token_hint={id_token}&post_logout_redirect_uri={redirect_uri}"
95+
logout_url = f"{OIDC_SERVER_URL}/realms/{OIDC_REALM}/protocol/openid-connect/logout"
96+
full_logout_url = f"{logout_url}?id_token_hint={id_token}&post_logout_redirect_uri={FRONTEND_URL}"
9797

9898
# Create a redirect response to Keycloak's logout endpoint
9999
response = JSONResponse({"status": "success", "logout_url": full_logout_url})

src/backend/routers/user_router.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import posthog
55
from fastapi import APIRouter, Depends, HTTPException
66

7-
from config import redis_client, OIDC_CONFIG
7+
from config import redis_client, FRONTEND_URL
88
from database import get_user_service
99
from database.service import UserService
1010
from dependencies import UserSession, require_admin, require_auth
@@ -81,7 +81,7 @@ async def get_user_info(
8181

8282
if os.getenv("VITE_PUBLIC_POSTHOG_KEY"):
8383
telemetry = user_data.copy()
84-
telemetry["$current_url"] = OIDC_CONFIG["frontend_url"]
84+
telemetry["$current_url"] = FRONTEND_URL
8585
posthog.identify(distinct_id=user_data["id"], properties=telemetry)
8686

8787
return user

0 commit comments

Comments
 (0)