From bd857ae015a95f4e40f4cda5b05820b7eb0dd6fa Mon Sep 17 00:00:00 2001 From: michael Date: Wed, 12 Nov 2025 16:27:59 -0600 Subject: [PATCH] extracted all domains, URLS, secrets, etc. to .env and wrote a deploy script to deploy on server --- .env.example | 29 +++ .gitignore | 2 + CLAUDE.md | 57 ++++- README.md | 39 ++- backend/app.py | 11 +- deploy.sh | 478 +++++++++++++++++++++++++++++++++++ email_analysis.py | 3 +- frontend/src/authConfig.js | 8 +- frontend/src/services/api.js | 11 +- frontend/vite.config.js | 14 +- run.sh | 10 + 11 files changed, 636 insertions(+), 26 deletions(-) create mode 100644 .env.example create mode 100755 deploy.sh diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..1c78e93 --- /dev/null +++ b/.env.example @@ -0,0 +1,29 @@ +# Domain Configuration +# The domain where your application will be deployed (without protocol) +DOMAIN=yourdomain.com + +# The base path for the application (must start and end with /) +BASE_PATH=/dashboard/ + +# Azure AD Configuration +# Get these values from your Azure AD app registration +# Portal: https://portal.azure.com > Azure Active Directory > App registrations +AZURE_TENANT_ID=your-tenant-id-here +AZURE_CLIENT_ID=your-client-id-here + +# Backend Configuration +# Port on which the backend server will run +BACKEND_PORT=5001 + +# Make.com Webhook +# The webhook URL that provides your data +MAKE_WEBHOOK_URL=https://hook.eu1.make.celonis.com/your-webhook-id + +# Frontend Build Configuration (used by Vite) +# These VITE_ prefixed variables are embedded at build time +# They should match the values above +VITE_DOMAIN=yourdomain.com +VITE_BASE_PATH=/dashboard/ +VITE_BACKEND_PORT=5001 +VITE_AZURE_TENANT_ID=your-tenant-id-here +VITE_AZURE_CLIENT_ID=your-client-id-here diff --git a/.gitignore b/.gitignore index 4df56fd..4f903d5 100644 --- a/.gitignore +++ b/.gitignore @@ -59,6 +59,8 @@ frontend/.vite/ .env.test.local .env.production.local *.env +# Keep .env.example tracked +!.env.example # IDE / Editor .vscode/ diff --git a/CLAUDE.md b/CLAUDE.md index 8823474..559f05d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -20,11 +20,34 @@ Oliver Agency Reporting Module - A web-based analytics dashboard for displaying - Filtering happens client-side after data fetch - CSV export uses PapaParse library +## Setup + +### Environment Configuration + +1. Copy the example environment file: +```bash +cp .env.example .env +``` + +2. Edit `.env` and configure the following: + - `DOMAIN`: Your deployment domain + - `BASE_PATH`: Your application path (keep `/dashboard/` or change as needed) + - `AZURE_TENANT_ID`: Your Azure AD tenant ID (from Azure portal) + - `AZURE_CLIENT_ID`: Your Azure AD application ID (from Azure portal) + - `MAKE_WEBHOOK_URL`: Your Make.com webhook URL + - Duplicate the above values to their `VITE_` prefixed equivalents + +3. Register your Azure AD application: + - Go to Azure Portal > Azure Active Directory > App registrations + - Create a new registration or update an existing one + - Add redirect URIs for your domain (e.g., `https://yourdomain.com/dashboard/`) + - Note the Tenant ID and Client ID for your `.env` file + ## Development Commands ### Full Application ```bash -# Start both backend and frontend simultaneously +# Start both backend and frontend simultaneously (loads .env automatically) ./run.sh ``` @@ -65,19 +88,35 @@ npm run preview # Preview production build ## Environment Configuration -**API URLs:** -- Development: `http://localhost:5001/api` -- Production: `https://baic.oliver.solutions/dashboard/back/api` +The application is configured using environment variables defined in a `.env` file at the project root. Copy `.env.example` to `.env` and configure for your deployment. -**Environment Variables:** -- `MAKE_WEBHOOK_URL`: Make.com webhook endpoint (defaults to production URL) +**Required Environment Variables:** + +**Domain & Path:** +- `DOMAIN`: Your deployment domain (e.g., `yourdomain.com`) +- `BASE_PATH`: Base path for the application (e.g., `/dashboard/`) + +**Azure AD Configuration:** +- `AZURE_TENANT_ID`: Azure AD tenant identifier +- `AZURE_CLIENT_ID`: Azure AD application (client) identifier + +**Backend Configuration:** +- `BACKEND_PORT`: Port for the backend server (default: `5001`) +- `MAKE_WEBHOOK_URL`: Make.com webhook endpoint for data source + +**Frontend Configuration (Vite):** +- `VITE_DOMAIN`: Same as DOMAIN (for frontend build) +- `VITE_BASE_PATH`: Same as BASE_PATH (for frontend build) +- `VITE_AZURE_TENANT_ID`: Same as AZURE_TENANT_ID (for frontend auth) +- `VITE_AZURE_CLIENT_ID`: Same as AZURE_CLIENT_ID (for frontend auth) + +**API URLs (constructed from environment variables):** +- Development: `http://localhost:{BACKEND_PORT}/api` +- Production: `https://{DOMAIN}{BASE_PATH}back/api` ## Authentication **Azure AD (MSAL) Configuration:** -- Tenant ID: `e519c2e6-bc6d-4fdf-8d9c-923c2f002385` -- Client ID: `014547f2-21c1-4245-881f-97f49543d963` -- Redirect URI: `https://baic.oliver.solutions/dashboard/` **Frontend Authentication:** - Uses `@azure/msal-react` and `@azure/msal-browser` diff --git a/README.md b/README.md index b5d8c78..3758741 100644 --- a/README.md +++ b/README.md @@ -7,8 +7,40 @@ A web-based reporting module to display usage analytics for conversations and me - `/backend`: Python Flask backend API - `/frontend`: React + Vite frontend application +## Environment Setup + +Before running the application, you need to configure environment variables: + +1. Copy the example environment file: + ```bash + cp .env.example .env + ``` + +2. Edit `.env` with your configuration: + - **DOMAIN**: Your deployment domain (e.g., `yourdomain.com`) + - **BASE_PATH**: Application base path (default: `/dashboard/`) + - **AZURE_TENANT_ID**: Azure AD tenant identifier + - **AZURE_CLIENT_ID**: Azure AD application (client) identifier + - **BACKEND_PORT**: Backend server port (default: `5001`) + - **MAKE_WEBHOOK_URL**: Make.com webhook endpoint + - **VITE_*** variables: Duplicate the above values with `VITE_` prefix for frontend + +3. Azure AD Setup: + - Create an app registration in Azure Portal + - Add redirect URIs for your deployment domain + - Copy the Tenant ID and Client ID to your `.env` file + ## Getting Started +### Quick Start (Recommended) + +Run both backend and frontend together: +```bash +./run.sh +``` + +This script automatically loads environment variables from `.env` and starts both servers. + ### Backend 1. Navigate to the backend directory: @@ -26,12 +58,15 @@ A web-based reporting module to display usage analytics for conversations and me pip install -r requirements.txt ``` -4. Start the development server: +4. Load environment variables and start the development server: ``` + # Load environment variables + set -a && source ../.env && set +a + # Start server python app.py ``` -The API will be available at http://localhost:5001. +The API will be available at `http://localhost:{BACKEND_PORT}` (default: 5001). ### Frontend diff --git a/backend/app.py b/backend/app.py index 994fcf3..c783b11 100644 --- a/backend/app.py +++ b/backend/app.py @@ -30,8 +30,8 @@ app.config["APPLICATION_ROOT"] = application_root MAKE_WEBHOOK_URL = os.environ.get("MAKE_WEBHOOK_URL", "https://hook.eu1.make.celonis.com/h8gjldwnp4u5cvc0io474zq4u7vwb9zw") # Azure AD configuration -TENANT_ID = "e519c2e6-bc6d-4fdf-8d9c-923c2f002385" -CLIENT_ID = "014547f2-21c1-4245-881f-97f49543d963" +TENANT_ID = os.environ.get("AZURE_TENANT_ID", "e519c2e6-bc6d-4fdf-8d9c-923c2f002385") +CLIENT_ID = os.environ.get("AZURE_CLIENT_ID", "014547f2-21c1-4245-881f-97f49543d963") JWKS_URL = f"https://login.microsoftonline.com/{TENANT_ID}/discovery/v2.0/keys" def get_public_keys(): @@ -333,10 +333,11 @@ if __name__ == "__main__": # Configure Hypercorn config = Config() - config.bind = ["0.0.0.0:5001"] # Port for backend + port = os.environ.get("BACKEND_PORT", "5001") + config.bind = [f"0.0.0.0:{port}"] # Port for backend config.use_reloader = False config.root_path = application_root - + # Run the application with Hypercorn - logger.warning("Starting Oliver Agency Reporting Backend with Hypercorn on port 5001") + logger.warning(f"Starting Oliver Agency Reporting Backend with Hypercorn on port {port}") asyncio.run(serve(app, config)) \ No newline at end of file diff --git a/deploy.sh b/deploy.sh new file mode 100755 index 0000000..917999e --- /dev/null +++ b/deploy.sh @@ -0,0 +1,478 @@ +#!/bin/bash + +################################################################################ +# BAIC Dashboard Deployment Script +# +# This script automates the deployment of the BAIC Dashboard application +# on an Ubuntu server with Apache and systemd. +# +# Prerequisites: +# - Repository cloned to /opt/baic_dashboard +# - .env file configured in repository root +# - Run this script from /opt/baic_dashboard directory +# - Execute with sudo/root privileges +# +# Usage: sudo bash deploy.sh +################################################################################ + +set -e # Exit on any error + +# Color codes for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# Expected deployment directory +EXPECTED_DIR="/opt/baic_dashboard" +SERVICE_NAME="baic-dashboard" +SERVICE_USER="www-data" + +################################################################################ +# Helper Functions +################################################################################ + +print_header() { + echo -e "\n${BLUE}========================================${NC}" + echo -e "${BLUE}$1${NC}" + echo -e "${BLUE}========================================${NC}\n" +} + +print_success() { + echo -e "${GREEN}✓ $1${NC}" +} + +print_error() { + echo -e "${RED}✗ ERROR: $1${NC}" +} + +print_warning() { + echo -e "${YELLOW}⚠ WARNING: $1${NC}" +} + +print_info() { + echo -e "${BLUE}ℹ $1${NC}" +} + +exit_with_error() { + print_error "$1" + exit 1 +} + +################################################################################ +# Pre-flight Checks +################################################################################ + +print_header "Pre-flight Checks" + +# Check if running as root +if [[ $EUID -ne 0 ]]; then + exit_with_error "This script must be run as root (use sudo)" +fi +print_success "Running as root" + +# Check if we're in the correct directory +CURRENT_DIR=$(pwd) +if [[ "$CURRENT_DIR" != "$EXPECTED_DIR" ]]; then + exit_with_error "Script must be run from $EXPECTED_DIR (currently in $CURRENT_DIR)" +fi +print_success "Running from correct directory: $EXPECTED_DIR" + +# Check for required commands +REQUIRED_COMMANDS=("python3" "npm" "systemctl") +for cmd in "${REQUIRED_COMMANDS[@]}"; do + if ! command -v $cmd &> /dev/null; then + exit_with_error "$cmd is not installed. Please install it first." + fi + print_success "$cmd is installed" +done + +# Check if .env file exists +if [[ ! -f ".env" ]]; then + exit_with_error ".env file not found in current directory. Please create it before running this script." +fi +print_success ".env file found" + +# Check if apache2 is installed (warn if not, but don't fail) +if ! command -v apache2 &> /dev/null; then + print_warning "apache2 is not installed. You'll need to install and configure it manually." +else + print_success "apache2 is installed" +fi + +################################################################################ +# Backend Setup +################################################################################ + +print_header "Backend Setup" + +# Create Python virtual environment +print_info "Creating Python virtual environment..." +if [[ -d "venv" ]]; then + print_warning "Virtual environment already exists. Removing and recreating..." + rm -rf venv +fi + +python3 -m venv venv +if [[ $? -ne 0 ]]; then + exit_with_error "Failed to create virtual environment" +fi +print_success "Virtual environment created" + +# Activate virtual environment and install dependencies +print_info "Installing Python dependencies from requirements.txt..." +source venv/bin/activate + +if [[ ! -f "backend/requirements.txt" ]]; then + exit_with_error "backend/requirements.txt not found" +fi + +pip install --upgrade pip > /dev/null 2>&1 +pip install -r backend/requirements.txt +if [[ $? -ne 0 ]]; then + exit_with_error "Failed to install Python dependencies" +fi +print_success "Python dependencies installed" + +# Test that Flask can be imported +python3 -c "import flask" 2>/dev/null +if [[ $? -ne 0 ]]; then + exit_with_error "Flask installation verification failed" +fi +print_success "Flask installation verified" + +deactivate + +# Set ownership to www-data +print_info "Setting ownership to $SERVICE_USER..." +chown -R $SERVICE_USER:$SERVICE_USER venv +chown -R $SERVICE_USER:$SERVICE_USER backend +print_success "Ownership set to $SERVICE_USER" + +################################################################################ +# Frontend Build +################################################################################ + +print_header "Frontend Build" + +# Check if frontend directory exists +if [[ ! -d "frontend" ]]; then + exit_with_error "frontend directory not found" +fi + +cd frontend + +# Install npm dependencies +print_info "Installing npm dependencies..." +npm install +if [[ $? -ne 0 ]]; then + exit_with_error "Failed to install npm dependencies" +fi +print_success "npm dependencies installed" + +# Build frontend +print_info "Building frontend for production (this may take a minute)..." +npm run build +if [[ $? -ne 0 ]]; then + exit_with_error "Frontend build failed" +fi + +# Verify dist directory was created +if [[ ! -d "dist" ]]; then + exit_with_error "Build completed but dist/ directory not found" +fi +print_success "Frontend built successfully" + +cd .. + +################################################################################ +# Frontend Deployment +################################################################################ + +print_header "Frontend Deployment" + +# Prompt user for frontend deployment path +echo -e "${BLUE}Please enter the full path where the frontend files should be deployed${NC}" +echo -e "${BLUE}(e.g., /var/www/html/dashboard or /var/www/mysite.com/dashboard)${NC}" +read -p "Deployment path: " FRONTEND_DEPLOY_PATH + +# Validate input +if [[ -z "$FRONTEND_DEPLOY_PATH" ]]; then + exit_with_error "No deployment path provided" +fi + +# Create directory if it doesn't exist +if [[ ! -d "$FRONTEND_DEPLOY_PATH" ]]; then + print_info "Creating directory: $FRONTEND_DEPLOY_PATH" + mkdir -p "$FRONTEND_DEPLOY_PATH" + if [[ $? -ne 0 ]]; then + exit_with_error "Failed to create deployment directory" + fi +fi + +# Copy frontend files +print_info "Copying frontend files to $FRONTEND_DEPLOY_PATH..." +cp -r frontend/dist/* "$FRONTEND_DEPLOY_PATH/" +if [[ $? -ne 0 ]]; then + exit_with_error "Failed to copy frontend files" +fi +print_success "Frontend files copied" + +# Set ownership and permissions +print_info "Setting ownership and permissions..." +chown -R $SERVICE_USER:$SERVICE_USER "$FRONTEND_DEPLOY_PATH" +find "$FRONTEND_DEPLOY_PATH" -type d -exec chmod 755 {} \; +find "$FRONTEND_DEPLOY_PATH" -type f -exec chmod 644 {} \; +print_success "Ownership and permissions set" + +################################################################################ +# Systemd Service Creation +################################################################################ + +print_header "Systemd Service Setup" + +# Read BACKEND_PORT from .env or use default +BACKEND_PORT=$(grep "^BACKEND_PORT=" .env | cut -d'=' -f2 | tr -d ' ') +if [[ -z "$BACKEND_PORT" ]]; then + BACKEND_PORT="5001" + print_warning "BACKEND_PORT not found in .env, using default: 5001" +else + print_info "Using BACKEND_PORT from .env: $BACKEND_PORT" +fi + +SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service" + +print_info "Creating systemd service file: $SERVICE_FILE" + +cat > "$SERVICE_FILE" << EOF +[Unit] +Description=BAIC Dashboard Backend Service +After=network.target + +[Service] +Type=simple +User=$SERVICE_USER +Group=$SERVICE_USER +WorkingDirectory=$EXPECTED_DIR/backend +EnvironmentFile=$EXPECTED_DIR/.env +ExecStart=$EXPECTED_DIR/venv/bin/python app.py + +# Restart policy +Restart=always +RestartSec=10 + +# Security settings +NoNewPrivileges=true +PrivateTmp=true + +# Logging +StandardOutput=journal +StandardError=journal +SyslogIdentifier=$SERVICE_NAME + +[Install] +WantedBy=multi-user.target +EOF + +if [[ $? -ne 0 ]]; then + exit_with_error "Failed to create systemd service file" +fi +print_success "Systemd service file created" + +################################################################################ +# Service Management +################################################################################ + +print_header "Service Management" + +# Reload systemd daemon +print_info "Reloading systemd daemon..." +systemctl daemon-reload +if [[ $? -ne 0 ]]; then + exit_with_error "Failed to reload systemd daemon" +fi +print_success "Systemd daemon reloaded" + +# Enable service +print_info "Enabling service to start on boot..." +systemctl enable $SERVICE_NAME +if [[ $? -ne 0 ]]; then + exit_with_error "Failed to enable service" +fi +print_success "Service enabled" + +# Start service +print_info "Starting service..." +systemctl start $SERVICE_NAME +if [[ $? -ne 0 ]]; then + print_error "Failed to start service. Check logs with: journalctl -u $SERVICE_NAME -n 50" + exit 1 +fi +print_success "Service started" + +# Wait a moment for service to initialize +sleep 2 + +# Check service status +print_info "Checking service status..." +if systemctl is-active --quiet $SERVICE_NAME; then + print_success "Service is running" + echo "" + systemctl status $SERVICE_NAME --no-pager -l +else + print_error "Service failed to start properly" + print_info "Showing recent logs:" + journalctl -u $SERVICE_NAME -n 20 --no-pager + exit 1 +fi + +################################################################################ +# Apache Configuration Generation +################################################################################ + +print_header "Apache Configuration" + +# Get domain and base path from .env +DOMAIN=$(grep "^DOMAIN=" .env | cut -d'=' -f2 | tr -d ' ') +BASE_PATH=$(grep "^BASE_PATH=" .env | cut -d'=' -f2 | tr -d ' ') + +if [[ -z "$DOMAIN" ]]; then + DOMAIN="yourdomain.com" + print_warning "DOMAIN not found in .env, using placeholder in config" +fi + +if [[ -z "$BASE_PATH" ]]; then + BASE_PATH="/dashboard/" + print_warning "BASE_PATH not found in .env, using default: /dashboard/" +fi + +# Remove trailing slash from BASE_PATH for cleaner config +BASE_PATH_NO_SLASH=${BASE_PATH%/} + +APACHE_CONFIG_FILE="$EXPECTED_DIR/apache-config.conf" + +print_info "Generating Apache configuration: $APACHE_CONFIG_FILE" + +cat > "$APACHE_CONFIG_FILE" << EOF +# Apache Configuration for BAIC Dashboard +# +# Add this configuration to your Apache virtual host file +# (e.g., /etc/apache2/sites-available/000-default.conf or your custom site config) +# +# Required Apache modules (enable with a2enmod): +# - proxy +# - proxy_http +# - headers +# - rewrite +# +# Enable modules: +# sudo a2enmod proxy proxy_http headers rewrite +# sudo systemctl restart apache2 + + + ServerName $DOMAIN + + # SSL Configuration (adjust paths to your certificates) + # SSLEngine on + # SSLCertificateFile /etc/letsencrypt/live/$DOMAIN/fullchain.pem + # SSLCertificateKeyFile /etc/letsencrypt/live/$DOMAIN/privkey.pem + + # Frontend static files + Alias $BASE_PATH_NO_SLASH $FRONTEND_DEPLOY_PATH + + Options -Indexes +FollowSymLinks + AllowOverride All + Require all granted + + # Handle client-side routing (React Router) + + RewriteEngine On + RewriteBase $BASE_PATH_NO_SLASH/ + RewriteRule ^index\.html$ - [L] + RewriteCond %{REQUEST_FILENAME} !-f + RewriteCond %{REQUEST_FILENAME} !-d + RewriteRule . $BASE_PATH_NO_SLASH/index.html [L] + + + + # Backend API reverse proxy + ProxyPreserveHost On + ProxyTimeout 300 + + + ProxyPass http://localhost:$BACKEND_PORT/api + ProxyPassReverse http://localhost:$BACKEND_PORT/api + + # Add headers for proper proxying + RequestHeader set X-Forwarded-Proto "https" + RequestHeader set X-Forwarded-Port "443" + + + # Error and Access logs + ErrorLog \${APACHE_LOG_DIR}/${SERVICE_NAME}-error.log + CustomLog \${APACHE_LOG_DIR}/${SERVICE_NAME}-access.log combined + + +# Optional: Redirect HTTP to HTTPS + + ServerName $DOMAIN + Redirect permanent / https://$DOMAIN/ + +EOF + +if [[ $? -ne 0 ]]; then + print_error "Failed to create Apache configuration file" +else + print_success "Apache configuration file created" +fi + +################################################################################ +# Deployment Complete +################################################################################ + +print_header "Deployment Complete!" + +echo -e "${GREEN}✓ Backend virtual environment created and dependencies installed${NC}" +echo -e "${GREEN}✓ Frontend built and deployed to: $FRONTEND_DEPLOY_PATH${NC}" +echo -e "${GREEN}✓ Systemd service created and started: $SERVICE_NAME${NC}" +echo -e "${GREEN}✓ Apache configuration generated: $APACHE_CONFIG_FILE${NC}" + +echo "" +print_header "Next Steps" + +echo -e "${YELLOW}1. Review the Apache configuration:${NC}" +echo -e " cat $APACHE_CONFIG_FILE" +echo "" +echo -e "${YELLOW}2. Enable required Apache modules:${NC}" +echo -e " sudo a2enmod proxy proxy_http headers rewrite" +echo "" +echo -e "${YELLOW}3. Add the configuration to your Apache virtual host:${NC}" +echo -e " - Edit: /etc/apache2/sites-available/your-site.conf" +echo -e " - Or copy: sudo cp $APACHE_CONFIG_FILE /etc/apache2/sites-available/${SERVICE_NAME}.conf" +echo -e " - Enable: sudo a2ensite ${SERVICE_NAME}" +echo "" +echo -e "${YELLOW}4. Test Apache configuration:${NC}" +echo -e " sudo apache2ctl configtest" +echo "" +echo -e "${YELLOW}5. Reload Apache:${NC}" +echo -e " sudo systemctl reload apache2" +echo "" +echo -e "${YELLOW}6. Configure SSL/TLS certificates (if not already done):${NC}" +echo -e " sudo apt install certbot python3-certbot-apache" +echo -e " sudo certbot --apache -d $DOMAIN" +echo "" + +print_header "Useful Commands" + +echo -e "${BLUE}Service Management:${NC}" +echo -e " sudo systemctl status $SERVICE_NAME # Check service status" +echo -e " sudo systemctl restart $SERVICE_NAME # Restart service" +echo -e " sudo systemctl stop $SERVICE_NAME # Stop service" +echo -e " sudo journalctl -u $SERVICE_NAME -f # View live logs" +echo -e " sudo journalctl -u $SERVICE_NAME -n 100 # View last 100 log lines" +echo "" + +print_success "Deployment script completed successfully!" + +exit 0 diff --git a/email_analysis.py b/email_analysis.py index 1dcb3c9..7745c7d 100644 --- a/email_analysis.py +++ b/email_analysis.py @@ -7,9 +7,10 @@ Pulls data from Make.com endpoint and analyzes unique email addresses for user f import requests import json import re +import os from collections import Counter -MAKE_WEBHOOK_URL = 'https://hook.eu1.make.celonis.com/h8gjldwnp4u5cvc0io474zq4u7vwb9zw' +MAKE_WEBHOOK_URL = os.environ.get('MAKE_WEBHOOK_URL', 'https://hook.eu1.make.celonis.com/h8gjldwnp4u5cvc0io474zq4u7vwb9zw') def fetch_data(data_type): """Fetch data from Make.com endpoint""" diff --git a/frontend/src/authConfig.js b/frontend/src/authConfig.js index c7a7fdb..0a612a2 100644 --- a/frontend/src/authConfig.js +++ b/frontend/src/authConfig.js @@ -1,9 +1,13 @@ import { LogLevel } from '@azure/msal-browser'; +// Get Azure AD configuration from environment variables +const tenantId = import.meta.env.VITE_AZURE_TENANT_ID || 'e519c2e6-bc6d-4fdf-8d9c-923c2f002385'; +const clientId = import.meta.env.VITE_AZURE_CLIENT_ID || '014547f2-21c1-4245-881f-97f49543d963'; + export const msalConfig = { auth: { - clientId: '014547f2-21c1-4245-881f-97f49543d963', - authority: 'https://login.microsoftonline.com/e519c2e6-bc6d-4fdf-8d9c-923c2f002385', + clientId: clientId, + authority: `https://login.microsoftonline.com/${tenantId}`, redirectUri: window.location.origin, postLogoutRedirectUri: window.location.origin, navigateToLoginRequestUrl: false diff --git a/frontend/src/services/api.js b/frontend/src/services/api.js index 8574723..f13b59e 100644 --- a/frontend/src/services/api.js +++ b/frontend/src/services/api.js @@ -4,10 +4,15 @@ import { PublicClientApplication } from '@azure/msal-browser'; // Determine the API URL based on the environment const isDevelopment = import.meta.env.DEV; +// Get configuration from environment variables +const domain = import.meta.env.VITE_DOMAIN || 'baic.oliver.solutions'; +const basePath = import.meta.env.VITE_BASE_PATH || '/dashboard/'; +const backendPort = import.meta.env.VITE_BACKEND_PORT || '5001'; + // In development mode, use the local URL; in production, use the deployed URL -const API_URL = isDevelopment - ? 'http://localhost:5001/api' - : 'https://baic.oliver.solutions/dashboard/back/api'; +const API_URL = isDevelopment + ? `http://localhost:${backendPort}/api` + : `https://${domain}${basePath}back/api`; /** * Get access token from MSAL instance diff --git a/frontend/vite.config.js b/frontend/vite.config.js index f2f73bd..ae3158d 100644 --- a/frontend/vite.config.js +++ b/frontend/vite.config.js @@ -1,8 +1,14 @@ -import { defineConfig } from 'vite' +import { defineConfig, loadEnv } from 'vite' import react from '@vitejs/plugin-react' // https://vite.dev/config/ -export default defineConfig({ - plugins: [react()], - base: '/dashboard/', +export default defineConfig(({ mode }) => { + // Load env file based on `mode` in the current working directory. + // By default, only env variables prefixed with `VITE_` are exposed. + const env = loadEnv(mode, process.cwd(), '') + + return { + plugins: [react()], + base: env.VITE_BASE_PATH || '/dashboard/', + } }) diff --git a/run.sh b/run.sh index d363a7b..b3200f7 100755 --- a/run.sh +++ b/run.sh @@ -1,5 +1,15 @@ #!/bin/bash +# Load environment variables from .env file +if [ -f .env ]; then + echo "Loading environment variables from .env file..." + set -a # automatically export all variables + source .env + set +a +else + echo "Warning: .env file not found. Using default values." +fi + # Start the backend server with Hypercorn echo "Starting backend server with Hypercorn..." cd backend