diff --git a/components/languageSwitcher.tsx b/components/languageSwitcher.tsx index 4131523..b8cce90 100644 --- a/components/languageSwitcher.tsx +++ b/components/languageSwitcher.tsx @@ -39,7 +39,7 @@ const LanguageSwitcher = () => { open={Boolean(anchorEl)} onClose={handleClose} > - {locales.map((lng) => { + {locales?.map((lng) => { if (lng === locale) return null; return ( changeLanguage(lng)}> diff --git a/components/protectedRoute.tsx b/components/protectedRoute.tsx index 4c2adc9..6a6e787 100644 --- a/components/protectedRoute.tsx +++ b/components/protectedRoute.tsx @@ -10,9 +10,10 @@ interface ProtectedRouteProps { allowedRoles: UserRole[]; deniedMessage?: string; bypass?: boolean; + autoRedirect?: boolean; } -const ProtectedRoute = ({ children, allowedRoles, deniedMessage, bypass = false }: ProtectedRouteProps) => { +const ProtectedRoute = ({ children, allowedRoles, deniedMessage, bypass = false, autoRedirect = false }: ProtectedRouteProps) => { const { data: session, status } = useSession() const router = useRouter(); @@ -20,10 +21,9 @@ const ProtectedRoute = ({ children, allowedRoles, deniedMessage, bypass = false console.log("session.role:" + session?.user?.role); if (!status || status === "unauthenticated") { // Redirect to the sign-in page - if (!bypass) { + if (autoRedirect) { signIn(); } - return null; } else { console.log("session.role:" + session?.user?.role); @@ -41,14 +41,27 @@ const ProtectedRoute = ({ children, allowedRoles, deniedMessage, bypass = false if (deniedMessage !== undefined) { return
{deniedMessage}
; } - return
Нямате достъп до тази страница. Ако мислите, че това е грешка, моля, свържете се с администраторите
; + return ( + <> +
+
+

{session?.user?.email},

+

{`Нямате достъп до тази страница. Ако мислите, че това е грешка, моля, свържете се с администраторите`}

+
+
+ ); + } if (status === "loading") { return
Зареждане...
; } - if (!session) return Защитено съдържание. Впишете се.. - return children; + if (!session) { + if (deniedMessage !== undefined) { + return
{deniedMessage}
; + } + return Защитено съдържание. Впишете се.. + } }; export default ProtectedRoute; diff --git a/components/sidebar.tsx b/components/sidebar.tsx index 57d86b0..34d2ceb 100644 --- a/components/sidebar.tsx +++ b/components/sidebar.tsx @@ -105,19 +105,22 @@ export default function Sidebar({ isSidebarOpen, toggleSidebar }) { useEffect(() => { const fetchLocations = async () => { try { - const response = await axiosInstance.get('/api/data/locations'); // Adjust the API endpoint as needed - const locationsData = response.data - .filter(location => location.isActive === true) - .map(location => ({ - text: location.name, - url: `/cart/locations/${location.id}`, - })); - // Find the "Locations" menu item and populate its children with locationsData - const menuIndex = sidemenu.findIndex(item => item.id === "locations"); - if (menuIndex !== -1) { - sidemenu[menuIndex].children = locationsData; + if (session) { // Don't fetch locations if the user is not authenticated + + const response = await axiosInstance.get('/api/data/locations'); // Adjust the API endpoint as needed + const locationsData = response.data + .filter(location => location.isActive === true) + .map(location => ({ + text: location.name, + url: `/cart/locations/${location.id}`, + })); + // Find the "Locations" menu item and populate its children with locationsData + const menuIndex = sidemenu.findIndex(item => item.id === "locations"); + if (menuIndex !== -1) { + sidemenu[menuIndex].children = locationsData; + } + //setLocations(locationsData); // Optional, if you need to use locations elsewhere } - //setLocations(locationsData); // Optional, if you need to use locations elsewhere } catch (error) { console.error("Error fetching locations:", error); } @@ -174,16 +177,17 @@ function UserSection({ session }) { } function SignInButton() { - const t = useTranslations('common'); + // const t = useTranslations('common'); return (
signIn()}> - + + {/* */}
); } function UserDetails({ session }) { - const t = useTranslations('common'); + // const t = useTranslations('common'); return ( <>
@@ -194,7 +198,10 @@ function UserDetails({ session }) {

{session.user.name}

{session.user.role}

- { e.preventDefault(); signOut(); }}>{t('logout')} + { e.preventDefault(); signOut(); }}> + {/* {t('logout')} */} + изход +
diff --git a/next.config.js b/next.config.js index 46f794f..bc25166 100644 --- a/next.config.js +++ b/next.config.js @@ -56,6 +56,6 @@ module.exports = withPWA({ // using https://next-intl-docs.vercel.app/docs/getting-started/pages-router locales: ['bg', 'en', 'ru'], defaultLocale: 'bg', - autoDetect: false, + localeDetection: false, }, }) \ No newline at end of file diff --git a/pages/_app.tsx b/pages/_app.tsx index 897ed80..e0934da 100644 --- a/pages/_app.tsx +++ b/pages/_app.tsx @@ -28,26 +28,27 @@ import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs' export default function App({ Component, pageProps: { session, ...pageProps }, }: AppProps<{ session: Session }>) { // console.log(pageProps); const router = useRouter(); + const [locale, setLocale] = useState(router.locale || 'bg'); const [messages, setMessages] = useState({}); useEffect(() => { console.log("Current locale:", router.locale); async function loadLocaleData() { // Replace the static import with a fetch request - const res = await fetch(`/api/translations/${router.locale}`); + const res = await fetch(`/api/translations/${locale}`); if (res.ok) { const localeMessages = await res.json(); - console.log("Loaded messages for locale:", router.locale, localeMessages); + console.log("Loaded messages for locale:", locale, localeMessages); setMessages(localeMessages); } else { - const localeMessages = await import(`../content/i18n/${router.locale}.json`); setMessages(localeMessages.default); + const localeMessages = await import(`../content/i18n/${locale}.json`); setMessages(localeMessages.default); } - console.log("Loaded locale '", router.locale, "' ",); + console.log("Loaded locale '", locale, "' ",); //console.log("Loaded messages for locale:", router.locale, localeMessages.default); } loadLocaleData(); - }, [router.locale]); + }, [locale]); // useEffect(() => { // async function loadLocaleData() { @@ -101,7 +102,7 @@ export default function App({ Component, pageProps: { session, ...pageProps }, } return ( <> @@ -110,7 +111,7 @@ export default function App({ Component, pageProps: { session, ...pageProps }, } - + ) } diff --git a/pages/api/data/[...nextcrud].ts b/pages/api/data/[...nextcrud].ts index 31101c7..c3aa01b 100644 --- a/pages/api/data/[...nextcrud].ts +++ b/pages/api/data/[...nextcrud].ts @@ -33,6 +33,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => { if (req.method === 'DELETE') { switch (targetTable) { case 'publishers': + case 'availabilities': const targetId = req.query.nextcrud[1]; logger.info('[nextCrud] ' + targetTable + ': ' + targetId + ' DELETED by ' + session.user.email); break; diff --git a/pages/cart/publishers/edit/[id].tsx b/pages/cart/publishers/edit/[id].tsx index c4605f9..331e52a 100644 --- a/pages/cart/publishers/edit/[id].tsx +++ b/pages/cart/publishers/edit/[id].tsx @@ -49,7 +49,19 @@ export const getServerSideProps = async (context) => { } var url = process.env.NEXT_PUBLIC_PUBLIC_URL + "/api/data/publishers/" + context.query.id + "?include=availabilities,assignments,assignments.shift"; console.log("GET PUBLISHER FROM:" + url) - const { data: item } = await axios.get(url); + try { + const { data: item } = await axios.get(url); + } catch (error) { + console.log("error fetching publisher: " + error); + //redirect to message page with message "no account found". get user from session + const user = context.req.session.user; + return { + redirect: { + destination: '/message?message=Този имейл (' + user.email + ') не е регистриран. Моля свържете се с администратора.', + permanent: false, + }, + } + } // item.allShifts = item.assignments.map((a: Assignment[]) => a.shift);