updated and tested dashboard page

This commit is contained in:
2025-06-04 14:22:21 +03:00
parent 3a35752b46
commit 3f0b3c8ed2
30 changed files with 3577 additions and 44 deletions

View File

@@ -0,0 +1,19 @@
'use server';
import { AuthLayout } from "@/layouts/auth/layout";
import { AuthServerProps } from "@/validations/mutual/pages/props";
import { LanguageTypes } from "@/validations/mutual/language/validations";
import { checkAccessTokenIsValid } from "@/fetchers/mutual/cookies/token";
import { getOnlineFromRedis } from "@/fetchers/custom/context/page/online/fetch";
import { redirect } from "next/navigation";
import Login from "@/pages/single/auth/login/page";
const AuthPageSSR = async ({ params, searchParams }: AuthServerProps) => {
const awaitedParams = await params;
const awaitedSearchParams = await searchParams;
const pageUrlFromParams = `/${awaitedParams.page?.join("/")}` || "/login";
const tokenValid = await checkAccessTokenIsValid();
try { const online = await getOnlineFromRedis(); if (tokenValid && online) { redirect("/panel/dashboard") } } catch (error) { }
return <div className="flex flex-col items-center justify-center"><AuthLayout lang={"en"} page={<Login language={"en"} query={awaitedSearchParams} />} activePageUrl={pageUrlFromParams} /></div>
}
export default AuthPageSSR;

View File

@@ -0,0 +1,15 @@
'use server';
import { MaindasboardPageProps } from "@/validations/mutual/dashboard/props";
import { DashboardLayout } from "@/layouts/dashboard/layout";
import { redirect } from "next/navigation";
import { checkAccessTokenIsValid } from "@/fetchers/mutual/cookies/token";
const MainEnPage: React.FC<MaindasboardPageProps> = async ({ params, searchParams }) => {
const parameters = await params;
const searchParameters = await searchParams;
const tokenValid = await checkAccessTokenIsValid()
if (!tokenValid) { redirect("/auth/login") }
return <div className="flex flex-col items-center justify-center"><DashboardLayout params={parameters} searchParams={searchParameters} lang="en" /></div>
}
export default MainEnPage;

View File

@@ -1,6 +1,6 @@
import { NextResponse } from "next/server";
import { loginViaAccessKeys } from "@/apifetchers/custom/login/login";
import { loginSchemaEmail } from "@/webPages/auth/login/schemas";
import { loginViaAccessKeys } from "@/fetchers/custom/login/login";
import { loginSchemaEmail } from "@/pages/single/auth/login/schemas";
export async function POST(req: Request): Promise<NextResponse> {
try {

View File

@@ -1,7 +1,7 @@
import { DashboardLayout } from '@/layouts/dashboard/layout';
import { LanguageTypes } from '@/validations/mutual/language/validations';
export default function Page({ params, searchParams }: { params: { page?: string[] }, searchParams: Record<string, any> }) {
export default async function Page({ params, searchParams }: { params: { page?: string[] }, searchParams: Record<string, any> }) {
const lang: LanguageTypes = 'en';
return <DashboardLayout params={params} searchParams={searchParams} lang={lang} />;
return <DashboardLayout params={{ page: params.page || [] }} searchParams={searchParams} lang={lang} />
}

View File

@@ -1,6 +1,6 @@
import { ContentProps } from "@/validations/mutual/dashboard/props";
import ContentToRenderNoPage from "@/pages/mutual/noContent/page";
import pageIndexMulti from "@/pages/multi/index";
import { pageIndexMulti } from "@/pages/multi/index"
const PageToBeChildrendMulti: React.FC<ContentProps> = ({
activePageUrl,

View File

@@ -1,13 +0,0 @@
import { ContentProps } from "@/validations/mutual/dashboard/props";
import ContentToRenderNoPage from "@/pages/mutual/noContent/page";
import { resolveWhichPageToRenderSingle } from "@/pages/resolver/resolver";
const PageToBeChildrendSingle: React.FC<ContentProps> = async ({ lang, translations, activePageUrl, mode }) => {
const ApplicationToRender = await resolveWhichPageToRenderSingle({ activePageUrl })
if (ApplicationToRender) {
return <ApplicationToRender lang={lang} translations={translations} activePageUrl={activePageUrl} mode={mode} />
}
return <ContentToRenderNoPage lang={lang} />
}
export default PageToBeChildrendSingle

View File

@@ -23,7 +23,7 @@ const FooterComponent: FC<FooterProps> = ({
const lang = onlineData?.lang as LanguageTypes || 'en';
return (
<div className="fixed text-center bottom-0 left-0 right-0 h-16 p-4 border-t border-emerald-150 border-t-2 shadow-sm backdrop-blur-sm bg-emerald-50">
<div className="fixed text-center bottom-0 left-0 right-0 h-16 p-4 border-emerald-150 border-t-2 shadow-sm backdrop-blur-sm bg-emerald-50">
<div className="flex justify-between items-center">
<div className="text-sm text-gray-500">
{!configLoading && configData && (

View File

@@ -1,5 +1,5 @@
'use client';
import { FC } from "react";
import { FC, useState, useEffect } from "react";
import { HeaderProps } from "@/validations/mutual/dashboard/props";
import { langGetKey } from "@/lib/langGet";
import { LanguageTypes } from "@/validations/mutual/language/validations";
@@ -8,35 +8,208 @@ import LanguageSelectionComponent from "@/components/mutual/languageSelection/co
const translations = {
en: {
selectedPage: "selectedPage",
page: "page"
page: "page",
search: "Search...",
notifications: "Notifications",
messages: "Messages",
profile: "Profile",
settings: "Settings",
logout: "Log Out"
},
tr: {
selectedPage: "seçiliSayfa",
page: "sayfa"
page: "sayfa",
search: "Ara...",
notifications: "Bildirimler",
messages: "Mesajlar",
profile: "Profil",
settings: "Ayarlar",
logout: ıkış"
}
}
const HeaderComponent: FC<HeaderProps> = ({
activePageUrl, onlineData, onlineLoading, onlineError, refreshOnline, updateOnline,
activePageUrl, searchParams,
onlineData, onlineLoading, onlineError, refreshOnline, updateOnline,
userData, userLoading, userError, refreshUser, updateUser
}) => {
const lang = onlineData?.lang as LanguageTypes || 'en';
const [activeTab, setActiveTab] = useState('notifications');
const [isFullscreen, setIsFullscreen] = useState(false);
useEffect(() => {
const handleFullscreenChange = () => {
setIsFullscreen(!!document.fullscreenElement);
};
document.addEventListener('fullscreenchange', handleFullscreenChange);
return () => {
document.removeEventListener('fullscreenchange', handleFullscreenChange);
};
}, []);
const toggleFullscreen = () => {
if (document.fullscreenElement) {
document.exitFullscreen();
} else {
document.documentElement.requestFullscreen().catch(err => {
console.error(`Error attempting to enable fullscreen: ${err.message}`);
});
}
};
return (
<div className="flex justify-between h-24 items-center p-4 border-emerald-150 border-b-2 shadow-sm backdrop-blur-sm sticky top-0 z-50 bg-emerald-50">
<div className="flex flex-row justify-center items-center">
<p className="text-2xl font-bold mx-3">{langGetKey(translations[lang], 'selectedPage')} :</p>
<p className="text-lg font-bold mx-3"> {activePageUrl || langGetKey(translations[lang], 'page')}</p>
<div className="py-2 px-6 bg-[#f8f4f3] flex items-center shadow-md shadow-black/5 sticky top-0 left-0 z-30">
<button type="button" className="text-lg text-gray-900 font-semibold sidebar-toggle">
<i className="ri-menu-line"></i>
</button>
<div className="ml-4">
<p className="text-lg font-semibold">{activePageUrl || langGetKey(translations[lang], 'page')}</p>
</div>
<div className="flex items-center">
{!onlineLoading && onlineData && onlineData.userType && (
<div className="mr-4 text-sm">
<span className="font-semibold">{lang}</span>
<span className="ml-2 text-xs bg-green-100 text-green-800 px-2 py-1 rounded-full">{onlineData.userType}</span>
<ul className="ml-auto flex items-center">
<li className="mr-1 dropdown relative group">
<button type="button" className="dropdown-toggle text-gray-400 mr-4 w-8 h-8 rounded flex items-center justify-center hover:text-gray-600">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" className="hover:bg-gray-100 rounded-full" viewBox="0 0 24 24" style={{ fill: 'gray' }}>
<path d="M19.023 16.977a35.13 35.13 0 0 1-1.367-1.384c-.372-.378-.596-.653-.596-.653l-2.8-1.337A6.962 6.962 0 0 0 16 9c0-3.859-3.14-7-7-7S2 5.141 2 9s3.14 7 7 7c1.763 0 3.37-.66 4.603-1.739l1.337 2.8s.275.224.653.596c.387.363.896.854 1.384 1.367l1.358 1.392.604.646 2.121-2.121-.646-.604c-.379-.372-.885-.866-1.391-1.36zM9 14c-2.757 0-5-2.243-5-5s2.243-5 5-5 5 2.243 5 5-2.243 5-5 5z"></path>
</svg>
</button>
<div className="dropdown-menu shadow-md shadow-black/5 z-30 hidden group-hover:block absolute right-0 top-full max-w-xs w-60 bg-white rounded-md border border-gray-100">
<form action="" className="p-4 border-b border-b-gray-100">
<div className="relative w-full">
<input type="text" className="py-2 pr-4 pl-10 bg-gray-50 w-full outline-none border border-gray-100 rounded-md text-sm focus:border-blue-500" placeholder={langGetKey(translations[lang], 'search')} />
<i className="ri-search-line absolute top-1/2 left-4 -translate-y-1/2 text-gray-900"></i>
</div>
</form>
</div>
)}<LanguageSelectionComponent
activePage={activePageUrl} onlineData={onlineData} onlineLoading={onlineLoading} onlineError={onlineError} refreshOnline={refreshOnline} updateOnline={updateOnline}
/>
</div>
</li>
<li className="dropdown relative group">
<button type="button" className="dropdown-toggle text-gray-400 mr-4 w-8 h-8 rounded flex items-center justify-center hover:text-gray-600">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" className="hover:bg-gray-100 rounded-full" viewBox="0 0 24 24" style={{ fill: 'gray' }}>
<path d="M19 13.586V10c0-3.217-2.185-5.927-5.145-6.742C13.562 2.52 12.846 2 12 2s-1.562.52-1.855 1.258C7.185 4.074 5 6.783 5 10v3.586l-1.707 1.707A.996.996 0 0 0 3 16v2a1 1 0 0 0 1 1h16a1 1 0 0 0 1-1v-2a.996.996 0 0 0-.293-.707L19 13.586zM19 17H5v-.586l1.707-1.707A.996.996 0 0 0 7 14v-4c0-2.757 2.243-5 5-5s5 2.243 5 5v4c0 .266.105.52.293.707L19 16.414V17zm-7 5a2.98 2.98 0 0 0 2.818-2H9.182A2.98 2.98 0 0 0 12 22z"></path>
</svg>
</button>
<div className="dropdown-menu shadow-md shadow-black/5 z-30 hidden group-hover:block absolute right-0 top-full max-w-xs w-80 bg-white rounded-md border border-gray-100">
<div className="flex items-center px-4 pt-4 border-b border-b-gray-100 notification-tab">
<button
type="button"
onClick={() => setActiveTab('notifications')}
className={`text-gray-400 font-medium text-[13px] hover:text-gray-600 border-b-2 ${activeTab === 'notifications' ? 'border-b-blue-500 text-blue-500' : 'border-b-transparent'} mr-4 pb-1`}
>
{langGetKey(translations[lang], 'notifications')}
</button>
<button
type="button"
onClick={() => setActiveTab('messages')}
className={`text-gray-400 font-medium text-[13px] hover:text-gray-600 border-b-2 ${activeTab === 'messages' ? 'border-b-blue-500 text-blue-500' : 'border-b-transparent'} mr-4 pb-1`}
>
{langGetKey(translations[lang], 'messages')}
</button>
</div>
<div className="my-2">
<ul className={`max-h-64 overflow-y-auto ${activeTab === 'notifications' ? 'block' : 'hidden'}`}>
{/* Notification items would go here */}
<li>
<a href="#" className="py-2 px-4 flex items-center hover:bg-gray-50 group">
<div className="w-8 h-8 rounded bg-blue-100 flex items-center justify-center mr-2">
<i className="ri-notification-2-line text-blue-500"></i>
</div>
<div className="ml-2">
<div className="text-[13px] text-gray-600 font-medium truncate group-hover:text-blue-500">System Notification</div>
<div className="text-[11px] text-gray-400">Just now</div>
</div>
</a>
</li>
</ul>
<ul className={`max-h-64 overflow-y-auto ${activeTab === 'messages' ? 'block' : 'hidden'}`}>
{/* Message items would go here */}
<li>
<a href="#" className="py-2 px-4 flex items-center hover:bg-gray-50 group">
<div className="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center mr-2">
<i className="ri-user-line text-gray-500"></i>
</div>
<div className="ml-2">
<div className="text-[13px] text-gray-600 font-medium truncate group-hover:text-blue-500">Support Team</div>
<div className="text-[11px] text-gray-400">Hello there!</div>
</div>
</a>
</li>
</ul>
</div>
</div>
</li>
<button onClick={toggleFullscreen} className="text-gray-400 mr-4 w-8 h-8 rounded flex items-center justify-center hover:text-gray-600">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" className="hover:bg-gray-100 rounded-full" viewBox="0 0 24 24" style={{ fill: 'gray' }}>
<path d="M5 5h5V3H3v7h2zm5 14H5v-5H3v7h7zm11-5h-2v5h-5v2h7zm-2-4h2V3h-7v2h5z"></path>
</svg>
</button>
<li className="dropdown ml-3 relative group">
<button type="button" className="dropdown-toggle flex items-center">
<div className="flex-shrink-0 w-10 h-10 relative">
<div className="p-1 bg-white rounded-full focus:outline-none focus:ring">
{userData?.avatar ? (
<img className="w-8 h-8 rounded-full" src={userData.avatar} alt="User Avatar" />
) : (
<div className="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center">
<i className="ri-user-line text-gray-500"></i>
</div>
)}
{!onlineLoading && onlineData && onlineData.status === 'online' && (
<>
<div className="top-0 left-7 absolute w-3 h-3 bg-lime-400 border-2 border-white rounded-full animate-ping"></div>
<div className="top-0 left-7 absolute w-3 h-3 bg-lime-500 border-2 border-white rounded-full"></div>
</>
)}
</div>
</div>
<div className="p-2 md:block text-left">
<h2 className="text-sm font-semibold text-gray-800">{userData?.name || 'User'}</h2>
<p className="text-xs text-gray-500">{onlineData?.userType || 'Guest'}</p>
</div>
</button>
<ul className="dropdown-menu shadow-md shadow-black/5 z-30 hidden group-hover:block absolute right-0 top-full py-1.5 rounded-md bg-white border border-gray-100 w-full max-w-[140px]">
<li>
<a href="#" className="flex items-center text-[13px] py-1.5 px-4 text-gray-600 hover:text-[#f84525] hover:bg-gray-50">
{langGetKey(translations[lang], 'profile')}
</a>
</li>
<li>
<a href="#" className="flex items-center text-[13px] py-1.5 px-4 text-gray-600 hover:text-[#f84525] hover:bg-gray-50">
{langGetKey(translations[lang], 'settings')}
</a>
</li>
<li>
<form method="POST" action="">
<a
role="menuitem"
className="flex items-center text-[13px] py-1.5 px-4 text-gray-600 hover:text-[#f84525] hover:bg-gray-50 cursor-pointer"
onClick={(e) => {
e.preventDefault();
// Handle logout logic here
}}
>
{langGetKey(translations[lang], 'logout')}
</a>
</form>
</li>
</ul>
</li>
<div className="ml-3">
<LanguageSelectionComponent
activePage={activePageUrl}
onlineData={onlineData}
onlineLoading={onlineLoading}
onlineError={onlineError}
refreshOnline={refreshOnline}
updateOnline={updateOnline}
/>
</div>
</ul>
</div>
);
};

View File

@@ -1,11 +1,12 @@
import { ApiResponse, CookieObject } from "./types";
import { ResponseCookie } from "next/dist/compiled/@edge-runtime/cookies";
import { ApiResponse } from "./types";
import NextCrypto from "next-crypto";
const tokenSecretEnv = process.env.TOKENSECRET_90;
const tokenSecret = tokenSecretEnv || "e781d1b0-9418-40b3-9940-385abf81a0b7";
const REDIS_TIMEOUT = 5000; // Redis operation timeout (5 seconds)
const nextCrypto = new NextCrypto(tokenSecret);
const cookieObject: CookieObject = {
const cookieObject: Partial<ResponseCookie> = {
httpOnly: true,
path: "/",
sameSite: "none",

View File

@@ -0,0 +1,200 @@
"use server";
import NextCrypto from "next-crypto";
import { fetchData, fetchDataWithToken } from "@/fetchers/fecther";
import { cookieObject, tokenSecret } from "@/fetchers/base";
import { urlLoginEndpoint, urlLoginSelectEndpoint, urlLogoutEndpoint } from "@/fetchers/index";
import { cookies } from "next/headers";
import { setNewCompleteToRedis, getCompleteFromRedis } from "@/fetchers/custom/context/complete/fetch";
import {
defaultValuesHeader,
defaultValuesMenu,
defaultValuesOnline,
defaultValuesPageConfig,
} from "@/fetchers/types/context";
import { retrievePageList } from "@/fetchers/mutual/cookies/token";
import { deleteAllCookies } from "@/fetchers/mutual/cookies/cookie-actions";
import { setMenuToRedis } from "@/fetchers/custom/context/page/menu/fetch";
import { LoginViaAccessKeys, LoginSelect, LoginSelectOccupant } from "@/fetchers/types/login/validations";
async function logoutActiveSession() {
const response = await fetchDataWithToken(urlLogoutEndpoint, {}, "GET", false);
await deleteAllCookies();
return response;
}
async function initRedis(loginRespone: any, firstSelection: any, accessToken: string, redisKey: string) {
let alreadyAtRedis = null
try {
const redisData = await getCompleteFromRedis();
alreadyAtRedis = redisData;
} catch (error) { }
if (!alreadyAtRedis) {
const loginObjectToRedis = {
online: {
...defaultValuesOnline,
lastLogin: new Date(),
userType: `${loginRespone.user_type}`.toUpperCase(),
lang: loginRespone.user.person.country_code.toLowerCase(),
},
pageConfig: defaultValuesPageConfig,
menu: defaultValuesMenu,
header: defaultValuesHeader,
selection: { selectionList: loginRespone.selection_list, activeSelection: firstSelection },
user: loginRespone.user,
settings: { lastOnline: new Date(), token: accessToken },
chatRoom: [],
notifications: [],
messages: [],
}
await setNewCompleteToRedis(loginObjectToRedis, redisKey);
}
}
async function loginViaAccessKeys(payload: LoginViaAccessKeys) {
const cookieStore = await cookies();
try {
const response = await fetchData(
urlLoginEndpoint,
{
access_key: payload.accessKey,
password: payload.password,
remember_me: payload.rememberMe,
},
"POST",
false
);
await deleteAllCookies()
if (response.status === 200 || response.status === 202) {
const loginRespone: any = response?.data;
const firstSelection = loginRespone.selection_list.find((item: any) => item.uu_id === loginRespone.selection_list[0].uu_id);
const nextCrypto = new NextCrypto(tokenSecret);
const accessToken = await nextCrypto.encrypt(loginRespone.access_token);
const redisKey = `CLIENT:${loginRespone.user_type.toUpperCase()}:${firstSelection.uu_id}`;
const redisKeyAccess = await nextCrypto.encrypt(redisKey);
const usersSelection = await nextCrypto.encrypt(
JSON.stringify({
selected: firstSelection.uu_id,
userType: loginRespone.user_type.toUpperCase(),
redisKey,
})
);
await initRedis(loginRespone, firstSelection, accessToken, redisKey);
cookieStore.set({
name: "eys-zzz",
value: accessToken,
...cookieObject,
});
cookieStore.set({
name: "eys-yyy",
value: redisKeyAccess,
...cookieObject,
});
cookieStore.set({
name: "eys-sel",
value: usersSelection,
...cookieObject,
});
try {
return {
completed: true,
message: "Login successful",
status: 200,
data: loginRespone,
};
} catch (error) {
console.error("JSON parse error:", error);
return {
completed: false,
message: "Login NOT successful",
status: 401,
data: "{}",
};
}
}
return {
completed: false,
// error: response.error || "Login failed",
// message: response.message || "Authentication failed",
status: response.status || 500,
};
} catch (error) {
console.error("Login error:", error);
return {
completed: false,
// error: error instanceof Error ? error.message : "Login error",
// message: "An error occurred during login",
status: 500,
};
}
}
async function loginSelectEmployee(payload: LoginSelect) {
const cookieStore = await cookies();
const nextCrypto = new NextCrypto(tokenSecret);
const employeeUUID = payload.uuid;
const redisKey = `CLIENT:EMPLOYEE:${employeeUUID}`;
const selectResponse: any = await fetchDataWithToken(urlLoginSelectEndpoint, { uuid: employeeUUID }, "POST", false);
cookieStore.delete({ name: "eys-sel", ...cookieObject });
if (selectResponse.status === 200 || selectResponse.status === 202) {
const usersSelection = await nextCrypto.encrypt(
JSON.stringify({
selected: employeeUUID,
userType: "employee",
redisKey,
})
);
cookieStore.set({
name: "eys-sel",
value: usersSelection,
...cookieObject,
});
try {
const pageList = await retrievePageList()
await setMenuToRedis({
selectionList: pageList,
activeSelection: "/dashboard"
})
} catch (error) { }
}
return selectResponse;
}
async function loginSelectOccupant(payload: LoginSelectOccupant) {
const livingSpaceUUID = payload.uuid;
const cookieStore = await cookies();
const nextCrypto = new NextCrypto(tokenSecret);
const selectResponse: any = await fetchDataWithToken(urlLoginSelectEndpoint, { uuid: livingSpaceUUID }, "POST", false);
const redisKey = `CLIENT:OCCUPANT:${livingSpaceUUID}`;
cookieStore.delete("eys-sel");
if (selectResponse.status === 200 || selectResponse.status === 202) {
const usersSelection = await nextCrypto.encrypt(
JSON.stringify({
selected: livingSpaceUUID,
userType: "OCCUPANT",
redisKey,
})
);
cookieStore.set({
name: "eys-sel",
value: usersSelection,
...cookieObject,
});
}
return selectResponse;
}
export {
loginViaAccessKeys,
loginSelectEmployee,
loginSelectOccupant,
logoutActiveSession,
};

View File

@@ -25,12 +25,19 @@ const urlCheckToken = `${baseUrlAuth}/authentication/token/check`;
const urlPageValid = `${baseUrlRestriction}/restrictions/page/valid`;
const urlSiteUrls = `${baseUrlRestriction}/restrictions/sites/list`;
const urlLoginEndpoint = `${baseUrlAuth}/authentication/login`;
const urlLoginSelectEndpoint = `${baseUrlAuth}/authentication/select`;
const urlLogoutEndpoint = `${baseUrlAuth}/authentication/logout`;
const urlTesterList = `${baseUrlTester}/tester/list`;
export {
urlCheckToken,
urlPageValid,
urlSiteUrls,
urlLoginEndpoint,
urlLoginSelectEndpoint,
urlLogoutEndpoint,
// For test use only
urlTesterList,
};

View File

@@ -0,0 +1,15 @@
interface LoginViaAccessKeys {
accessKey: string;
password: string;
rememberMe: boolean;
}
interface LoginSelect {
uuid: string;
}
interface LoginSelectOccupant {
uuid: any;
}
export type { LoginViaAccessKeys, LoginSelect, LoginSelectOccupant };

View File

@@ -1,10 +1,10 @@
import { DashboardPage } from '@/components/custom/content/DashboardPage';
import { DashboardPage } from "@/components/custom/content/DashboardPage";
const pageIndexMulti: Record<string, Record<string, React.FC<any>>> = {
'/dashboard': {
'DashboardPage': DashboardPage
},
// Add more pages as needed
"/dashboard": {
DashboardPage: DashboardPage,
},
// Add more pages as needed
};
export default pageIndexMulti;
export { pageIndexMulti };

View File

@@ -0,0 +1,37 @@
import { LanguageTypes } from "@/validations/mutual/language/validations";
export function loginHook(
startTransition: any,
data: any,
setError: any,
setJsonText: any,
Router: any,
lang: LanguageTypes
) {
try {
const sendData = { ...data };
startTransition(() => {
fetch("/api/login/email", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(sendData),
})
.then((response) => {
if (response.status === 200) {
response.json().then((data) => {
setTimeout(() => {
Router.push(`/panel/dashboard`);
}, 100);
});
} else {
response.json().then((data) => {
setError(data?.message);
});
}
})
.catch(() => {});
});
} catch (error) {
setError("An error occurred during login");
}
}

View File

@@ -0,0 +1,22 @@
export const loginTranslation = {
tr: {
email: "E-Posta",
password: "Şifre",
rememberMe: "Beni Hatırla",
login: "Giriş Yap",
successMessage: "Giriş Yapıldı",
errorMessage: "Giriş Yapılmadı",
pendingMessage: "Giriş Yapılıyor...",
responseData: "Giriş Verileri",
},
en: {
email: "Email",
password: "Password",
rememberMe: "Remember Me",
login: "Login",
successMessage: "Login completed successfully",
errorMessage: "Login failed",
pendingMessage: "Logging in...",
responseData: "Response Data",
},
};

View File

@@ -0,0 +1,62 @@
"use client";
import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { LoginFormData } from "./types";
import { loginSchemaEmail } from "./schemas";
import { loginTranslation } from "./language";
import { loginHook } from "./hook";
import { AuthPageProps } from "@/validations/mutual/auth/props";
function Login({ language }: AuthPageProps) {
const Router = useRouter();
const translation = loginTranslation[language];
const [isPending, startTransition] = useTransition();
const [error, setError] = useState<string | null>(null);
const [jsonText, setJsonText] = useState<string | null>(null);
const { register, formState: { errors }, handleSubmit, } = useForm<LoginFormData>({ resolver: zodResolver(loginSchemaEmail) });
const onSubmit = async (data: LoginFormData) => { loginHook(startTransition, data, setError, setJsonText, Router, language) };
return (
<>
<div className="flex h-full min-h-[inherit] flex-col items-center justify-center gap-4">
<div className="w-full max-w-md rounded-lg bg-white p-8 shadow-md">
<h2 className="mb-6 text-center text-2xl font-bold text-gray-900">{translation.login}</h2>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
<div>
<label htmlFor="email" className="block text-sm font-medium text-gray-700">{translation.email}</label>
<input {...register("email")} type="email" id="email" className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-indigo-500" />
{errors.email && (<p className="mt-1 text-sm text-red-600">{errors.email.message}</p>)}
</div>
<div>
<label htmlFor="password" className="block text-sm font-medium text-gray-700">{translation.password}</label>
<input {...register("password")} type="password" id="password" className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-indigo-500" />
{errors.password && (<p className="mt-1 text-sm text-red-600">{errors.password.message}</p>)}
</div>
{error && (<div className="rounded-md bg-red-50 p-4"><p className="text-sm text-red-700">{error}</p></div>)}
<button type="submit" disabled={isPending} className="w-full rounded-md bg-indigo-600 px-4 py-2 text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 disabled:opacity-50">
{isPending ? translation.pendingMessage : translation.login}</button>
</form>
</div>
{jsonText && (
<div className="w-full max-w-md rounded-lg bg-white p-8 shadow-md">
<h2 className="mb-4 text-center text-xl font-bold text-gray-900">{translation.responseData}</h2>
<div className="space-y-2">
{Object.entries(JSON.parse(jsonText)).map(([key, value]) => (
<div key={key} className="flex items-start gap-2">
<strong className="text-gray-700">{key}:</strong>
<span className="text-gray-600">{typeof value === "object" ? JSON.stringify(value) : value?.toString() || "N/A"}</span>
</div>
))}
</div>
</div>
)}
</div>
</>
);
}
export default Login;

View File

@@ -0,0 +1,15 @@
import { z } from "zod";
const loginSchemaEmail = z.object({
email: z.string().email("Invalid email address"),
password: z.string().min(5, "Password must be at least 5 characters"),
rememberMe: z.boolean().optional().default(false),
});
const loginSchemaPhone = z.object({
phone: z.string().regex(/^[0-9]{10}$/, "Invalid phone number"),
password: z.string().min(5, "Password must be at least 5 characters"),
rememberMe: z.boolean().optional().default(false),
});
export { loginSchemaEmail, loginSchemaPhone };

View File

@@ -0,0 +1,13 @@
type LoginFormData = {
email: string;
password: string;
rememberMe?: boolean;
};
type LoginFormDataPhone = {
phone: string;
password: string;
rememberMe?: boolean;
};
export type { LoginFormData, LoginFormDataPhone };

View File

@@ -0,0 +1,13 @@
import { LanguageTypes } from "../language/validations";
// <AuthLayout params={params} searchParams={searchParams} lang={lang} page={page} />
interface AuthLayoutProps {
page: React.ReactNode;
lang: LanguageTypes;
activePageUrl: string;
}
interface AuthPageProps {
query?: { [key: string]: string | string[] | undefined };
language: LanguageTypes;
}
export type { AuthLayoutProps, AuthPageProps };

View File

@@ -0,0 +1,7 @@
type ParamsType = { page: string[] | undefined };
interface AuthServerProps {
params: Promise<{ page: string[] | undefined }>;
searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}
export type { ParamsType, AuthServerProps };