@@ -55,12 +55,12 @@ export const AdminHeader: React.FC<AdminHeaderProps> = ({ onMenuClick }) => {
|
||||
},
|
||||
});
|
||||
|
||||
// Clear old notifications mutation
|
||||
const clearOldMutation = useMutation({
|
||||
mutationFn: notificationsService.clearOldNotifications,
|
||||
// Clear notifications mutation
|
||||
const clearAllMutation = useMutation({
|
||||
mutationFn: notificationsService.clearAllNotifications,
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['notifications'] });
|
||||
toast.success(t('admin.notificationToasts.clearedOld', { count: data.deletedCount }));
|
||||
toast.success(t('admin.notificationToasts.clearedAll', { count: data.deletedCount }));
|
||||
},
|
||||
});
|
||||
|
||||
@@ -128,12 +128,12 @@ export const AdminHeader: React.FC<AdminHeaderProps> = ({ onMenuClick }) => {
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => clearOldMutation.mutate()}
|
||||
onClick={() => clearAllMutation.mutate()}
|
||||
className="text-xs text-neutral-600 hover:text-neutral-700 flex items-center gap-1"
|
||||
title={t('admin.clearOld')}
|
||||
title={t('admin.clearAll')}
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
{t('admin.clearOld')}
|
||||
{t('admin.clearAll')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
inferGallerySlugFromLocation,
|
||||
resolveSlugFromRequestUrl,
|
||||
} from '../utils/galleryAuthStorage';
|
||||
import { getApiBaseUrl } from '../utils/url';
|
||||
|
||||
// Maintenance mode callback
|
||||
let maintenanceModeCallback: ((enabled: boolean) => void) | null = null;
|
||||
@@ -15,7 +16,7 @@ export const setMaintenanceModeCallback = (callback: (enabled: boolean) => void)
|
||||
|
||||
// Create axios instance
|
||||
export const api = axios.create({
|
||||
baseURL: import.meta.env.VITE_API_URL || '/api',
|
||||
baseURL: getApiBaseUrl(),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
|
||||
@@ -13,6 +13,7 @@ interface AdminAuthContextType {
|
||||
error: string | null;
|
||||
mustChangePassword: boolean;
|
||||
updatePasswordChanged: () => void;
|
||||
updateProfile: (user: AdminUser) => void;
|
||||
}
|
||||
|
||||
const AdminAuthContext = createContext<AdminAuthContextType | undefined>(undefined);
|
||||
@@ -104,6 +105,11 @@ export const AdminAuthProvider: React.FC<AdminAuthProviderProps> = ({ children }
|
||||
}
|
||||
};
|
||||
|
||||
const updateProfile = (updatedUser: AdminUser) => {
|
||||
setUser(updatedUser);
|
||||
sessionStorage.setItem('admin_user', JSON.stringify(updatedUser));
|
||||
};
|
||||
|
||||
return (
|
||||
<AdminAuthContext.Provider
|
||||
value={{
|
||||
@@ -115,6 +121,7 @@ export const AdminAuthProvider: React.FC<AdminAuthProviderProps> = ({ children }
|
||||
error,
|
||||
mustChangePassword,
|
||||
updatePasswordChanged,
|
||||
updateProfile,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
|
||||
@@ -1080,7 +1080,7 @@
|
||||
"viewAllNotifications": "Alle Benachrichtigungen anzeigen",
|
||||
"noNotifications": "Keine neuen Benachrichtigungen",
|
||||
"markAllRead": "Alle als gelesen markieren",
|
||||
"clearOld": "Alte löschen",
|
||||
"clearAll": "Alle löschen",
|
||||
"close": "Schließen",
|
||||
"noNotificationsMessage": "Keine Benachrichtigungen",
|
||||
"notificationMessages": {
|
||||
@@ -1113,11 +1113,13 @@
|
||||
"archiveDownloaded": "Archiv für \"{{eventName}}\" heruntergeladen",
|
||||
"archiveDeleted": "Archiv für \"{{eventName}}\" gelöscht",
|
||||
"archiveRestored": "Archiv für \"{{eventName}}\" wiederhergestellt",
|
||||
"systemActivity": "Systemaktivität: {{type}}"
|
||||
"systemActivity": "Systemaktivität: {{type}}",
|
||||
"adminProfileUpdated": "Admin-Profil aktualisiert von {{actorName}}"
|
||||
},
|
||||
"notificationToasts": {
|
||||
"markedAllRead": "Alle Benachrichtigungen als gelesen markiert",
|
||||
"clearedOld": "{{count}} alte Benachrichtigungen gelöscht"
|
||||
"clearedAll": "{{count}} Benachrichtigungen gelöscht",
|
||||
"profileUpdated": "Admin-Profil aktualisiert"
|
||||
},
|
||||
"viewAllNotifications": "Alle Benachrichtigungen anzeigen",
|
||||
"noNotifications": "Keine neuen Benachrichtigungen",
|
||||
@@ -1125,6 +1127,16 @@
|
||||
"markAllAsRead": "Alle als gelesen markieren",
|
||||
"notificationSettings": "Benachrichtigungseinstellungen",
|
||||
"changePassword": "Passwort ändern",
|
||||
"accountSettings": {
|
||||
"title": "Admin-Konto",
|
||||
"description": "Aktualisiere die Zugangsdaten für die PicPeak-Administration.",
|
||||
"username": "Benutzername",
|
||||
"usernamePlaceholder": "Admin",
|
||||
"email": "E-Mail",
|
||||
"emailPlaceholder": "admin@example.com",
|
||||
"updateButton": "Profil aktualisieren"
|
||||
},
|
||||
"profileUpdateError": "Admin-Profil konnte nicht aktualisiert werden. Bitte versuche es erneut.",
|
||||
"loadingDashboard": "Dashboard wird geladen...",
|
||||
"activeEvents": "Aktive Veranstaltungen",
|
||||
"expiringSoon": "Demnächst ablaufend",
|
||||
|
||||
@@ -818,7 +818,7 @@
|
||||
"viewAllNotifications": "View all notifications",
|
||||
"noNotifications": "No new notifications",
|
||||
"markAllRead": "Mark all read",
|
||||
"clearOld": "Clear old",
|
||||
"clearAll": "Clear all",
|
||||
"close": "Close",
|
||||
"noNotificationsMessage": "No notifications",
|
||||
"notificationMessages": {
|
||||
@@ -851,16 +851,28 @@
|
||||
"archiveDownloaded": "Archive downloaded for \"{{eventName}}\"",
|
||||
"archiveDeleted": "Archive deleted for \"{{eventName}}\"",
|
||||
"archiveRestored": "Archive restored for \"{{eventName}}\"",
|
||||
"systemActivity": "System activity: {{type}}"
|
||||
"systemActivity": "System activity: {{type}}",
|
||||
"adminProfileUpdated": "Admin profile updated by {{actorName}}"
|
||||
},
|
||||
"notificationToasts": {
|
||||
"markedAllRead": "All notifications marked as read",
|
||||
"clearedOld": "Cleared {{count}} old notifications"
|
||||
"clearedAll": "Cleared {{count}} notifications",
|
||||
"profileUpdated": "Admin profile updated"
|
||||
},
|
||||
"markAsRead": "Mark as read",
|
||||
"markAllAsRead": "Mark all as read",
|
||||
"notificationSettings": "Notification Settings",
|
||||
"changePassword": "Change Password",
|
||||
"accountSettings": {
|
||||
"title": "Admin account",
|
||||
"description": "Update the credentials used to sign in to PicPeak.",
|
||||
"username": "Username",
|
||||
"usernamePlaceholder": "Admin",
|
||||
"email": "Email",
|
||||
"emailPlaceholder": "admin@example.com",
|
||||
"updateButton": "Update profile"
|
||||
},
|
||||
"profileUpdateError": "Unable to update admin profile. Please try again.",
|
||||
"loadingDashboard": "Loading dashboard...",
|
||||
"activeEvents": "Active Events",
|
||||
"expiringSoon": "Expiring Soon",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState } from 'react';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import {
|
||||
Save,
|
||||
Database,
|
||||
@@ -19,7 +19,9 @@ import { CategoryManager } from '../../components/admin/CategoryManager';
|
||||
import { WordFilterManager } from '../../components/admin/WordFilterManager';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { settingsService } from '../../services/settings.service';
|
||||
import { authService } from '../../services/auth.service';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useAdminAuth } from '../../contexts';
|
||||
|
||||
const BYTES_PER_GB = 1024 * 1024 * 1024;
|
||||
|
||||
@@ -56,6 +58,23 @@ export const SettingsPage: React.FC = () => {
|
||||
const [activeTab, setActiveTab] = useState<'general' | 'status' | 'security' | 'categories' | 'analytics' | 'moderation'>('general');
|
||||
const queryClient = useQueryClient();
|
||||
const { t, i18n } = useTranslation();
|
||||
const { user, updateProfile: updateAuthProfile } = useAdminAuth();
|
||||
|
||||
const [profileForm, setProfileForm] = useState({
|
||||
username: user?.username ?? '',
|
||||
email: user?.email ?? '',
|
||||
});
|
||||
const [profileError, setProfileError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
setProfileForm({ username: user.username, email: user.email });
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
const isProfileDirty = user
|
||||
? (profileForm.username !== user.username || profileForm.email !== user.email)
|
||||
: Boolean(profileForm.username.trim() || profileForm.email.trim());
|
||||
|
||||
// Fetch settings
|
||||
const { data: settings, isLoading } = useQuery({
|
||||
@@ -78,6 +97,20 @@ export const SettingsPage: React.FC = () => {
|
||||
refetchInterval: 30000 // Refresh every 30 seconds
|
||||
});
|
||||
|
||||
const updateProfileMutation = useMutation({
|
||||
mutationFn: authService.updateAdminProfile,
|
||||
onSuccess: (updatedUser) => {
|
||||
updateAuthProfile(updatedUser);
|
||||
setProfileError(null);
|
||||
toast.success(t('admin.notificationToasts.profileUpdated'));
|
||||
},
|
||||
onError: (error: any) => {
|
||||
const message = error?.response?.data?.error || t('admin.profileUpdateError');
|
||||
setProfileError(message);
|
||||
toast.error(message);
|
||||
},
|
||||
});
|
||||
|
||||
// General settings state
|
||||
const [generalSettings, setGeneralSettings] = useState({
|
||||
site_url: '',
|
||||
@@ -343,6 +376,19 @@ export const SettingsPage: React.FC = () => {
|
||||
}
|
||||
});
|
||||
|
||||
const handleProfileSubmit = (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
if (!isProfileDirty || updateProfileMutation.isPending) {
|
||||
return;
|
||||
}
|
||||
|
||||
setProfileError(null);
|
||||
updateProfileMutation.mutate({
|
||||
username: profileForm.username.trim(),
|
||||
email: profileForm.email.trim(),
|
||||
});
|
||||
};
|
||||
|
||||
const handleSaveCapacityOverride = () => {
|
||||
if (saveCapacityOverrideMutation.isPending) {
|
||||
return;
|
||||
@@ -466,6 +512,46 @@ export const SettingsPage: React.FC = () => {
|
||||
{/* General Settings Tab */}
|
||||
{activeTab === 'general' && (
|
||||
<div className="space-y-6">
|
||||
<Card padding="md">
|
||||
<h2 className="text-lg font-semibold text-neutral-900 mb-2">{t('admin.accountSettings.title')}</h2>
|
||||
<p className="text-sm text-neutral-500 mb-4">{t('admin.accountSettings.description')}</p>
|
||||
<form className="space-y-4" onSubmit={handleProfileSubmit}>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-neutral-700 mb-1">
|
||||
{t('admin.accountSettings.username')}
|
||||
</label>
|
||||
<Input
|
||||
value={profileForm.username}
|
||||
onChange={(e) => setProfileForm(prev => ({ ...prev, username: e.target.value }))}
|
||||
placeholder={t('admin.accountSettings.usernamePlaceholder')}
|
||||
maxLength={120}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-neutral-700 mb-1">
|
||||
{t('admin.accountSettings.email')}
|
||||
</label>
|
||||
<Input
|
||||
type="email"
|
||||
value={profileForm.email}
|
||||
onChange={(e) => setProfileForm(prev => ({ ...prev, email: e.target.value }))}
|
||||
placeholder={t('admin.accountSettings.emailPlaceholder')}
|
||||
/>
|
||||
</div>
|
||||
{profileError && (
|
||||
<p className="text-sm text-red-600">{profileError}</p>
|
||||
)}
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={!isProfileDirty || updateProfileMutation.isPending}
|
||||
>
|
||||
{updateProfileMutation.isPending ? t('common.saving') : t('admin.accountSettings.updateButton')}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Card>
|
||||
|
||||
<Card padding="md">
|
||||
<h2 className="text-lg font-semibold text-neutral-900 mb-4">{t('settings.general.siteConfiguration')}</h2>
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { api } from '../config/api';
|
||||
import type { LoginResponse, GalleryAuthResponse } from '../types';
|
||||
import type { LoginResponse, GalleryAuthResponse, AdminUser } from '../types';
|
||||
import { normalizeRequirePassword } from '../utils/accessControl';
|
||||
|
||||
const normalizeGalleryResponse = (response: GalleryAuthResponse): GalleryAuthResponse => ({
|
||||
@@ -61,4 +61,9 @@ export const authService = {
|
||||
// Ignore; cookie will naturally expire if removal fails
|
||||
}
|
||||
},
|
||||
|
||||
async updateAdminProfile(profile: { username: string; email: string }): Promise<AdminUser> {
|
||||
const response = await api.put<{ user: AdminUser }>('/auth/admin/profile', profile);
|
||||
return response.data.user;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -38,9 +38,9 @@ export const notificationsService = {
|
||||
await api.put('/admin/notifications/read-all');
|
||||
},
|
||||
|
||||
// Clear old notifications
|
||||
async clearOldNotifications(): Promise<{ deletedCount: number }> {
|
||||
const response = await api.delete('/admin/notifications/clear-old');
|
||||
// Clear all notifications
|
||||
async clearAllNotifications(): Promise<{ deletedCount: number }> {
|
||||
const response = await api.delete('/admin/notifications/clear-all');
|
||||
return response.data;
|
||||
},
|
||||
|
||||
@@ -133,6 +133,10 @@ export const notificationsService = {
|
||||
return t('admin.notificationMessages.generalSettingsUpdated');
|
||||
case 'security_settings_updated':
|
||||
return t('admin.notificationMessages.securitySettingsUpdated');
|
||||
case 'admin_profile_updated':
|
||||
return t('admin.notificationMessages.adminProfileUpdated', {
|
||||
actorName: notification.actorName,
|
||||
});
|
||||
case 'theme_updated':
|
||||
return t('admin.notificationMessages.themeUpdated');
|
||||
case 'archive_downloaded':
|
||||
@@ -184,6 +188,8 @@ export const notificationsService = {
|
||||
case 'security_settings_updated':
|
||||
case 'theme_updated':
|
||||
return { icon: 'Settings', color: 'text-gray-600' };
|
||||
case 'admin_profile_updated':
|
||||
return { icon: 'User', color: 'text-primary-600' };
|
||||
case 'email_template_updated':
|
||||
case 'email_config_updated':
|
||||
return { icon: 'Mail', color: 'text-teal-600' };
|
||||
@@ -209,4 +215,4 @@ export const notificationsService = {
|
||||
return { icon: 'Bell', color: 'text-gray-600' };
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { getApiBaseUrl, buildResourceUrl } from '../url';
|
||||
const originalLocation = window.location;
|
||||
|
||||
const setLocation = (origin: string) => {
|
||||
const parsed = new URL(origin);
|
||||
Object.defineProperty(window, 'location', {
|
||||
value: {
|
||||
origin: parsed.origin,
|
||||
hostname: parsed.hostname,
|
||||
href: parsed.href,
|
||||
},
|
||||
configurable: true,
|
||||
});
|
||||
};
|
||||
|
||||
describe('url utilities', () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllEnvs();
|
||||
setLocation('https://example.com');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
Object.defineProperty(window, 'location', {
|
||||
value: originalLocation,
|
||||
configurable: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns relative API base by default', () => {
|
||||
vi.unstubAllEnvs();
|
||||
expect(getApiBaseUrl()).toBe('/api');
|
||||
expect(buildResourceUrl('/api/gallery/test')).toBe('https://example.com/api/gallery/test');
|
||||
});
|
||||
|
||||
it('honours absolute API URLs for non-local hosts', () => {
|
||||
vi.stubEnv('VITE_API_URL', 'https://api.picpeak.cloud/api');
|
||||
expect(getApiBaseUrl()).toBe('https://api.picpeak.cloud/api');
|
||||
expect(buildResourceUrl('/api/gallery/test')).toBe('https://api.picpeak.cloud/api/gallery/test');
|
||||
expect(buildResourceUrl('/uploads/logo.png')).toBe('https://api.picpeak.cloud/uploads/logo.png');
|
||||
});
|
||||
|
||||
it('falls back to relative when build-time URL is localhost but browser host is remote', () => {
|
||||
vi.stubEnv('VITE_API_URL', 'http://localhost:3001/api');
|
||||
setLocation('https://photos.example.com');
|
||||
expect(getApiBaseUrl()).toBe('/api');
|
||||
expect(buildResourceUrl('/api/gallery/test')).toBe('https://photos.example.com/api/gallery/test');
|
||||
expect(buildResourceUrl('uploads/logo.png')).toBe('https://photos.example.com/uploads/logo.png');
|
||||
});
|
||||
|
||||
it('keeps localhost API URL when browser is also localhost', () => {
|
||||
vi.stubEnv('VITE_API_URL', 'http://127.0.0.1:3001/api');
|
||||
setLocation('http://127.0.0.1:3000');
|
||||
expect(getApiBaseUrl()).toBe('http://127.0.0.1:3001/api');
|
||||
expect(buildResourceUrl('/api/gallery/test')).toBe('http://127.0.0.1:3001/api/gallery/test');
|
||||
});
|
||||
});
|
||||
+108
-20
@@ -2,39 +2,126 @@
|
||||
* Utility functions for URL handling in production environments
|
||||
*/
|
||||
|
||||
const ABSOLUTE_URL_REGEX = /^https?:\/\//i;
|
||||
const LOCAL_HOSTNAMES = new Set(['localhost', '127.0.0.1', '[::1]']);
|
||||
|
||||
const isBrowser = typeof window !== 'undefined' && typeof window.location !== 'undefined';
|
||||
|
||||
const normalizeBase = (value: string): string => value.replace(/\/+$/, '');
|
||||
|
||||
const getEnvApiUrl = (): string | undefined => {
|
||||
const raw = import.meta.env?.VITE_API_URL;
|
||||
if (!raw || raw === '') {
|
||||
return undefined;
|
||||
}
|
||||
if (raw === '/') {
|
||||
return '/api';
|
||||
}
|
||||
return raw;
|
||||
};
|
||||
|
||||
const isLocalHostname = (hostname: string): boolean => LOCAL_HOSTNAMES.has(hostname.toLowerCase());
|
||||
|
||||
const shouldFallbackToRelative = (url: string): boolean => {
|
||||
if (!ABSOLUTE_URL_REGEX.test(url)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!isBrowser) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
const envHostIsLocal = isLocalHostname(parsed.hostname);
|
||||
const browserHost = window.location.hostname?.toLowerCase?.() ?? '';
|
||||
const browserHostIsLocal = isLocalHostname(browserHost);
|
||||
|
||||
// Only fallback when the build-time URL points to localhost/loopback
|
||||
// but the runtime browser location is remote (non-local).
|
||||
return envHostIsLocal && !browserHostIsLocal;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const buildFromOrigin = (path: string): string => {
|
||||
if (!isBrowser) {
|
||||
return path;
|
||||
}
|
||||
const normalizedPath = path.startsWith('/') ? path : `/${path}`;
|
||||
return `${window.location.origin}${normalizedPath}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the base API URL, preferring relative URLs for production
|
||||
* Get the base API URL, preferring relative URLs for production and
|
||||
* falling back to relative when the build was created with localhost
|
||||
* endpoints but is being accessed from a remote browser.
|
||||
* @returns The API base URL
|
||||
*/
|
||||
export const getApiBaseUrl = (): string => {
|
||||
// If VITE_API_URL is explicitly set, use it
|
||||
if (import.meta.env.VITE_API_URL && import.meta.env.VITE_API_URL !== '/api') {
|
||||
return import.meta.env.VITE_API_URL;
|
||||
const envUrl = getEnvApiUrl();
|
||||
|
||||
if (envUrl && envUrl !== '/api') {
|
||||
if (ABSOLUTE_URL_REGEX.test(envUrl) && shouldFallbackToRelative(envUrl)) {
|
||||
return '/api';
|
||||
}
|
||||
return envUrl;
|
||||
}
|
||||
|
||||
// In production, use relative URL
|
||||
|
||||
return '/api';
|
||||
};
|
||||
|
||||
const buildFromAbsoluteApi = (base: string, path: string): string => {
|
||||
const trimmedBase = normalizeBase(base);
|
||||
|
||||
// When the path already targets /api we want to preserve the suffix
|
||||
if (path.startsWith('/api')) {
|
||||
const pathWithoutLeadingApi = path.replace(/^\/api/, '');
|
||||
return `${trimmedBase}${pathWithoutLeadingApi}`;
|
||||
}
|
||||
|
||||
// For non-API assets (uploads, thumbnails, etc.) drop any /api suffix
|
||||
const origin = trimmedBase.replace(/\/api$/, '');
|
||||
const normalizedPath = path.startsWith('/') ? path : `/${path}`;
|
||||
return `${origin}${normalizedPath}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Build a full URL for resources (images, files, etc.)
|
||||
* In production, this will use the current origin
|
||||
* In production, this will prefer the current origin unless an absolute
|
||||
* API URL is explicitly configured and applicable.
|
||||
* @param path - The resource path
|
||||
* @returns The full URL
|
||||
*/
|
||||
export const buildResourceUrl = (path: string): string => {
|
||||
// Remove leading slash if present
|
||||
const cleanPath = path.startsWith('/') ? path.slice(1) : path;
|
||||
|
||||
// If we have an explicit API URL that's not relative, use it
|
||||
const apiUrl = import.meta.env.VITE_API_URL;
|
||||
if (apiUrl && apiUrl !== '/api' && apiUrl.startsWith('http')) {
|
||||
const baseUrl = apiUrl.replace(/\/api\/?$/, ''); // Remove /api suffix if present
|
||||
return `${baseUrl}/${cleanPath}`;
|
||||
if (!path) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// In production (relative API), use current origin
|
||||
return `${window.location.origin}/${cleanPath}`;
|
||||
|
||||
// Absolute paths (http/https) should generally be respected,
|
||||
// except when they point to localhost but we're running remotely.
|
||||
if (ABSOLUTE_URL_REGEX.test(path)) {
|
||||
if (!shouldFallbackToRelative(path)) {
|
||||
return path;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = new URL(path);
|
||||
return buildFromOrigin(`${parsed.pathname}${parsed.search}${parsed.hash}`);
|
||||
} catch {
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
const normalizedPath = path.startsWith('/') ? path : `/${path}`;
|
||||
const apiBase = getApiBaseUrl();
|
||||
|
||||
if (ABSOLUTE_URL_REGEX.test(apiBase)) {
|
||||
return buildFromAbsoluteApi(apiBase, normalizedPath);
|
||||
}
|
||||
|
||||
return buildFromOrigin(normalizedPath);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -42,5 +129,6 @@ export const buildResourceUrl = (path: string): string => {
|
||||
* @returns True if in production mode
|
||||
*/
|
||||
export const isProductionMode = (): boolean => {
|
||||
return !import.meta.env.VITE_API_URL || import.meta.env.VITE_API_URL === '/api';
|
||||
};
|
||||
const apiBase = getApiBaseUrl();
|
||||
return !ABSOLUTE_URL_REGEX.test(apiBase);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user