🔒 (security) security improvement

This commit is contained in:
2025-10-10 23:57:09 +07:00
parent 54f4e72b32
commit 15c9599ce7
54 changed files with 1603 additions and 1567 deletions

View File

@ -1,13 +1,13 @@
"use server";
import { api } from "@/shared/lib/ky/connector";
const getOauthProviderList = async () => {
try {
const res = await api.get(`auth/providers`);
return res.json();
} catch (error) {
throw new Error("Failed to fetch OAuth providers", { cause: error });
}
};
export default getOauthProviderList;
"use server";
import { api } from "@/shared/lib/ky/connector";
const getOauthProviderList = async () => {
try {
const res = await api.get(`auth/providers`);
return res.json();
} catch (error) {
throw new Error("Failed to fetch OAuth providers", { cause: error });
}
};
export default getOauthProviderList;

View File

@ -1,36 +1,36 @@
"use server";
import { api } from "@/shared/lib/ky/connector";
import { redirect } from "next/navigation";
import { ResponseRequestOauthUrl } from "../types/responseRequestOauthUrl";
const requestOauthUrl = async (providerData: {
name: string;
endpoint: string;
}) => {
// Check if requestEndpoint is provided, if not throw an error
if (!providerData.endpoint)
throw new Error("oAuth endpoint request not found");
// Define a variable to hold the OAuth data
let oauthData: Promise<ResponseRequestOauthUrl>;
// Fetch OAuth data from the API
try {
const response = await api.get(providerData.endpoint, {
searchParams: {
callback: `${
process.env.APP_DOMAIN
}/auth/callback/${providerData.name.toLocaleLowerCase()}`,
},
});
oauthData = response.json<ResponseRequestOauthUrl>();
} catch (error) {
throw new Error(JSON.stringify(error));
}
// Redirect to the OAuth provider's authorization page
redirect((await oauthData).data);
};
export default requestOauthUrl;
"use server";
import { api } from "@/shared/lib/ky/connector";
import { redirect } from "next/navigation";
import { ResponseRequestOauthUrl } from "../types/responseRequestOauthUrl";
const requestOauthUrl = async (providerData: {
name: string;
endpoint: string;
}) => {
// Check if requestEndpoint is provided, if not throw an error
if (!providerData.endpoint)
throw new Error("oAuth endpoint request not found");
// Define a variable to hold the OAuth data
let oauthData: Promise<ResponseRequestOauthUrl>;
// Fetch OAuth data from the API
try {
const response = await api.get(providerData.endpoint, {
searchParams: {
callback: `${
process.env.APP_DOMAIN
}/auth/callback/${providerData.name.toLocaleLowerCase()}`,
},
});
oauthData = response.json<ResponseRequestOauthUrl>();
} catch (error) {
throw new Error(JSON.stringify(error));
}
// Redirect to the OAuth provider's authorization page
redirect((await oauthData).data);
};
export default requestOauthUrl;

View File

@ -1,27 +1,27 @@
"use server";
import { apiErrorHandler } from "@/shared/lib/ky/errorHandler";
import { RegisterInputs } from "../ui/components/ProvisionInput";
import { ServerRequestCallback } from "@/shared/types/ServerRequestCallback";
export const submitRegisterForm = async (
data: RegisterInputs
): Promise<ServerRequestCallback> => {
if (data.password !== data.confirmPassword)
return apiErrorHandler([], {
success: false,
status: 400,
text: { message: "Password and Confirm Password do not match" },
});
try {
await new Promise((resolve) => setTimeout(resolve, 3000));
return {
success: true,
status: 200,
text: { message: "Registration successful" },
};
} catch (error) {
return apiErrorHandler(error);
}
};
"use server";
import { apiErrorHandler } from "@/shared/lib/ky/errorHandler";
import { RegisterInputs } from "../ui/components/ProvisionInput";
import { ServerRequestCallback } from "@/shared/types/ServerRequestCallback";
export const submitRegisterForm = async (
data: RegisterInputs
): Promise<ServerRequestCallback> => {
if (data.password !== data.confirmPassword)
return apiErrorHandler([], {
success: false,
status: 400,
text: { message: "Password and Confirm Password do not match" },
});
try {
await new Promise((resolve) => setTimeout(resolve, 3000));
return {
success: true,
status: 200,
text: { message: "Registration successful" },
};
} catch (error) {
return apiErrorHandler(error);
}
};

View File

@ -0,0 +1,21 @@
import { z } from "zod";
export const registerFormSchema = z
.object({
fullname: z.string().min(1, "Full name is required"),
email: z.email("Invalid email address"),
password: z
.string()
.min(8, "Password must be at least 8 characters long")
.max(25, "Password must be at most 25 characters long"),
confirmPassword: z
.string()
.min(8, "Password must be at least 8 characters long")
.max(25, "Password must be at most 25 characters long"),
})
.refine((data) => data.password === data.confirmPassword, {
message: "Passwords confirmation does not match",
path: ["confirmPassword"],
});
export type RegisterFormSchema = z.infer<typeof registerFormSchema>;

View File

@ -1,53 +1,53 @@
"use client";
import { redirect } from "next/navigation";
import React, { useEffect, useState } from "react";
import Login from "@/features/auth/ui/cards/Login";
import SecurityCheckup from "@/shared/auth/ui/SecurityCheckup";
import SecurityCheckupFailed from "@/shared/auth/ui/SecurityCheckupFailed";
const LoginPage = () => {
/**
* Create a lit component that will be used in popp, consisting of 3 component flows:
* 1. When the user opens it, a browser environment check will be performed.
* 2. If it passes, the login component will appear and the user will perform authentication.
* 3. If it fails, stop the authentication process and display the warning component, then return the user to the homepage.
*/
const componentFlowList = {
securityCheckup: <SecurityCheckup />,
securityCheckupFailed: <SecurityCheckupFailed />,
SecurityCheckupSuccessed: <Login />,
};
// State to set the current page component
const [componentFlow, setComponentFlow] = useState(
componentFlowList.securityCheckup
);
useEffect(() => {
/**
* Check if the window has an opener (i.e., it was opened by another window)
* If it does, the security checkup has passed.
* If it doesn't, the security checkup has failed and user will be redirected to the homepage.
*/
if (window.opener) {
setComponentFlow(componentFlowList.SecurityCheckupSuccessed);
} else {
setComponentFlow(componentFlowList.securityCheckupFailed);
const timer = setTimeout(() => {
redirect("/");
}, 5000);
return () => clearTimeout(timer);
}
}, []);
return (
<>
{/* show the current component flow */}
<main>{componentFlow}</main>
</>
);
};
export default LoginPage;
"use client";
import { redirect } from "next/navigation";
import React, { useEffect, useState } from "react";
import Login from "@/features/auth/ui/cards/Login";
import SecurityCheckup from "@/shared/auth/ui/SecurityCheckup";
import SecurityCheckupFailed from "@/shared/auth/ui/SecurityCheckupFailed";
const LoginPage = () => {
/**
* Create a lit component that will be used in popp, consisting of 3 component flows:
* 1. When the user opens it, a browser environment check will be performed.
* 2. If it passes, the login component will appear and the user will perform authentication.
* 3. If it fails, stop the authentication process and display the warning component, then return the user to the homepage.
*/
const componentFlowList = {
securityCheckup: <SecurityCheckup />,
securityCheckupFailed: <SecurityCheckupFailed />,
SecurityCheckupSuccessed: <Login />,
};
// State to set the current page component
const [componentFlow, setComponentFlow] = useState(
componentFlowList.securityCheckup
);
useEffect(() => {
/**
* Check if the window has an opener (i.e., it was opened by another window)
* If it does, the security checkup has passed.
* If it doesn't, the security checkup has failed and user will be redirected to the homepage.
*/
if (window.opener) {
setComponentFlow(componentFlowList.SecurityCheckupSuccessed);
} else {
setComponentFlow(componentFlowList.securityCheckupFailed);
const timer = setTimeout(() => {
redirect("/");
}, 5000);
return () => clearTimeout(timer);
}
}, []);
return (
<>
{/* show the current component flow */}
<main>{componentFlow}</main>
</>
);
};
export default LoginPage;

View File

@ -1,51 +1,51 @@
"use client";
import { redirect } from "next/navigation";
import React, { JSX, useEffect, useState } from "react";
import SecurityCheckup from "@/shared/auth/ui/SecurityCheckup";
import SecurityCheckupFailed from "@/shared/auth/ui/SecurityCheckupFailed";
import Signup from "../ui/cards/Signup";
const SignupPage = () => {
// State to set the current page component
const [componentFlow, setComponentFlow] = useState<JSX.Element>(
<SecurityCheckup />
);
/**
* Create a lit component that will be used in popp, consisting of 3 component flows:
* 1. If it passes, the login component will appear and the user will perform authentication.
* 2. If it fails, stop the authentication process and display the warning component, then return the user to the homepage.
*/
const componentFlowList = {
securityCheckupFailed: <SecurityCheckupFailed />,
SecurityCheckupSuccessed: <Signup changeCurrentPage={setComponentFlow} />,
};
useEffect(() => {
/**
* Check if the window has an opener (i.e., it was opened by another window)
* If it does, the security checkup has passed.
* If it doesn't, the security checkup has failed and user will be redirected to the homepage.
*/
if (window.opener) {
setComponentFlow(componentFlowList.SecurityCheckupSuccessed);
} else {
setComponentFlow(componentFlowList.securityCheckupFailed);
const timer = setTimeout(() => {
redirect("/");
}, 5000);
return () => clearTimeout(timer);
}
}, []);
return (
<>
{/* show the current component flow */}
<main>{componentFlow}</main>
</>
);
};
export default SignupPage;
"use client";
import { redirect } from "next/navigation";
import React, { JSX, useEffect, useState } from "react";
import SecurityCheckup from "@/shared/auth/ui/SecurityCheckup";
import SecurityCheckupFailed from "@/shared/auth/ui/SecurityCheckupFailed";
import Signup from "../ui/cards/Signup";
const SignupPage = () => {
// State to set the current page component
const [componentFlow, setComponentFlow] = useState<JSX.Element>(
<SecurityCheckup />
);
/**
* Create a lit component that will be used in popp, consisting of 3 component flows:
* 1. If it passes, the login component will appear and the user will perform authentication.
* 2. If it fails, stop the authentication process and display the warning component, then return the user to the homepage.
*/
const componentFlowList = {
securityCheckupFailed: <SecurityCheckupFailed />,
SecurityCheckupSuccessed: <Signup changeCurrentPage={setComponentFlow} />,
};
useEffect(() => {
/**
* Check if the window has an opener (i.e., it was opened by another window)
* If it does, the security checkup has passed.
* If it doesn't, the security checkup has failed and user will be redirected to the homepage.
*/
if (window.opener) {
setComponentFlow(componentFlowList.SecurityCheckupSuccessed);
} else {
setComponentFlow(componentFlowList.securityCheckupFailed);
const timer = setTimeout(() => {
redirect("/");
}, 5000);
return () => clearTimeout(timer);
}
}, []);
return (
<>
{/* show the current component flow */}
<main>{componentFlow}</main>
</>
);
};
export default SignupPage;

View File

@ -1,8 +1,8 @@
export interface OauthProviders {
name: string;
icon: string;
req_endpoint: string;
client_id: string | undefined;
client_secret: string | undefined;
client_callback: string;
}
export interface OauthProviders {
name: string;
icon: string;
req_endpoint: string;
client_id: string | undefined;
client_secret: string | undefined;
client_callback: string;
}

View File

@ -1,5 +1,5 @@
export interface ResponseRequestOauthUrl {
data: string;
message: string;
status: string;
}
export interface ResponseRequestOauthUrl {
data: string;
message: string;
status: string;
}

View File

@ -1,42 +1,42 @@
"use client";
import React from "react";
import { Divider, Link } from "@heroui/react";
import { routes } from "@/shared/config/routes";
import EmailInput from "../components/EmailInput";
import OAuthProviders from "../components/OAuthProviders";
const Login = () => {
return (
<div className="pt-12 max-w-[480px] mx-auto">
<div className="text-3xl text-center">Welcome back</div>
{/* Email form */}
<div className="mt-6 px-3">
<EmailInput />
</div>
{/* Sign up link */}
<p className="text-center text-neutral-300 text-sm font-light mt-5">
Don't have an account?{" "}
<Link className="text-sm font-medium" href={routes.signup}>
Sign Up
</Link>
</p>
{/* Divider between email form and third-party login options */}
<div className="flex w-full items-center mt-6 px-10">
<Divider className="flex-1" />
<span className="px-2 text-neutral-500 text-sm">or</span>
<Divider className="flex-1" />
</div>
{/* Buttons for third-party login options */}
<div className="mt-6 px-4">
<OAuthProviders />
</div>
</div>
);
};
export default Login;
"use client";
import React from "react";
import { Divider, Link } from "@heroui/react";
import { routes } from "@/shared/config/routes";
import EmailInput from "../components/EmailInput";
import OAuthProviders from "../components/OAuthProviders";
const Login = () => {
return (
<div className="pt-12 max-w-[480px] mx-auto">
<div className="text-3xl text-center">Welcome back</div>
{/* Email form */}
<div className="mt-6 px-3">
<EmailInput />
</div>
{/* Sign up link */}
<p className="text-center text-neutral-300 text-sm font-light mt-5">
Don't have an account?{" "}
<Link className="text-sm font-medium" href={routes.signup}>
Sign Up
</Link>
</p>
{/* Divider between email form and third-party login options */}
<div className="flex w-full items-center mt-6 px-10">
<Divider className="flex-1" />
<span className="px-2 text-neutral-500 text-sm">or</span>
<Divider className="flex-1" />
</div>
{/* Buttons for third-party login options */}
<div className="mt-6 px-4">
<OAuthProviders />
</div>
</div>
);
};
export default Login;

View File

@ -1,22 +1,22 @@
"use client";
import React from "react";
import ProvisionInput from "../components/ProvisionInput";
type Props = {
fullName: string;
};
const Provision = ({ fullName }: Props) => {
return (
<div className="pt-12 max-w-[480px] mx-auto">
<div className="text-3xl text-center">Hey, {fullName.split(" ")[0]}</div>
<p className="text-sm text-center font-light text-neutral-300 mt-2">
Just a few more steps to join the fun!
</p>
<ProvisionInput fullname={fullName} />
</div>
);
};
export default Provision;
"use client";
import React from "react";
import ProvisionInput from "../components/ProvisionInput";
type Props = {
fullName: string;
};
const Provision = ({ fullName }: Props) => {
return (
<div className="pt-12 max-w-[480px] mx-auto">
<div className="text-3xl text-center">Hey, {fullName.split(" ")[0]}</div>
<p className="text-sm text-center font-light text-neutral-300 mt-2">
Just a few more steps to join the fun!
</p>
<ProvisionInput fullname={fullName} />
</div>
);
};
export default Provision;

View File

@ -1,46 +1,46 @@
"use client";
import React from "react";
import { Divider, Link } from "@heroui/react";
import { routes } from "@/shared/config/routes";
import OAuthProviders from "../components/OAuthProviders";
import FullNameInput from "../components/FullNameInput";
type Props = {
changeCurrentPage: React.Dispatch<React.SetStateAction<React.JSX.Element>>;
};
const Signup = ({ changeCurrentPage }: Props) => {
return (
<div className="pt-12 max-w-[480px] mx-auto">
<div className="text-3xl text-center">Create an account</div>
{/* Email form */}
<div className="mt-6 px-3">
<FullNameInput changeCurrentPage={changeCurrentPage} />
</div>
{/* Sign up link */}
<p className="text-center text-neutral-300 text-sm font-light mt-5">
Already have an account?{" "}
<Link className="text-sm font-medium" href={routes.login}>
Log in
</Link>
</p>
{/* Divider between email form and third-party login options */}
<div className="flex w-full items-center mt-6 px-10">
<Divider className="flex-1" />
<span className="px-2 text-neutral-500 text-sm">or</span>
<Divider className="flex-1" />
</div>
{/* Buttons for third-party login options */}
<div className="mt-6 px-4">
<OAuthProviders />
</div>
</div>
);
};
export default Signup;
"use client";
import React from "react";
import { Divider, Link } from "@heroui/react";
import { routes } from "@/shared/config/routes";
import OAuthProviders from "../components/OAuthProviders";
import FullNameInput from "../components/FullNameInput";
type Props = {
changeCurrentPage: React.Dispatch<React.SetStateAction<React.JSX.Element>>;
};
const Signup = ({ changeCurrentPage }: Props) => {
return (
<div className="pt-12 max-w-[480px] mx-auto">
<div className="text-3xl text-center">Create an account</div>
{/* Email form */}
<div className="mt-6 px-3">
<FullNameInput changeCurrentPage={changeCurrentPage} />
</div>
{/* Sign up link */}
<p className="text-center text-neutral-300 text-sm font-light mt-5">
Already have an account?{" "}
<Link className="text-sm font-medium" href={routes.login}>
Log in
</Link>
</p>
{/* Divider between email form and third-party login options */}
<div className="flex w-full items-center mt-6 px-10">
<Divider className="flex-1" />
<span className="px-2 text-neutral-500 text-sm">or</span>
<Divider className="flex-1" />
</div>
{/* Buttons for third-party login options */}
<div className="mt-6 px-4">
<OAuthProviders />
</div>
</div>
);
};
export default Signup;

View File

@ -1,26 +1,26 @@
"use client";
import { Button, Input } from "@heroui/react";
import React from "react";
const EmailInput = () => {
return (
<>
<Input
className="w-full "
label="Email"
type="email"
variant="bordered"
classNames={{
input: "text-md font-light pt-4",
inputWrapper: "flex gap-10",
}}
/>
<Button className="mt-2 w-full" color="primary">
Continue
</Button>
</>
);
};
export default EmailInput;
"use client";
import { Button, Input } from "@heroui/react";
import React from "react";
const EmailInput = () => {
return (
<>
<Input
className="w-full "
label="Email"
type="email"
variant="bordered"
classNames={{
input: "text-md font-light pt-4",
inputWrapper: "flex gap-10",
}}
/>
<Button className="mt-2 w-full" color="primary">
Continue
</Button>
</>
);
};
export default EmailInput;

View File

@ -1,38 +1,38 @@
"use client";
import React, { useState } from "react";
import { Button, Input } from "@heroui/react";
import Provision from "../cards/Provision";
type Props = {
changeCurrentPage: React.Dispatch<React.SetStateAction<React.JSX.Element>>;
};
const FullNameInput = ({ changeCurrentPage }: Props) => {
const [fullName, setFullName] = useState("");
return (
<>
<Input
className="w-full "
label="Full Name"
type="name"
variant="bordered"
onChange={(e) => setFullName(e.target.value)}
classNames={{
input: "text-md font-light pt-4",
inputWrapper: "flex gap-10",
}}
/>
<Button
onPress={() => changeCurrentPage(<Provision fullName={fullName} />)}
className="mt-2 w-full"
color="primary"
>
Continue
</Button>
</>
);
};
export default FullNameInput;
"use client";
import React, { useState } from "react";
import { Button, Input } from "@heroui/react";
import Provision from "../cards/Provision";
type Props = {
changeCurrentPage: React.Dispatch<React.SetStateAction<React.JSX.Element>>;
};
const FullNameInput = ({ changeCurrentPage }: Props) => {
const [fullName, setFullName] = useState("");
return (
<>
<Input
className="w-full "
label="Full Name"
type="name"
variant="bordered"
onChange={(e) => setFullName(e.target.value)}
classNames={{
input: "text-md font-light pt-4",
inputWrapper: "flex gap-10",
}}
/>
<Button
onPress={() => changeCurrentPage(<Provision fullName={fullName} />)}
className="mt-2 w-full"
color="primary"
>
Continue
</Button>
</>
);
};
export default FullNameInput;

View File

@ -1,85 +1,85 @@
"use client";
import React, { useEffect, useState } from "react";
import { OauthProviders } from "../../types/oauthProvidersList";
import { ResponseRequestOauthUrl } from "../../types/responseRequestOauthUrl";
import { Button } from "@heroui/react";
import { Icon } from "@iconify/react";
import getOauthProviderList from "../../lib/getOauthProviderList";
import requestOauthUrl from "../../lib/requestOauthUrl";
const OAuthProviders = () => {
// Set initial state for OAuth providers list
const [oauthProvidersList, setOauthProvidersList] = useState<
OauthProviders[]
>([]);
/**
* Fetch the list of OAuth providers from backend API
* and update the state if OAuth providers list is available
*/
useEffect(() => {
(async () => {
try {
const res = (await getOauthProviderList()) as OauthProviders[];
setOauthProvidersList(res);
} catch (err) {
console.error(err);
}
})();
}, []);
const [loadingButton, setLoadingButton] = useState(false);
/**
* Start the authentication process using oAuth by sending the endpoint URL to the backend for processing.
*
* @param providerRequestEndpoint The request endpoint for the OAuth provider
*/
const startOauthProcess = async (providerData: {
name: string;
endpoint: string;
}) => {
try {
setLoadingButton(true);
(await requestOauthUrl(providerData)) as ResponseRequestOauthUrl;
} catch (err) {
setLoadingButton(false);
console.error(err);
}
};
return (
<div className="w-full flex flex-col gap-2 mt-4">
{/* Render OAuth provider buttons */}
{oauthProvidersList.length > 0 ? (
oauthProvidersList.map((provider, index) => {
return (
<Button
key={index}
className="w-full hover:bg-neutral-800"
variant="bordered"
startContent={<Icon className="w-4 h-4" icon={provider.icon} />}
onPress={() =>
startOauthProcess({
name: provider.name,
endpoint: provider.req_endpoint,
})
}
isLoading={loadingButton}
>
Continue with {provider.name}
</Button>
);
})
) : (
<Button className="w-full" variant="ghost" isDisabled>
No login options available via third-party providers
</Button>
)}
</div>
);
};
export default OAuthProviders;
"use client";
import React, { useEffect, useState } from "react";
import { OauthProviders } from "../../types/oauthProvidersList";
import { ResponseRequestOauthUrl } from "../../types/responseRequestOauthUrl";
import { Button } from "@heroui/react";
import { Icon } from "@iconify/react";
import getOauthProviderList from "../../lib/getOauthProviderList";
import requestOauthUrl from "../../lib/requestOauthUrl";
const OAuthProviders = () => {
// Set initial state for OAuth providers list
const [oauthProvidersList, setOauthProvidersList] = useState<
OauthProviders[]
>([]);
/**
* Fetch the list of OAuth providers from backend API
* and update the state if OAuth providers list is available
*/
useEffect(() => {
(async () => {
try {
const res = (await getOauthProviderList()) as OauthProviders[];
setOauthProvidersList(res);
} catch (err) {
console.error(err);
}
})();
}, []);
const [loadingButton, setLoadingButton] = useState(false);
/**
* Start the authentication process using oAuth by sending the endpoint URL to the backend for processing.
*
* @param providerRequestEndpoint The request endpoint for the OAuth provider
*/
const startOauthProcess = async (providerData: {
name: string;
endpoint: string;
}) => {
try {
setLoadingButton(true);
(await requestOauthUrl(providerData)) as ResponseRequestOauthUrl;
} catch (err) {
setLoadingButton(false);
console.error(err);
}
};
return (
<div className="w-full flex flex-col gap-2 mt-4">
{/* Render OAuth provider buttons */}
{oauthProvidersList.length > 0 ? (
oauthProvidersList.map((provider, index) => {
return (
<Button
key={index}
className="w-full hover:bg-neutral-800"
variant="bordered"
startContent={<Icon className="w-4 h-4" icon={provider.icon} />}
onPress={() =>
startOauthProcess({
name: provider.name,
endpoint: provider.req_endpoint,
})
}
isLoading={loadingButton}
>
Continue with {provider.name}
</Button>
);
})
) : (
<Button className="w-full" variant="ghost" isDisabled>
No login options available via third-party providers
</Button>
)}
</div>
);
};
export default OAuthProviders;

View File

@ -1,103 +1,118 @@
"use client";
import React, { useState } from "react";
import { addToast, Button, Form, Input } from "@heroui/react";
import { SubmitHandler, useForm } from "react-hook-form";
import { submitRegisterForm } from "../../lib/submitRegisterForm";
type Props = {
fullname: string;
};
export type RegisterInputs = {
fullname: string;
email: string;
password: string;
confirmPassword: string;
};
const ProvisionInput = ({ fullname }: Props) => {
const { register, handleSubmit, setValue } = useForm<RegisterInputs>();
setValue("fullname", fullname);
const [submitStatus, setSubmitStatus] = useState(false);
const onSubmit: SubmitHandler<RegisterInputs> = async (data) => {
setSubmitStatus(true);
try {
const returnData = await submitRegisterForm(data);
if (!returnData.success) {
setSubmitStatus(false);
addToast({
color: "danger",
title: "😬 Oops, something went wrong!",
description: returnData.text.message,
});
} else {
setSubmitStatus(false);
addToast({
color: "success",
title: "OKKE!",
description: returnData.text.message,
});
}
} catch (error) {
setSubmitStatus(false);
addToast({
color: "danger",
title: "😬 Oops, something went wrong!",
description: "Internal server error",
});
}
};
return (
<div className="mt-6 px-3">
<Form className="flex flex-col gap-1.5" onSubmit={handleSubmit(onSubmit)}>
<Input
{...register("email")}
className="w-full "
label="Email"
type="email"
variant="bordered"
classNames={{
input: "text-md font-light pt-4",
inputWrapper: "flex gap-10",
}}
/>
<Input
{...register("password")}
className="w-full "
label="Password"
type="password"
variant="bordered"
classNames={{
input: "text-md font-light pt-4",
inputWrapper: "flex gap-10",
}}
/>
<Input
{...register("confirmPassword")}
className="w-full "
label="Confirm Password"
type="password"
variant="bordered"
classNames={{
input: "text-md font-light pt-4",
inputWrapper: "flex gap-10",
}}
/>
<Button
type="submit"
className="mt-1.5 w-full"
color="primary"
isLoading={submitStatus}
>
Continue
</Button>
</Form>
</div>
);
};
export default ProvisionInput;
"use client";
import React, { useState } from "react";
import { addToast, Button, Form, Input } from "@heroui/react";
import { SubmitHandler, useForm } from "react-hook-form";
import { submitRegisterForm } from "../../lib/submitRegisterForm";
import { zodResolver } from "@hookform/resolvers/zod";
import { registerFormSchema } from "../../models/registerForm.schema";
type Props = {
fullname: string;
};
export type RegisterInputs = {
fullname: string;
email: string;
password: string;
confirmPassword: string;
};
const ProvisionInput = ({ fullname }: Props) => {
const {
register,
handleSubmit,
setValue,
formState: { errors },
} = useForm<RegisterInputs>({
resolver: zodResolver(registerFormSchema),
});
setValue("fullname", fullname);
const [submitStatus, setSubmitStatus] = useState(false);
const onSubmit: SubmitHandler<RegisterInputs> = async (data) => {
setSubmitStatus(true);
try {
const returnData = await submitRegisterForm(data);
if (!returnData.success) {
setSubmitStatus(false);
addToast({
color: "danger",
title: "😬 Oops, something went wrong!",
description: returnData.text.message,
});
} else {
setSubmitStatus(false);
addToast({
color: "success",
title: "OKKE!",
description: returnData.text.message,
});
}
} catch (error) {
setSubmitStatus(false);
addToast({
color: "danger",
title: "😬 Oops, something went wrong!",
description: "Connection to server lost",
});
}
};
return (
<div className="mt-6 px-3">
<Form className="flex flex-col gap-1.5" onSubmit={handleSubmit(onSubmit)}>
<Input
{...register("email")}
className="w-full "
label="Email"
type="email"
variant="bordered"
isInvalid={errors.email ? true : false}
errorMessage={errors.email?.message}
classNames={{
input: "text-md font-light pt-4",
inputWrapper: "flex gap-10",
}}
/>
<Input
{...register("password")}
className="w-full "
label="Password"
type="password"
variant="bordered"
isInvalid={errors.password ? true : false}
errorMessage={errors.password?.message}
classNames={{
input: "text-md font-light pt-4",
inputWrapper: "flex gap-10",
}}
/>
<Input
{...register("confirmPassword")}
className="w-full "
label="Confirm Password"
type="password"
variant="bordered"
isInvalid={errors.confirmPassword ? true : false}
errorMessage={errors.confirmPassword?.message}
classNames={{
input: "text-md font-light pt-4",
inputWrapper: "flex gap-10",
}}
/>
<Button
type="submit"
className="mt-1.5 w-full"
color="primary"
isLoading={submitStatus}
>
Continue
</Button>
</Form>
</div>
);
};
export default ProvisionInput;

View File

@ -1,83 +1,83 @@
"use server";
import { api } from "@/shared/lib/ky/connector";
import { apiErrorHandler } from "@/shared/lib/ky/errorHandler";
import { ServerRequestCallback } from "@/shared/types/serverRequestCallback";
/**
* @function SendCallbackToServer
* @description Proxies OAuth callback requests from the frontend to the main backend system.
* Acts as an intermediary between the client Next.js application and the Elysia server.
* Handles the forwarding of OAuth provider callback data for authentication processing.
*
* @param {string} data - The OAuth callback data received from the provider, typically containing
* query parameters such as authorization code, user consent, scopes, state,
* and other OAuth-specific information. Usually obtained from
* `window.location.search` in browser environments.
* @param {string} provider - The name of the OAuth provider/service (e.g., "google", "github",
* "facebook"). Used to construct the appropriate backend API endpoint.
*
* @returns {Promise<Object>} The response data from the backend server after processing the
* OAuth callback. Typically contains authentication tokens, user
* information, or session data.
*
* @throws {Error} If the network request fails or the backend returns an error response.
* @throws {Error} If the required environment variable APP_DOMAIN is not defined.
* @throws {Error} If the provided parameters are invalid or missing.
*
* @example
* // Handling OAuth callback in a React component
* useEffect(() => {
* const handleOAuthCallback = async () => {
* try {
* const result = await SendCallbackToServer(window.location.search, "google");
* // Handle successful authentication (e.g., store tokens, redirect user)
* console.log("Authentication successful:", result);
* } catch (error) {
* // Handle authentication errors
* console.error("Authentication failed:", error);
* }
* };
*
* handleOAuthCallback();
* }, []);
*
* @example
* // Usage with different providers
* await SendCallbackToServer(window.location.search, "github");
* await SendCallbackToServer(window.location.search, "facebook");
* await SendCallbackToServer(window.location.search, "microsoft");
*
* @remarks
* - This function is specifically designed for OAuth callback handling in a Next.js frontend
* acting as a proxy to an Elysia backend.
* - The `data` parameter should include the complete query string from the OAuth redirect.
* - The callback URI is automatically constructed using the APP_DOMAIN environment variable.
* - Ensure APP_DOMAIN is properly configured in your environment variables.
*/
export const SendCallbackToServer = async (
data: string,
provider: string
): Promise<ServerRequestCallback> => {
// Construct the backend and frontend handler URLs
const backendHandlerUrl = `auth/${provider}/callback/`;
const frontendHandlerUrl = `${process.env
.APP_DOMAIN!}/auth/callback/${provider}`;
try {
// Forward the OAuth callback data to the backend for processing
const response = await api.get(
`${backendHandlerUrl}${data}&callbackURI=${frontendHandlerUrl}`
);
// Parse the JSON response from the backend and return the result
const result = await response.json();
return {
success: true,
status: response.status,
text: { message: "Callback processed successfully" },
data: result,
};
} catch (error) {
return apiErrorHandler(error);
}
};
"use server";
import { api } from "@/shared/lib/ky/connector";
import { apiErrorHandler } from "@/shared/lib/ky/errorHandler";
import { ServerRequestCallback } from "@/shared/types/serverRequestCallback";
/**
* @function SendCallbackToServer
* @description Proxies OAuth callback requests from the frontend to the main backend system.
* Acts as an intermediary between the client Next.js application and the Elysia server.
* Handles the forwarding of OAuth provider callback data for authentication processing.
*
* @param {string} data - The OAuth callback data received from the provider, typically containing
* query parameters such as authorization code, user consent, scopes, state,
* and other OAuth-specific information. Usually obtained from
* `window.location.search` in browser environments.
* @param {string} provider - The name of the OAuth provider/service (e.g., "google", "github",
* "facebook"). Used to construct the appropriate backend API endpoint.
*
* @returns {Promise<Object>} The response data from the backend server after processing the
* OAuth callback. Typically contains authentication tokens, user
* information, or session data.
*
* @throws {Error} If the network request fails or the backend returns an error response.
* @throws {Error} If the required environment variable APP_DOMAIN is not defined.
* @throws {Error} If the provided parameters are invalid or missing.
*
* @example
* // Handling OAuth callback in a React component
* useEffect(() => {
* const handleOAuthCallback = async () => {
* try {
* const result = await SendCallbackToServer(window.location.search, "google");
* // Handle successful authentication (e.g., store tokens, redirect user)
* console.log("Authentication successful:", result);
* } catch (error) {
* // Handle authentication errors
* console.error("Authentication failed:", error);
* }
* };
*
* handleOAuthCallback();
* }, []);
*
* @example
* // Usage with different providers
* await SendCallbackToServer(window.location.search, "github");
* await SendCallbackToServer(window.location.search, "facebook");
* await SendCallbackToServer(window.location.search, "microsoft");
*
* @remarks
* - This function is specifically designed for OAuth callback handling in a Next.js frontend
* acting as a proxy to an Elysia backend.
* - The `data` parameter should include the complete query string from the OAuth redirect.
* - The callback URI is automatically constructed using the APP_DOMAIN environment variable.
* - Ensure APP_DOMAIN is properly configured in your environment variables.
*/
export const SendCallbackToServer = async (
data: string,
provider: string
): Promise<ServerRequestCallback> => {
// Construct the backend and frontend handler URLs
const backendHandlerUrl = `auth/${provider}/callback/`;
const frontendHandlerUrl = `${process.env
.APP_DOMAIN!}/auth/callback/${provider}`;
try {
// Forward the OAuth callback data to the backend for processing
const response = await api.get(
`${backendHandlerUrl}${data}&callbackURI=${frontendHandlerUrl}`
);
// Parse the JSON response from the backend and return the result
const result = await response.json();
return {
success: true,
status: response.status,
text: { message: "Callback processed successfully" },
data: result,
};
} catch (error) {
return apiErrorHandler(error);
}
};

View File

@ -1,56 +1,56 @@
"use client";
import { redirect } from "next/navigation";
import React, { useEffect, useState } from "react";
import SecurityCheckup from "@/shared/auth/ui/SecurityCheckup";
import SecurityCheckupFailed from "@/shared/auth/ui/SecurityCheckupFailed";
import LoadingProcess from "../ui/LoadingProcess";
const OauthCallbackHandler = () => {
/**
* Create a lit component that will be used in popp, consisting of 3 component flows:
* 1. When the user opens it, a browser environment check will be performed.
* 2. If it passes, the login component will appear and the user will perform authentication.
* 3. If it fails, stop the authentication process and display the warning component, then return the user to the homepage.
*/
const componentFlowList = {
securityCheckup: <SecurityCheckup />,
securityCheckupFailed: <SecurityCheckupFailed />,
proceedCallback: <LoadingProcess />,
};
// State to set the current page component
const [componentFlow, setComponentFlow] = useState(
componentFlowList.securityCheckup
);
useEffect(() => {
// Prevent opening devtools while in authentication page
// disableDevtool();
/**
* Check if the window has an opener (i.e., it was opened by another window)
* If it does, the security checkup has passed.
* If it doesn't, the security checkup has failed and user will be redirected to the homepage.
*/
if (window.opener) {
setComponentFlow(componentFlowList.proceedCallback);
} else {
setComponentFlow(componentFlowList.securityCheckupFailed);
const timer = setTimeout(() => {
redirect("/");
}, 5000);
return () => clearTimeout(timer);
}
}, []);
return (
<>
{/* show the current component flow */}
<main>{componentFlow}</main>
</>
);
};
export default OauthCallbackHandler;
"use client";
import { redirect } from "next/navigation";
import React, { useEffect, useState } from "react";
import SecurityCheckup from "@/shared/auth/ui/SecurityCheckup";
import SecurityCheckupFailed from "@/shared/auth/ui/SecurityCheckupFailed";
import LoadingProcess from "../ui/LoadingProcess";
const OauthCallbackHandler = () => {
/**
* Create a lit component that will be used in popp, consisting of 3 component flows:
* 1. When the user opens it, a browser environment check will be performed.
* 2. If it passes, the login component will appear and the user will perform authentication.
* 3. If it fails, stop the authentication process and display the warning component, then return the user to the homepage.
*/
const componentFlowList = {
securityCheckup: <SecurityCheckup />,
securityCheckupFailed: <SecurityCheckupFailed />,
proceedCallback: <LoadingProcess />,
};
// State to set the current page component
const [componentFlow, setComponentFlow] = useState(
componentFlowList.securityCheckup
);
useEffect(() => {
// Prevent opening devtools while in authentication page
// disableDevtool();
/**
* Check if the window has an opener (i.e., it was opened by another window)
* If it does, the security checkup has passed.
* If it doesn't, the security checkup has failed and user will be redirected to the homepage.
*/
if (window.opener) {
setComponentFlow(componentFlowList.proceedCallback);
} else {
setComponentFlow(componentFlowList.securityCheckupFailed);
const timer = setTimeout(() => {
redirect("/");
}, 5000);
return () => clearTimeout(timer);
}
}, []);
return (
<>
{/* show the current component flow */}
<main>{componentFlow}</main>
</>
);
};
export default OauthCallbackHandler;

View File

@ -1,9 +1,9 @@
export interface ParamProps {
params: { provider: string[] };
searchParams:
| string
| string[][]
| Record<string, string>
| URLSearchParams
| undefined;
}
export interface ParamProps {
params: { provider: string[] };
searchParams:
| string
| string[][]
| Record<string, string>
| URLSearchParams
| undefined;
}

View File

@ -1,73 +1,73 @@
"use client";
import React from "react";
import { addToast, Button, CircularProgress, Link } from "@heroui/react";
import { SendCallbackToServer } from "../lib/sendCallbackToServer";
import { useParams } from "next/navigation";
import { useRunOnce } from "@/shared/hooks/useRunOnce";
import { routes } from "@/shared/config/routes";
const LoadingProcess = () => {
// Access the URL parameters
const params = useParams();
// Forward the callback response to the backend server
useRunOnce("forwardCallbackResponseToBackend", async () => {
try {
const response = await SendCallbackToServer(
window.location.search,
params.provider as string
);
if (response.success) {
window.close();
} else {
addToast({
title: "😬 Oops, there's a problem!",
description: response.text.message,
color: "danger",
timeout: 0,
endContent: (
<Button
size="sm"
variant="flat"
onPress={() => (window.location.href = routes.login)}
>
Try again
</Button>
),
});
}
} catch (error) {
console.log(error);
addToast({
title: "😵‍💫 Oops, lost connection!",
description: "Check your internet and try again",
color: "danger",
timeout: 0,
endContent: (
<Button
size="sm"
variant="flat"
onPress={() => (window.location.href = routes.login)}
>
Reload
</Button>
),
});
}
});
return (
<div className="w-full flex flex-col items-center text-center mt-[26vh]">
<CircularProgress aria-label="Loading..." size="lg" />
<div className="mt-4">
<h1 className="text-lg text-neutral-200">Please wait...</h1>
<p className="text-sm text-neutral-400">
Your request is being processed
</p>
</div>
</div>
);
};
export default LoadingProcess;
"use client";
import React from "react";
import { addToast, Button, CircularProgress, Link } from "@heroui/react";
import { SendCallbackToServer } from "../lib/sendCallbackToServer";
import { useParams } from "next/navigation";
import { useRunOnce } from "@/shared/hooks/useRunOnce";
import { routes } from "@/shared/config/routes";
const LoadingProcess = () => {
// Access the URL parameters
const params = useParams();
// Forward the callback response to the backend server
useRunOnce("forwardCallbackResponseToBackend", async () => {
try {
const response = await SendCallbackToServer(
window.location.search,
params.provider as string
);
if (response.success) {
window.close();
} else {
addToast({
title: "😬 Oops, there's a problem!",
description: response.text.message,
color: "danger",
timeout: 0,
endContent: (
<Button
size="sm"
variant="flat"
onPress={() => (window.location.href = routes.login)}
>
Try again
</Button>
),
});
}
} catch (error) {
console.log(error);
addToast({
title: "😵‍💫 Oops, lost connection!",
description: "Check your internet and try again",
color: "danger",
timeout: 0,
endContent: (
<Button
size="sm"
variant="flat"
onPress={() => (window.location.href = routes.login)}
>
Reload
</Button>
),
});
}
});
return (
<div className="w-full flex flex-col items-center text-center mt-[26vh]">
<CircularProgress aria-label="Loading..." size="lg" />
<div className="mt-4">
<h1 className="text-lg text-neutral-200">Please wait...</h1>
<p className="text-sm text-neutral-400">
Your request is being processed
</p>
</div>
</div>
);
};
export default LoadingProcess;