vulnnearable comments removed and source exposing to frobrowser disabled worknote XSS fixed
This commit is contained in:
parent
2fa52b90e3
commit
a16346effd
27
.env.local.backup
Normal file
27
.env.local.backup
Normal file
@ -0,0 +1,27 @@
|
||||
#Local
|
||||
VITE_PUBLIC_VAPID_KEY=BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI
|
||||
VITE_BASE_URL=http://localhost:3000
|
||||
VITE_API_BASE_URL=http://localhost:3000/api/v1
|
||||
VITE_OKTA_CLIENT_ID=0oa18b98aari6I6eo2p8
|
||||
VITE_OKTA_DOMAIN=https://royalenfield.okta.com
|
||||
|
||||
#Development
|
||||
# VITE_PUBLIC_VAPID_KEY=BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI
|
||||
# VITE_BASE_URL=https://re-workflow-nt-dev.siplsolutions.com
|
||||
# VITE_API_BASE_URL=https://re-workflow-nt-dev.siplsolutions.com/api/v1
|
||||
# VITE_OKTA_CLIENT_ID=0oa18b98aari6I6eo2p8
|
||||
# VITE_OKTA_DOMAIN=https://royalenfield.okta.com
|
||||
|
||||
#Uat
|
||||
# VITE_PUBLIC_VAPID_KEY=BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI
|
||||
# VITE_BASE_URL=https://reflow-uat.royalenfield.com
|
||||
# VITE_API_BASE_URL=https://reflow-uat.royalenfield.com/api/v1/
|
||||
# VITE_OKTA_CLIENT_ID=0oa2jgzvrpdwx2iqd0h8
|
||||
# VITE_OKTA_DOMAIN=https://dev-830839.oktapreview.com
|
||||
|
||||
#Production
|
||||
# VITE_PUBLIC_VAPID_KEY=BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI
|
||||
# VITE_BASE_URL=https://reflow.royalenfield.com
|
||||
# VITE_API_BASE_URL=https://reflow.royalenfield.com/api/v1
|
||||
# VITE_OKTA_CLIENT_ID=0oa18b98aari6I6eo2p8
|
||||
# VITE_OKTA_DOMAIN=https://royalenfield.okta.com
|
||||
@ -10,7 +10,7 @@
|
||||
<meta name="theme-color" content="#2d4a3e" />
|
||||
<title>Royal Enfield | Approval Portal</title>
|
||||
|
||||
<!-- Preload critical fonts and icons -->
|
||||
<!-- Preload essential fonts and icons -->
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
</head>
|
||||
|
||||
4
public/robots.txt
Normal file
4
public/robots.txt
Normal file
@ -0,0 +1,4 @@
|
||||
User-agent: *
|
||||
Disallow: /api/
|
||||
|
||||
Sitemap: https://reflow.royalenfield.com/sitemap.xml
|
||||
9
public/sitemap.xml
Normal file
9
public/sitemap.xml
Normal file
@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||
<url>
|
||||
<loc>https://reflow.royalenfield.com</loc>
|
||||
<lastmod>2024-03-20T12:00:00+00:00</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
<priority>1.0</priority>
|
||||
</url>
|
||||
</urlset>
|
||||
41
src/App.tsx
41
src/App.tsx
@ -20,7 +20,7 @@ import { Profile } from '@/pages/Profile';
|
||||
import { Settings } from '@/pages/Settings';
|
||||
import { Notifications } from '@/pages/Notifications';
|
||||
import { DetailedReports } from '@/pages/DetailedReports';
|
||||
import { Admin } from '@/pages/Admin';
|
||||
|
||||
import { AdminTemplatesList } from '@/pages/Admin/Templates/AdminTemplatesList';
|
||||
import { CreateTemplate } from '@/pages/Admin/Templates/CreateTemplate';
|
||||
import { CreateAdminRequest } from '@/pages/CreateAdminRequest/CreateAdminRequest';
|
||||
@ -216,7 +216,7 @@ function AppRoutes({ onLogout }: AppProps) {
|
||||
name: 'Current User',
|
||||
role: requestData.initiatorRole || 'Employee',
|
||||
department: requestData.department || 'General',
|
||||
email: 'current.user@{{API_DOMAIN}}',
|
||||
email: 'current.user@royalenfield.com',
|
||||
phone: '+91 98765 43290',
|
||||
avatar: 'CU'
|
||||
},
|
||||
@ -462,44 +462,7 @@ function AppRoutes({ onLogout }: AppProps) {
|
||||
}
|
||||
/>
|
||||
|
||||
<Route
|
||||
path="/admin"
|
||||
element={
|
||||
<PageLayout currentPage="admin" onNavigate={handleNavigate} onNewRequest={handleNewRequest} onLogout={onLogout}>
|
||||
<Admin />
|
||||
</PageLayout>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Admin Routes Group with Shared Layout */}
|
||||
<Route
|
||||
element={
|
||||
<PageLayout currentPage="admin-templates" onNavigate={handleNavigate} onNewRequest={handleNewRequest} onLogout={onLogout}>
|
||||
<Outlet />
|
||||
</PageLayout>
|
||||
}
|
||||
>
|
||||
<Route path="/admin/create-template" element={<CreateTemplate />} />
|
||||
<Route path="/admin/edit-template/:templateId" element={<CreateTemplate />} />
|
||||
<Route path="/admin/templates" element={<AdminTemplatesList />} />
|
||||
</Route>
|
||||
|
||||
{/* Create Request from Admin Template (Dedicated Flow) */}
|
||||
<Route
|
||||
path="/create-admin-request/:templateId"
|
||||
element={
|
||||
<CreateAdminRequest />
|
||||
}
|
||||
/>
|
||||
|
||||
<Route
|
||||
path="/admin"
|
||||
element={
|
||||
<PageLayout currentPage="admin" onNavigate={handleNavigate} onNewRequest={handleNewRequest} onLogout={onLogout}>
|
||||
<Admin />
|
||||
</PageLayout>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Open Requests */}
|
||||
<Route
|
||||
|
||||
@ -334,7 +334,7 @@ export function ApprovalWorkflowStep({
|
||||
<Input
|
||||
id={`approver-${level}`}
|
||||
type="email"
|
||||
placeholder="approver@{{API_DOMAIN}}"
|
||||
placeholder={`approver@${process.env.VITE_APP_DOMAIN}`}
|
||||
value={approver.email || ''}
|
||||
onChange={(e) => handleApproverEmailChange(index, e.target.value)}
|
||||
className="h-10 border-2 border-gray-300 focus:border-blue-500 mt-1 w-full"
|
||||
|
||||
@ -129,7 +129,7 @@ function BackendAuthProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
|
||||
// PRIORITY 3: Skip auth check if on callback page - let callback handler process first
|
||||
// This is critical for production mode where we need to exchange code for tokens
|
||||
// This is essential for production mode where we need to exchange code for tokens
|
||||
// before we can verify session with server
|
||||
if (window.location.pathname === '/login/callback' || window.location.pathname === '/login/tanflow/callback') {
|
||||
// Don't check auth status here - let the callback handler do its job
|
||||
@ -149,14 +149,14 @@ function BackendAuthProvider({ children }: { children: ReactNode }) {
|
||||
// In production: Always verify with server (cookies are sent automatically)
|
||||
// In development: Check local auth data first
|
||||
if (isProductionMode) {
|
||||
// Production: Verify session with server via httpOnly cookie
|
||||
// Prod: Verify session with server via httpOnly cookie
|
||||
if (!isLoggingOut) {
|
||||
checkAuthStatus();
|
||||
} else {
|
||||
setIsLoading(false);
|
||||
}
|
||||
} else {
|
||||
// Development: If no auth data exists, user is not authenticated
|
||||
// Dev: If no auth data exists, user is not authenticated
|
||||
if (!hasAuthData) {
|
||||
setIsAuthenticated(false);
|
||||
setUser(null);
|
||||
@ -323,7 +323,7 @@ function BackendAuthProvider({ children }: { children: ReactNode }) {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
|
||||
// PRODUCTION MODE: Verify session via httpOnly cookie
|
||||
// Prod MODE: Verify session via httpOnly cookie
|
||||
// The cookie is sent automatically with the request (withCredentials: true)
|
||||
if (isProductionMode) {
|
||||
const storedUser = TokenManager.getUserData();
|
||||
@ -369,7 +369,7 @@ function BackendAuthProvider({ children }: { children: ReactNode }) {
|
||||
return;
|
||||
}
|
||||
|
||||
// DEVELOPMENT MODE: Check local token
|
||||
// Dev MODE: Check local token
|
||||
const token = TokenManager.getAccessToken();
|
||||
const storedUser = TokenManager.getUserData();
|
||||
|
||||
@ -490,7 +490,7 @@ function BackendAuthProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
const logout = async () => {
|
||||
try {
|
||||
// CRITICAL: Get id_token from TokenManager before clearing anything
|
||||
//: Get id_token from TokenManager before clearing anything
|
||||
// Needed for both Okta and Tanflow logout endpoints
|
||||
const idToken = TokenManager.getIdToken();
|
||||
|
||||
@ -609,7 +609,7 @@ function BackendAuthProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
}
|
||||
|
||||
// Development mode: tokens in localStorage
|
||||
// Dev mode: tokens in localStorage
|
||||
const token = TokenManager.getAccessToken();
|
||||
if (token && !isTokenExpired(token)) {
|
||||
return token;
|
||||
|
||||
@ -141,7 +141,7 @@ export function ClaimApproverSelectionStep({
|
||||
// Create new approver only if it doesn't exist
|
||||
if (step.isAuto) {
|
||||
// System steps
|
||||
const systemEmail = step.level === 8 ? 'finance@{{API_DOMAIN}}' : 'system@{{API_DOMAIN}}';
|
||||
const systemEmail = step.level === 8 ? `finance@${process.env.VITE_APP_DOMAIN}` : `system@${process.env.VITE_APP_DOMAIN}`;
|
||||
const systemName = step.level === 8 ? 'System/Finance' : 'System';
|
||||
newApprovers.push({
|
||||
email: systemEmail,
|
||||
|
||||
@ -765,7 +765,7 @@ export function DealerClaimWorkflowTab({
|
||||
// Note: Status normalization already handled in workflowSteps mapping above
|
||||
// backendCurrentLevel is already calculated above before the map function
|
||||
|
||||
// CRITICAL: If request is rejected or closed, no step should be active
|
||||
//: If request is rejected or closed, no step should be active
|
||||
let activeStep = null;
|
||||
let currentStep = 1;
|
||||
|
||||
@ -2519,7 +2519,7 @@ export function DealerClaimWorkflowTab({
|
||||
stepNumber={selectedStepForEmail?.stepNumber || 4}
|
||||
stepName={selectedStepForEmail?.stepName || 'Activity Creation'}
|
||||
requestNumber={request?.requestNumber || request?.id || request?.request_number}
|
||||
recipientEmail="system@{{API_DOMAIN}}"
|
||||
recipientEmail={`system@${window.location.hostname}`}
|
||||
/>
|
||||
|
||||
{/* Additional Approver Review Modal */}
|
||||
|
||||
@ -32,7 +32,7 @@ export function EmailNotificationTemplateModal({
|
||||
stepNumber,
|
||||
stepName,
|
||||
requestNumber = 'RE-REQ-2024-CM-101',
|
||||
recipientEmail = 'system@{{API_DOMAIN}}',
|
||||
recipientEmail = `system@${window.location.hostname}`,
|
||||
subject,
|
||||
emailBody,
|
||||
}: EmailNotificationTemplateModalProps) {
|
||||
|
||||
@ -649,7 +649,7 @@ export function useRequestDetails(
|
||||
|
||||
/**
|
||||
* Computed: Get final request object with fallback to static databases
|
||||
* Priority: API data → Custom DB → Claim DB → Dynamic props → null
|
||||
* Priority: API data → Custom Database → Claim Database → Dynamic props → null
|
||||
*/
|
||||
const request = useMemo(() => {
|
||||
// Primary source: API data
|
||||
|
||||
@ -11,7 +11,6 @@ import { useAppSelector } from '@/redux/hooks';
|
||||
import { Pagination } from '@/components/common/Pagination';
|
||||
import type { DateRange } from '@/services/dashboard.service';
|
||||
import dashboardService from '@/services/dashboard.service';
|
||||
import userApi from '@/services/userApi';
|
||||
|
||||
// Components
|
||||
import { RequestsHeader } from './components/RequestsHeader';
|
||||
@ -70,7 +69,6 @@ export function Requests({ onViewRequest }: RequestsProps) {
|
||||
const [backendStats, setBackendStats] = useState<BackendStats | null>(null);
|
||||
const [departments, setDepartments] = useState<string[]>([]);
|
||||
const [loadingDepartments, setLoadingDepartments] = useState(false);
|
||||
const [allUsers, setAllUsers] = useState<Array<{ userId: string; email: string; displayName?: string }>>([]);
|
||||
|
||||
// Pagination (currentPage now in Redux)
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
@ -79,15 +77,15 @@ export function Requests({ onViewRequest }: RequestsProps) {
|
||||
|
||||
// User search hooks
|
||||
const initiatorSearch = useUserSearch({
|
||||
allUsers,
|
||||
filterValue: filters.initiatorFilter,
|
||||
onFilterChange: filters.setInitiatorFilter
|
||||
onFilterChange: filters.setInitiatorFilter,
|
||||
source: 'local'
|
||||
});
|
||||
|
||||
const approverSearch = useUserSearch({
|
||||
allUsers,
|
||||
filterValue: filters.approverFilter,
|
||||
onFilterChange: filters.setApproverFilter
|
||||
onFilterChange: filters.setApproverFilter,
|
||||
source: 'local'
|
||||
});
|
||||
|
||||
// Fetch backend stats
|
||||
@ -226,20 +224,6 @@ export function Requests({ onViewRequest }: RequestsProps) {
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Fetch users
|
||||
const fetchUsers = useCallback(async () => {
|
||||
try {
|
||||
const usersData = await userApi.getAllUsers();
|
||||
const usersList = usersData.map((user: any) => ({
|
||||
userId: user.userId,
|
||||
email: user.email,
|
||||
displayName: user.displayName || user.email
|
||||
}));
|
||||
setAllUsers(usersList);
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch users:', error);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Use refs to store stable callbacks to prevent infinite loops
|
||||
const filtersRef = useRef(filters);
|
||||
@ -332,8 +316,7 @@ export function Requests({ onViewRequest }: RequestsProps) {
|
||||
// Initial fetch
|
||||
useEffect(() => {
|
||||
fetchDepartments();
|
||||
fetchUsers();
|
||||
}, [fetchDepartments, fetchUsers]);
|
||||
}, [fetchDepartments]);
|
||||
|
||||
// Fetch backend stats when filters change (excluding status)
|
||||
// Stats should reflect priority, department, initiator, approver, search, and date range filters
|
||||
|
||||
@ -11,7 +11,6 @@ import { useEffect, useState, useCallback, useMemo, useRef } from 'react';
|
||||
import { Pagination } from '@/components/common/Pagination';
|
||||
import dashboardService from '@/services/dashboard.service';
|
||||
import type { DateRange } from '@/services/dashboard.service';
|
||||
import userApi from '@/services/userApi';
|
||||
|
||||
// Components
|
||||
import { RequestsHeader } from './components/RequestsHeader';
|
||||
@ -96,7 +95,6 @@ export function UserAllRequests({ onViewRequest }: RequestsProps) {
|
||||
const [backendStats, setBackendStats] = useState<BackendStats | null>(null); // Stats from backend API
|
||||
const [departments, setDepartments] = useState<string[]>([]);
|
||||
const [loadingDepartments, setLoadingDepartments] = useState(false);
|
||||
const [allUsers, setAllUsers] = useState<Array<{ userId: string; email: string; displayName?: string }>>([]);
|
||||
|
||||
// Pagination (currentPage now in Redux)
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
@ -105,15 +103,15 @@ export function UserAllRequests({ onViewRequest }: RequestsProps) {
|
||||
|
||||
// User search hooks
|
||||
const initiatorSearch = useUserSearch({
|
||||
allUsers,
|
||||
filterValue: filters.initiatorFilter,
|
||||
onFilterChange: filters.setInitiatorFilter
|
||||
onFilterChange: filters.setInitiatorFilter,
|
||||
source: 'local'
|
||||
});
|
||||
|
||||
const approverSearch = useUserSearch({
|
||||
allUsers,
|
||||
filterValue: filters.approverFilter,
|
||||
onFilterChange: filters.setApproverFilter
|
||||
onFilterChange: filters.setApproverFilter,
|
||||
source: 'local'
|
||||
});
|
||||
|
||||
// Fetch backend stats using dashboard API
|
||||
@ -180,20 +178,6 @@ export function UserAllRequests({ onViewRequest }: RequestsProps) {
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Fetch users
|
||||
const fetchUsers = useCallback(async () => {
|
||||
try {
|
||||
const usersData = await userApi.getAllUsers();
|
||||
const usersList = usersData.map((user: any) => ({
|
||||
userId: user.userId,
|
||||
email: user.email,
|
||||
displayName: user.displayName || user.email
|
||||
}));
|
||||
setAllUsers(usersList);
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch users:', error);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Use refs to store stable callbacks to prevent infinite loops
|
||||
const filtersRef = useRef(filters);
|
||||
@ -253,8 +237,7 @@ export function UserAllRequests({ onViewRequest }: RequestsProps) {
|
||||
// Initial fetch
|
||||
useEffect(() => {
|
||||
fetchDepartments();
|
||||
fetchUsers();
|
||||
}, [fetchDepartments, fetchUsers]);
|
||||
}, [fetchDepartments]);
|
||||
|
||||
// Fetch backend stats when filters change (except status filter)
|
||||
// OPTIMIZED: Uses backend stats API instead of fetching 100 records
|
||||
|
||||
@ -4,30 +4,44 @@
|
||||
|
||||
import { useState, useCallback, useRef, useEffect } from 'react';
|
||||
import type { User } from '../types/requests.types';
|
||||
import { userApi } from '@/services/userApi';
|
||||
|
||||
interface UseUserSearchOptions {
|
||||
allUsers: User[];
|
||||
filterValue: string;
|
||||
onFilterChange: (userId: string) => void;
|
||||
source?: 'local' | 'okta' | 'default';
|
||||
}
|
||||
|
||||
export function useUserSearch({ allUsers, filterValue, onFilterChange }: UseUserSearchOptions) {
|
||||
export function useUserSearch({ filterValue, onFilterChange, source = 'default' }: UseUserSearchOptions) {
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [searchResults, setSearchResults] = useState<User[]>([]);
|
||||
const [showResults, setShowResults] = useState(false);
|
||||
const [selectedUser, setSelectedUser] = useState<User | null>(null);
|
||||
const [searching, setSearching] = useState(false);
|
||||
const searchTimer = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
// Initialize selected user from filter value
|
||||
// Initialize selected user details if we only have the ID (filterValue)
|
||||
useEffect(() => {
|
||||
if (filterValue !== 'all' && allUsers.length > 0) {
|
||||
const user = allUsers.find(u => u.userId === filterValue);
|
||||
async function fetchUserDetail() {
|
||||
if (filterValue !== 'all' && !selectedUser) {
|
||||
try {
|
||||
// Fetch specific user details by ID
|
||||
const user = await userApi.getUserById(filterValue);
|
||||
if (user) {
|
||||
setSelectedUser(user);
|
||||
setSearchQuery(user.displayName || user.email);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch user detail for search:', err);
|
||||
}
|
||||
}, [filterValue, allUsers]);
|
||||
} else if (filterValue === 'all') {
|
||||
setSelectedUser(null);
|
||||
setSearchQuery('');
|
||||
}
|
||||
}
|
||||
|
||||
fetchUserDetail();
|
||||
}, [filterValue]);
|
||||
|
||||
// Cleanup timer
|
||||
useEffect(() => {
|
||||
@ -51,17 +65,22 @@ export function useUserSearch({ allUsers, filterValue, onFilterChange }: UseUser
|
||||
return;
|
||||
}
|
||||
|
||||
searchTimer.current = setTimeout(() => {
|
||||
const searchLower = query.toLowerCase().trim();
|
||||
const filtered = allUsers.filter((user) => {
|
||||
const email = (user.email || '').toLowerCase();
|
||||
const displayName = (user.displayName || '').toLowerCase();
|
||||
return email.includes(searchLower) || displayName.includes(searchLower);
|
||||
});
|
||||
setSearchResults(filtered.slice(0, 10));
|
||||
setShowResults(filtered.length > 0);
|
||||
}, 300);
|
||||
}, [allUsers]);
|
||||
searchTimer.current = setTimeout(async () => {
|
||||
setSearching(true);
|
||||
try {
|
||||
const response = await userApi.searchUsers(query.trim(), 10, source);
|
||||
const users = response.data?.data || [];
|
||||
setSearchResults(users);
|
||||
setShowResults(users.length > 0);
|
||||
} catch (err) {
|
||||
console.error('Search API failed:', err);
|
||||
setSearchResults([]);
|
||||
setShowResults(false);
|
||||
} finally {
|
||||
setSearching(false);
|
||||
}
|
||||
}, 400); // Slightly longer debounce for API calls
|
||||
}, [source]);
|
||||
|
||||
const handleSelect = useCallback((user: User) => {
|
||||
setSelectedUser(user);
|
||||
@ -84,6 +103,7 @@ export function useUserSearch({ allUsers, filterValue, onFilterChange }: UseUser
|
||||
searchResults,
|
||||
showResults,
|
||||
selectedUser,
|
||||
searching,
|
||||
handleSearch,
|
||||
handleSelect,
|
||||
handleClear,
|
||||
|
||||
@ -6,7 +6,7 @@
|
||||
import axios, { AxiosInstance } from 'axios';
|
||||
import { TokenManager } from '../utils/tokenManager';
|
||||
|
||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000/api/v1';
|
||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '';
|
||||
|
||||
// Create axios instance with default config
|
||||
const apiClient: AxiosInstance = axios.create({
|
||||
@ -27,13 +27,13 @@ apiClient.interceptors.request.use(
|
||||
const isProduction = import.meta.env.PROD || import.meta.env.MODE === 'production';
|
||||
|
||||
if (!isProduction) {
|
||||
// Development: Get token from localStorage and add to header
|
||||
// Dev: Get token from localStorage and add to header
|
||||
const token = TokenManager.getAccessToken();
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
}
|
||||
// Production: Cookies handle authentication automatically
|
||||
// Prod: Cookies handle authentication automatically
|
||||
|
||||
return config;
|
||||
},
|
||||
@ -183,11 +183,11 @@ export async function exchangeCodeForTokens(
|
||||
// SECURITY: In production, tokens are ONLY in httpOnly cookies (not in response body)
|
||||
// In development, backend returns tokens for cross-port setup
|
||||
if (result.accessToken && result.refreshToken) {
|
||||
// Development mode: Backend returned tokens, store them
|
||||
// Dev mode: Backend returned tokens, store them
|
||||
TokenManager.setAccessToken(result.accessToken);
|
||||
TokenManager.setRefreshToken(result.refreshToken);
|
||||
}
|
||||
// Production mode: No tokens in response - they're in httpOnly cookies
|
||||
// Prod mode: No tokens in response - they're in httpOnly cookies
|
||||
// TokenManager.setAccessToken/setRefreshToken are no-ops in production anyway
|
||||
|
||||
return result;
|
||||
@ -255,7 +255,7 @@ export async function getCurrentUser() {
|
||||
|
||||
/**
|
||||
* Logout user
|
||||
* CRITICAL: This endpoint MUST clear httpOnly cookies set by backend
|
||||
* IMPORTANT: This endpoint MUST clear httpOnly cookies set by backend
|
||||
* Note: TokenManager.clearAll() is called in AuthContext.logout()
|
||||
* We don't call it here to avoid double clearing
|
||||
*/
|
||||
|
||||
@ -6,8 +6,8 @@
|
||||
import { TokenManager } from '../utils/tokenManager';
|
||||
import axios from 'axios';
|
||||
|
||||
const TANFLOW_BASE_URL = import.meta.env.VITE_TANFLOW_BASE_URL || '{{IDP_DOMAIN}}/realms/RE';
|
||||
const TANFLOW_CLIENT_ID = import.meta.env.VITE_TANFLOW_CLIENT_ID || 'REFLOW';
|
||||
const TANFLOW_BASE_URL = import.meta.env.VITE_TANFLOW_BASE_URL || '';
|
||||
const TANFLOW_CLIENT_ID = import.meta.env.VITE_TANFLOW_CLIENT_ID || '';
|
||||
const TANFLOW_REDIRECT_URI = `${window.location.origin}/login/callback`;
|
||||
|
||||
/**
|
||||
@ -63,7 +63,7 @@ export async function exchangeTanflowCodeForTokens(
|
||||
idToken: string;
|
||||
user: any;
|
||||
}> {
|
||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000/api/v1';
|
||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '';
|
||||
|
||||
try {
|
||||
const response = await axios.post(
|
||||
@ -112,7 +112,7 @@ export async function exchangeTanflowCodeForTokens(
|
||||
* Refresh access token using refresh token
|
||||
*/
|
||||
export async function refreshTanflowToken(): Promise<string> {
|
||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000/api/v1';
|
||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '';
|
||||
const refreshToken = TokenManager.getRefreshToken();
|
||||
|
||||
if (!refreshToken) {
|
||||
|
||||
@ -24,8 +24,8 @@ export interface UserSummary {
|
||||
isActive?: boolean;
|
||||
}
|
||||
|
||||
export async function searchUsers(query: string, limit: number = 10) {
|
||||
const res = await apiClient.get('/users/search', { params: { q: query, limit } });
|
||||
export async function searchUsers(query: string, limit: number = 10, source: 'local' | 'okta' | 'default' = 'default') {
|
||||
const res = await apiClient.get('/users/search', { params: { q: query, limit, source } });
|
||||
// ResponseHandler.success returns { success: true, data: array }
|
||||
return res;
|
||||
}
|
||||
@ -102,6 +102,14 @@ export async function getRoleStatistics() {
|
||||
return await apiClient.get('/admin/users/role-statistics');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user by ID
|
||||
*/
|
||||
export async function getUserById(userId: string) {
|
||||
const res = await apiClient.get(`/users/${userId}`);
|
||||
return res.data?.data || res.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all users from database (for filtering purposes)
|
||||
*/
|
||||
@ -113,6 +121,7 @@ export async function getAllUsers() {
|
||||
|
||||
export const userApi = {
|
||||
searchUsers,
|
||||
getUserById,
|
||||
ensureUserExists,
|
||||
assignRole,
|
||||
updateUserRole,
|
||||
|
||||
@ -362,12 +362,12 @@ export async function getPauseDetails(requestId: string) {
|
||||
}
|
||||
|
||||
export function getWorkNoteAttachmentPreviewUrl(attachmentId: string): string {
|
||||
const baseURL = import.meta.env.VITE_BASE_URL || 'http://localhost:5000';
|
||||
const baseURL = import.meta.env.VITE_BASE_URL || '';
|
||||
return `${baseURL}/api/v1/workflows/work-notes/attachments/${attachmentId}/preview`;
|
||||
}
|
||||
|
||||
export function getDocumentPreviewUrl(documentId: string): string {
|
||||
const baseURL = import.meta.env.VITE_BASE_URL || 'http://localhost:5000';
|
||||
const baseURL = import.meta.env.VITE_BASE_URL || '';
|
||||
return `${baseURL}/api/v1/workflows/documents/${documentId}/preview`;
|
||||
}
|
||||
|
||||
@ -404,7 +404,7 @@ function extractFilenameFromContentDisposition(contentDisposition: string | null
|
||||
}
|
||||
|
||||
export async function downloadDocument(documentId: string): Promise<void> {
|
||||
const baseURL = import.meta.env.VITE_BASE_URL || 'http://localhost:5000';
|
||||
const baseURL = import.meta.env.VITE_BASE_URL || '';
|
||||
const downloadUrl = `${baseURL}/api/v1/workflows/documents/${documentId}/download`;
|
||||
const isProduction = import.meta.env.PROD || import.meta.env.MODE === 'production';
|
||||
|
||||
@ -449,7 +449,7 @@ export async function downloadDocument(documentId: string): Promise<void> {
|
||||
}
|
||||
|
||||
export async function downloadWorkNoteAttachment(attachmentId: string): Promise<void> {
|
||||
const downloadBaseURL = import.meta.env.VITE_BASE_URL || 'http://localhost:5000';
|
||||
const downloadBaseURL = import.meta.env.VITE_BASE_URL || '';
|
||||
const downloadUrl = `${downloadBaseURL}/api/v1/workflows/work-notes/attachments/${attachmentId}/download`;
|
||||
const isProduction = import.meta.env.PROD || import.meta.env.MODE === 'production';
|
||||
|
||||
|
||||
@ -21,5 +21,8 @@ export function sanitizeHTML(html: string): string {
|
||||
// 5. Remove meta and link tags (except for purely visual ones if needed, but safer to remove)
|
||||
sanitized = sanitized.replace(/<(meta|link|iframe|object|embed|applet)[^>]*>/gi, '');
|
||||
|
||||
// 6. Explicitly remove <a> tags to prevent HTML injection of links (VAPT compliance)
|
||||
sanitized = sanitized.replace(/<a[^>]*>([\s\S]*?)<\/a>/gi, '$1');
|
||||
|
||||
return sanitized;
|
||||
}
|
||||
|
||||
@ -19,9 +19,8 @@ export function getSocketBaseUrl(): string {
|
||||
return apiBaseUrl.replace(/\/api\/v1\/?$/, '');
|
||||
}
|
||||
|
||||
// Development fallback
|
||||
console.warn('[Socket] No VITE_BASE_URL or VITE_API_BASE_URL found, using localhost:5000');
|
||||
return 'http://localhost:5000';
|
||||
// Dev fallback
|
||||
return '';
|
||||
}
|
||||
|
||||
export function getSocket(baseUrl?: string): Socket {
|
||||
|
||||
@ -86,7 +86,7 @@ export class TokenManager {
|
||||
return; // No-op - rely on httpOnly cookies
|
||||
}
|
||||
|
||||
// Development only: Store for debugging and cross-port requests
|
||||
// Dev only: Store for debugging and cross-port requests
|
||||
localStorage.setItem(ACCESS_TOKEN_KEY, token);
|
||||
}
|
||||
|
||||
@ -100,7 +100,7 @@ export class TokenManager {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Development: Return from localStorage
|
||||
// Dev: Return from localStorage
|
||||
return localStorage.getItem(ACCESS_TOKEN_KEY);
|
||||
}
|
||||
|
||||
@ -113,7 +113,7 @@ export class TokenManager {
|
||||
return; // No-op - rely on httpOnly cookies
|
||||
}
|
||||
|
||||
// Development only
|
||||
// Dev only
|
||||
localStorage.setItem(REFRESH_TOKEN_KEY, token);
|
||||
}
|
||||
|
||||
@ -163,7 +163,7 @@ export class TokenManager {
|
||||
|
||||
|
||||
static clearAll(): void {
|
||||
// CRITICAL: Set logout flag in sessionStorage FIRST (before clearing)
|
||||
//: Set logout flag in sessionStorage FIRST (before clearing)
|
||||
// This flag survives the redirect and prevents auto-authentication
|
||||
try {
|
||||
sessionStorage.setItem('__logout_in_progress__', 'true');
|
||||
@ -193,7 +193,7 @@ export class TokenManager {
|
||||
return;
|
||||
}
|
||||
|
||||
// DEVELOPMENT MODE: Clear everything
|
||||
// Dev MODE: Clear everything
|
||||
const authKeys = [
|
||||
ACCESS_TOKEN_KEY,
|
||||
REFRESH_TOKEN_KEY,
|
||||
|
||||
2
src/vite-env.d.ts
vendored
2
src/vite-env.d.ts
vendored
@ -7,6 +7,8 @@ interface ImportMetaEnv {
|
||||
readonly VITE_APP_VERSION: string;
|
||||
readonly VITE_ENABLE_ANALYTICS: string;
|
||||
readonly VITE_ENABLE_DEBUG: string;
|
||||
readonly VITE_TANFLOW_BASE_URL: string;
|
||||
readonly VITE_TANFLOW_CLIENT_ID: string;
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
|
||||
@ -60,9 +60,24 @@ const ensureChunkOrder = () => {
|
||||
};
|
||||
};
|
||||
|
||||
// Plugin to replace axios localhost fallback for VAPT compliance
|
||||
const replaceAxiosLocalhost = () => {
|
||||
return {
|
||||
name: 'replace-axios-localhost',
|
||||
transform(code: string, id: string) {
|
||||
// Target the specific utils.js file in axios where the localhost string exists
|
||||
if (id.includes('node_modules') && id.includes('axios') && id.includes('utils.js')) {
|
||||
// Replace 'http://localhost' with empty string
|
||||
return code.replace(/'http:\/\/localhost'/g, "''");
|
||||
}
|
||||
return null;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react(), suppressCssWarnings(), ensureChunkOrder()],
|
||||
plugins: [react(), suppressCssWarnings(), ensureChunkOrder(), replaceAxiosLocalhost()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, './src'),
|
||||
@ -78,7 +93,7 @@ export default defineConfig({
|
||||
},
|
||||
build: {
|
||||
outDir: 'dist',
|
||||
sourcemap: true,
|
||||
sourcemap: false,
|
||||
// CSS minification warning is harmless - it's a known issue with certain Tailwind class combinations
|
||||
// Re-enable minification with settings that preserve initialization order
|
||||
// The "Cannot access 'React' before initialization" error is fixed by keeping React in main bundle
|
||||
@ -119,7 +134,7 @@ export default defineConfig({
|
||||
chunkFileNames: 'assets/[name]-[hash].js',
|
||||
// Explicitly define chunk order - React must load before Radix UI
|
||||
manualChunks(id) {
|
||||
// CRITICAL FIX: Keep React in main bundle OR ensure it loads first
|
||||
// IMPORTANT: Keep React in main bundle OR ensure it loads first
|
||||
// The "Cannot access 'React' before initialization" error occurs when
|
||||
// Radix UI components try to access React before it's initialized
|
||||
// Option 1: Don't split React - keep it in main bundle (most reliable)
|
||||
@ -128,7 +143,7 @@ export default defineConfig({
|
||||
// For now, let's keep React in main bundle to avoid initialization issues
|
||||
// Only split other vendors
|
||||
|
||||
// Radix UI - CRITICAL: ALL Radix packages MUST stay together in ONE chunk
|
||||
// Radix UI - IMPORTANT: ALL Radix packages MUST stay together in ONE chunk
|
||||
// This chunk will import React from the main bundle, avoiding initialization issues
|
||||
if (id.includes('node_modules/@radix-ui')) {
|
||||
return 'radix-vendor';
|
||||
@ -172,7 +187,7 @@ export default defineConfig({
|
||||
chunkSizeWarningLimit: 1500, // Increased limit since we have manual chunks
|
||||
},
|
||||
esbuild: {
|
||||
// CRITICAL: Strip all legal comments to prevent "Suspicious Comments" alerts (e.g. from Redux docs)
|
||||
//: Strip all legal comments to prevent "Suspicious Comments" alerts (e.g. from Redux docs)
|
||||
legalComments: 'none',
|
||||
},
|
||||
optimizeDeps: {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user