added server address
Browse filesFiles changed (6)
119 unmodified lines12012112212312412512616 unmodified lines143144145146147148149119 unmodified lines"http://127.0.0.1:3000","http://127.0.0.1:5000","http://192.168.1.4:3000","https://zelyanoth-lin-cbfcff2.hf.space"],"methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],"allow_headers": ["Content-Type", "Authorization", "X-Requested-With"],16 unmodified lines"http://127.0.0.1:3000","http://127.0.0.1:5000","http://192.168.1.4:3000","https://zelyanoth-lin-cbfcff2.hf.space"]# Add CORS headers specifically for OAuth callback routes119 unmodified lines12012112212312412512616 unmodified lines143144145146147148149119 unmodified lines"http://127.0.0.1:3000","http://127.0.0.1:5000","http://192.168.1.4:3000","http://46.62.218.169"],"methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],"allow_headers": ["Content-Type", "Authorization", "X-Requested-With"],16 unmodified lines"http://127.0.0.1:3000","http://127.0.0.1:5000","http://192.168.1.4:3000","http://46.62.218.169"]# Add CORS headers specifically for OAuth callback routes
92 unmodified lines9394959697989992 unmodified lines'http://127.0.0.1:3000','http://127.0.0.1:5000','http://192.168.1.4:3000','https://zelyanoth-lin-cbfcff2.hf.space']@jwt.token_verification_loader92 unmodified lines9394959697989992 unmodified lines'http://127.0.0.1:3000','http://127.0.0.1:5000','http://192.168.1.4:3000','http://46.62.218.169']@jwt.token_verification_loader
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172# Tech-Spec: Fix API URL Configuration Issue
**Created:** December 23, 2025**Status:** Ready for Development
## Overview
### Problem StatementThe frontend application is configured to use a hardcoded Hugging Face Space URL (`https://zelyanoth-lin-cbfcff2.hf.space`) instead of the user's local server IP address (`http://46.62.218.169/`). This causes API requests to fail with 404 errors when users try to access endpoints like `/api/posts/jobs/{jobId}`.
### SolutionUpdate the frontend environment configuration to use the correct API URL that matches the user's server IP address instead of the hardcoded Hugging Face Space URL.
### Scope (In/Out)
**In Scope:**- Update frontend environment configuration files to use correct API URL- Ensure API requests are made to the user's server IP address (`http://46.62.218.169/`)- Test that API endpoints work correctly after configuration change
**Out Scope:**- Backend server modifications- Database schema changes- UI/UX modifications
## Context for Development
### Codebase Patterns- Frontend uses Vite with environment variables for configuration- API calls are made through axios with a base URL configuration- The project follows a standard React + Flask architecture
### Files to Reference- `frontend/.env.production` - Contains the hardcoded Hugging Face Space URL- `frontend/src/services/apiClient.js` - Contains the API client configuration logic- `frontend/src/services/api.js` - Contains additional API configuration
### Technical Decisions- The API URL should be configurable via environment variables to support different deployment environments- The production environment file should be updated to use the correct server IP address- CORS configuration in the backend already supports multiple origins including local addresses
## Implementation Plan
### Tasks
- [x] Update `frontend/.env.production` to use correct API URL- [x] Verify that the API client properly handles the new URL configuration- [x] Test that API requests are made to the correct server IP address- [x] Verify that job polling endpoints work correctly
### Acceptance Criteria
- [x] AC 1: Given the updated configuration, when a user clicks the button to generate a post, then API requests should be made to `http://46.62.218.169/api/posts/` instead of the Hugging Face Space URL- [x] AC 2: Given the updated configuration, when a user polls for job status, then requests to `/api/posts/jobs/{jobId}` should succeed without 404 errors- [x] AC 3: Given the updated configuration, when the application runs in production mode, then all API calls should use the correct server IP address
## Additional Context
### Dependencies- Frontend build process needs to be run after environment variable changes- Backend server must be accessible at the configured IP address
### Testing Strategy- Test the post generation flow after configuration changes- Verify that job polling works correctly- Check that all API endpoints return successful responses
### Notes- The backend is already configured to accept requests from various origins including local addresses- The frontend uses environment variables to determine the API URL based on the environment- The hardcoded URL in the production environment file needs to be changed to the user's server IP12345# API ConfigurationVITE_API_URL=https://zelyanoth-lin-cbfcff2.hf.space/api# EnvironmentVITE_NODE_ENV=production12345# API ConfigurationVITE_API_URL=http://46.62.218.169/api# EnvironmentVITE_NODE_ENV=production
3 unmodified lines4567891021 unmodified lines323334353637384 unmodified lines434445464748493 unmodified lines535455565758594 unmodified lines6465666768697020 unmodified lines919293949596975 unmodified lines1031041051061071081091101111121131141151161171181191201211221231241251261271282 unmodified lines1311321331341351361371381391401411421431441451461471481491501511522 unmodified lines1551561571581591601611621631641651663 unmodified lines// Create axios instance with default configconst API_BASE_URL = import.meta.env.VITE_API_URL ||(import.meta.env.VITE_NODE_ENV === 'production' ?'https://zelyanoth-lin-cbfcff2.hf.space' :'http://localhost:5000');console.log('API_BASE_URL:', API_BASE_URL);21 unmodified linesheaders: config.headers,data: config.data});// Special logging for auth requests to verify field transformationif (config.url?.includes('/auth/register')) {console.log('π [Auth Register] Request data verification:', {4 unmodified lines});}}// Get token from cookie service with fallback to localStoragelet token = null;try {3 unmodified linesconsole.warn('πͺ [Cookie] Error getting auth tokens, trying localStorage:', error.message);token = localStorage.getItem('token');}if (token) {config.headers.Authorization = `Bearer ${token}`;if (isDevelopment) {4 unmodified linesconsole.log('π [Token] No token found for request');}}return config;},(error) => {20 unmodified linesasync (error) => {const isDevelopment = import.meta.env.VITE_NODE_ENV === 'development';const originalRequest = error.config;// Enhanced error loggingif (isDevelopment) {console.error('β [API Response Error]', {5 unmodified linesheaders: error.response?.headers});}// Handle 401 Unauthorized errorsif (error.response?.status === 401) {if (isDevelopment) {console.log('π [Auth] 401 error detected, attempting token refresh');}// If we haven't retried this request yetif (!originalRequest._retry) {originalRequest._retry = true;try {// Clear all authentication dataawait cookieService.clearAuthTokens();localStorage.removeItem('token');if (isDevelopment) {console.log('π [Auth] Cleared all authentication data');}// Redirect to login pageconst currentPath = window.location.pathname;if (currentPath !== '/login' && currentPath !== '/register') {2 unmodified lines}window.location.href = '/login';}} catch (refreshError) {if (isDevelopment) {console.error('π [Auth] Error during token refresh:', refreshError);}// Even if refresh fails, clear auth dataawait cookieService.clearAuthTokens();localStorage.removeItem('token');window.location.href = '/login';return Promise.reject(refreshError);}}}// Handle network errorsif (!error.response) {if (isDevelopment) {2 unmodified linesmessage: error.message});}// You might want to implement offline mode here// For now, just reject the errorreturn Promise.reject(error);}return Promise.reject(error);});3 unmodified lines4567891021 unmodified lines323334353637384 unmodified lines434445464748493 unmodified lines535455565758594 unmodified lines6465666768697020 unmodified lines919293949596975 unmodified lines1031041051061071081091101111121131141151161171181191201211221231241251261271282 unmodified lines1311321331341351361371381391401411421431441451461471481491501511522 unmodified lines1551561571581591601611621631641651663 unmodified lines// Create axios instance with default configconst API_BASE_URL = import.meta.env.VITE_API_URL ||(import.meta.env.VITE_NODE_ENV === 'production' ?'http://46.62.218.169' :'http://localhost:5000');console.log('API_BASE_URL:', API_BASE_URL);21 unmodified linesheaders: config.headers,data: config.data});// Special logging for auth requests to verify field transformationif (config.url?.includes('/auth/register')) {console.log('π [Auth Register] Request data verification:', {4 unmodified lines});}}// Get token from cookie service with fallback to localStoragelet token = null;try {3 unmodified linesconsole.warn('πͺ [Cookie] Error getting auth tokens, trying localStorage:', error.message);token = localStorage.getItem('token');}if (token) {config.headers.Authorization = `Bearer ${token}`;if (isDevelopment) {4 unmodified linesconsole.log('π [Token] No token found for request');}}return config;},(error) => {20 unmodified linesasync (error) => {const isDevelopment = import.meta.env.VITE_NODE_ENV === 'development';const originalRequest = error.config;// Enhanced error loggingif (isDevelopment) {console.error('β [API Response Error]', {5 unmodified linesheaders: error.response?.headers});}// Handle 401 Unauthorized errorsif (error.response?.status === 401) {if (isDevelopment) {console.log('π [Auth] 401 error detected, attempting token refresh');}// If we haven't retried this request yetif (!originalRequest._retry) {originalRequest._retry = true;try {// Clear all authentication dataawait cookieService.clearAuthTokens();localStorage.removeItem('token');if (isDevelopment) {console.log('π [Auth] Cleared all authentication data');}// Redirect to login pageconst currentPath = window.location.pathname;if (currentPath !== '/login' && currentPath !== '/register') {2 unmodified lines}window.location.href = '/login';}} catch (refreshError) {if (isDevelopment) {console.error('π [Auth] Error during token refresh:', refreshError);}// Even if refresh fails, clear auth dataawait cookieService.clearAuthTokens();localStorage.removeItem('token');window.location.href = '/login';return Promise.reject(refreshError);}}}// Handle network errorsif (!error.response) {if (isDevelopment) {2 unmodified linesmessage: error.message});}// You might want to implement offline mode here// For now, just reject the errorreturn Promise.reject(error);}return Promise.reject(error);});
1234567891011121314159 unmodified lines2526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221 unmodified line1241251261271281291301311321331341351361 unmodified line1381391401411421431441 unmodified line1461471481491501511522 unmodified lines155156157158159160161162163164165166167168169170171/*** Authentication Fix Test Script* This script tests the authentication fixes for Hugging Face Spaces deployment*/// Test configurationconst testConfig = {production: {apiUrl: 'https://zelyanoth-lin-cbfcff2.hf.space/api',expectedCookieSameSite: 'Lax',expectedCookieSecure: true,expectedCorsOrigin: 'https://zelyanoth-lin-cbfcff2.hf.space'},development: {apiUrl: 'http://localhost:5000/api',9 unmodified lines// Test 1: Environment Detectionfunction testEnvironmentDetection() {console.log('\nπ Test 1: Environment Detection');const env = import.meta.env?.VITE_NODE_ENV || 'development';console.log(`Current environment: ${env}`);if (env === 'production') {console.log('β Production environment detected');console.log(' - Cookie sameSite should be: Lax');console.log(' - Cookie secure should be: true');} else {console.log('β Development environment detected');console.log(' - Cookie sameSite should be: Strict');console.log(' - Cookie secure should be: false');}return env;}// Test 2: API URL Configurationfunction testApiUrlConfiguration() {console.log('\nπ Test 2: API URL Configuration');const apiUrl = import.meta.env?.VITE_API_URL || 'http://localhost:5000/api';console.log(`API URL: ${apiUrl}`);if (apiUrl.includes('hf.space')) {console.log('β Production API URL detected');console.log(' - Should use: https://zelyanoth-lin-cbfcff2.hf.space/api');} else {console.log('β Development API URL detected');console.log(' - Should use: http://localhost:5000/api');}return apiUrl;}// Test 3: Cookie Service Configurationfunction testCookieServiceConfiguration() {console.log('\nπ Test 3: Cookie Service Configuration');// Simulate the cookie service logicconst isProduction = import.meta.env?.VITE_NODE_ENV === 'production';const sameSitePolicy = isProduction ? 'Lax' : 'Strict';const secureFlag = isProduction;console.log(`Cookie sameSite policy: ${sameSitePolicy}`);console.log(`Cookie secure flag: ${secureFlag}`);if (isProduction && sameSitePolicy === 'Lax' && secureFlag === true) {console.log('β Production cookie configuration is correct');} else if (!isProduction && sameSitePolicy === 'Strict' && secureFlag === false) {console.log('β Development cookie configuration is correct');} else {console.log('β Cookie configuration is incorrect');return false;}return true;}// Test 4: CORS Configuration Checkfunction testCorsConfiguration() {console.log('\nπ Test 4: CORS Configuration Check');const env = import.meta.env?.VITE_NODE_ENV || 'development';const expectedOrigin = env === 'production'? 'https://zelyanoth-lin-cbfcff2.hf.space': 'http://localhost:3000';console.log(`Expected CORS origin: ${expectedOrigin}`);console.log('β CORS configuration should include this origin');return expectedOrigin;}// Test 5: Authentication Flow Simulationfunction testAuthenticationFlow() {console.log('\nπ Test 5: Authentication Flow Simulation');console.log('1. User attempts to login...');console.log(' - Should send credentials to /api/auth/login');console.log(' - Server should validate and return JWT token');console.log('2. Token should be stored in cookies with:');console.log(' - SameSite: Lax (production) / Strict (development)');console.log(' - Secure: true (production) / false (development)');console.log(' - HttpOnly: true');console.log('3. Page reload should:');console.log(' - Send cookies with requests');console.log(' - Server should validate JWT token');console.log(' - Return user data if valid');console.log('β Authentication flow simulation complete');return true;}1 unmodified line// Test 6: Error Handlingfunction testErrorHandling() {console.log('\nπ Test 6: Error Handling');console.log('Expected error scenarios:');console.log('1. Invalid token β Should redirect to login');console.log('2. Expired token β Should clear cookies and redirect');console.log('3. Network error β Should show appropriate error message');console.log('4. CORS error β Should be handled gracefully');console.log('β Error handling configuration complete');return true;}1 unmodified line// Main test runnerfunction runTests() {console.log('π Starting authentication fix tests...\n');try {const env = testEnvironmentDetection();const apiUrl = testApiUrlConfiguration();1 unmodified lineconst corsOrigin = testCorsConfiguration();const authFlow = testAuthenticationFlow();const errorHandling = testErrorHandling();console.log('\nπ― Test Results Summary:');console.log('========================');console.log(`Environment: ${env}`);2 unmodified linesconsole.log(`CORS Origin: ${corsOrigin}`);console.log(`Auth Flow: ${authFlow ? 'β ' : 'β'}`);console.log(`Error Handling: ${errorHandling ? 'β ' : 'β'}`);if (cookieConfig && authFlow && errorHandling) {console.log('\nπ All tests passed! Authentication fix should work correctly.');console.log('\nπ Next Steps:');console.log('1. Build the frontend: npm run build');console.log('2. Deploy to Hugging Face Spaces');console.log('3. Test login and page reload functionality');} else {console.log('\nβ οΈ Some tests failed. Please review the configuration.');}} catch (error) {console.error('\nβ Test execution failed:', error);}1234567891011121314159 unmodified lines2526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221 unmodified line1241251261271281291301311321331341351361 unmodified line1381391401411421431441 unmodified line1461471481491501511522 unmodified lines155156157158159160161162163164165166167168169170171/*** Authentication Fix Test Script* This script tests the authentication fixes for server IP deployment*/// Test configurationconst testConfig = {production: {apiUrl: 'http://46.62.218.169/api',expectedCookieSameSite: 'Lax',expectedCookieSecure: false, // Set to false for HTTP serverexpectedCorsOrigin: 'http://46.62.218.169'},development: {apiUrl: 'http://localhost:5000/api',9 unmodified lines// Test 1: Environment Detectionfunction testEnvironmentDetection() {console.log('\nπ Test 1: Environment Detection');const env = import.meta.env?.VITE_NODE_ENV || 'development';console.log(`Current environment: ${env}`);if (env === 'production') {console.log('β Production environment detected');console.log(' - Cookie sameSite should be: Lax');console.log(' - Cookie secure should be: false (HTTP server)');} else {console.log('β Development environment detected');console.log(' - Cookie sameSite should be: Strict');console.log(' - Cookie secure should be: false');}return env;}// Test 2: API URL Configurationfunction testApiUrlConfiguration() {console.log('\nπ Test 2: API URL Configuration');const apiUrl = import.meta.env?.VITE_API_URL || 'http://localhost:5000/api';console.log(`API URL: ${apiUrl}`);if (apiUrl.includes('46.62.218.169')) {console.log('β Production API URL detected');console.log(' - Should use: http://46.62.218.169/api');} else {console.log('β Development API URL detected');console.log(' - Should use: http://localhost:5000/api');}return apiUrl;}// Test 3: Cookie Service Configurationfunction testCookieServiceConfiguration() {console.log('\nπ Test 3: Cookie Service Configuration');// Simulate the cookie service logicconst isProduction = import.meta.env?.VITE_NODE_ENV === 'production';const sameSitePolicy = isProduction ? 'Lax' : 'Strict';const secureFlag = isProduction ? false : false; // Set to false for HTTP serverconsole.log(`Cookie sameSite policy: ${sameSitePolicy}`);console.log(`Cookie secure flag: ${secureFlag}`);if (isProduction && sameSitePolicy === 'Lax' && secureFlag === false) {console.log('β Production cookie configuration is correct (HTTP server)');} else if (!isProduction && sameSitePolicy === 'Strict' && secureFlag === false) {console.log('β Development cookie configuration is correct');} else {console.log('β Cookie configuration is incorrect');return false;}return true;}// Test 4: CORS Configuration Checkfunction testCorsConfiguration() {console.log('\nπ Test 4: CORS Configuration Check');const env = import.meta.env?.VITE_NODE_ENV || 'development';const expectedOrigin = env === 'production'? 'http://46.62.218.169': 'http://localhost:3000';console.log(`Expected CORS origin: ${expectedOrigin}`);console.log('β CORS configuration should include this origin');return expectedOrigin;}// Test 5: Authentication Flow Simulationfunction testAuthenticationFlow() {console.log('\nπ Test 5: Authentication Flow Simulation');console.log('1. User attempts to login...');console.log(' - Should send credentials to /api/auth/login');console.log(' - Server should validate and return JWT token');console.log('2. Token should be stored in cookies with:');console.log(' - SameSite: Lax (production) / Strict (development)');console.log(' - Secure: false (HTTP server) / false (development)');console.log(' - HttpOnly: true');console.log('3. Page reload should:');console.log(' - Send cookies with requests');console.log(' - Server should validate JWT token');console.log(' - Return user data if valid');console.log('β Authentication flow simulation complete');return true;}1 unmodified line// Test 6: Error Handlingfunction testErrorHandling() {console.log('\nπ Test 6: Error Handling');console.log('Expected error scenarios:');console.log('1. Invalid token β Should redirect to login');console.log('2. Expired token β Should clear cookies and redirect');console.log('3. Network error β Should show appropriate error message');console.log('4. CORS error β Should be handled gracefully');console.log('β Error handling configuration complete');return true;}1 unmodified line// Main test runnerfunction runTests() {console.log('π Starting authentication fix tests...\n');try {const env = testEnvironmentDetection();const apiUrl = testApiUrlConfiguration();1 unmodified lineconst corsOrigin = testCorsConfiguration();const authFlow = testAuthenticationFlow();const errorHandling = testErrorHandling();console.log('\nπ― Test Results Summary:');console.log('========================');console.log(`Environment: ${env}`);2 unmodified linesconsole.log(`CORS Origin: ${corsOrigin}`);console.log(`Auth Flow: ${authFlow ? 'β ' : 'β'}`);console.log(`Error Handling: ${errorHandling ? 'β ' : 'β'}`);if (cookieConfig && authFlow && errorHandling) {console.log('\nπ All tests passed! Authentication fix should work correctly.');console.log('\nπ Next Steps:');console.log('1. Build the frontend: npm run build');console.log('2. Deploy with correct server IP configuration');console.log('3. Test login and page reload functionality');} else {console.log('\nβ οΈ Some tests failed. Please review the configuration.');}} catch (error) {console.error('\nβ Test execution failed:', error);}
backend/app.py+2-2
backend/utils/cookies.py+1-1
docs/sprint-artifacts/tech-spec-api-url-fix.mdAdded+72
frontend/.env.production+1-1
frontend/src/services/apiClient.js+17-17
frontend/test-auth-fix.js+37-37