Refresh Token added + ui bug fixed

Kahdooie
Hossein Rahmani 2024-01-22 14:31:29 +03:30
parent 1d36e37376
commit 105fea9232
6 changed files with 93 additions and 48 deletions

View File

@ -15,7 +15,7 @@ export default function RootLayout({
return ( return (
<> <>
<NavbarPanel /> <NavbarPanel />
<div className="mt-10 mx-auto px-2">{children}</div> <div className="px-2 mx-auto mt-10">{children}</div>
</> </>
); );
} }

View File

@ -58,16 +58,14 @@ export default function Login() {
const loginMutation = useMutation({ const loginMutation = useMutation({
mutationFn: loginStaff, mutationFn: loginStaff,
onSuccess: (res) => {}, onSuccess: (res) => {
onError: (err: any | string) => {
if (err.response.status == 428) {
console.log(useData);
router.push("/Verify"); router.push("/Verify");
} else { localStorage.setItem("verificationToken", res.verificationToken);
},
onError: (err: any | string) => {
toast("مشکلی در ارسال درخواست به وجود آمد.", { toast("مشکلی در ارسال درخواست به وجود آمد.", {
className: "!bg-red-500 !text-white", className: "!bg-red-500 !text-white",
}); });
}
}, },
}); });
@ -97,12 +95,12 @@ export default function Login() {
: null; : null;
return ( return (
<div className=" w-screen h-screen grid place-content-center bg-gray-200 "> <div className="grid w-screen h-screen bg-gray-200 place-content-center">
<div <div
className="w-full sm:[20rem] md:[20rem] xl:w-[30rem] bg-white rounded-lg dark:border xl:p-0 dark:bg-gray-800 dark:border-gray-700 shadow-[0px_0px_15px_0px_#00000040] className="w-full sm:[20rem] md:[20rem] xl:w-[30rem] bg-white rounded-lg dark:border xl:p-0 dark:bg-gray-800 dark:border-gray-700 shadow-[0px_0px_15px_0px_#00000040]
h-fit" h-fit"
> >
<div className="space-y-3 md:space-y-4 flex flex-col md:py-10 p-10 md:px-12 lg:px-16 h-full justify-center"> <div className="flex flex-col justify-center h-full p-10 space-y-3 md:space-y-4 md:py-10 md:px-12 lg:px-16">
<Image alt="icon" src={LoginIcon} className="self-center w-1/3 " /> <Image alt="icon" src={LoginIcon} className="self-center w-1/3 " />
<p className="text-lg font-bold leading-tight tracking-tight text-blue dark:text-white"> <p className="text-lg font-bold leading-tight tracking-tight text-blue dark:text-white">
@ -112,7 +110,7 @@ export default function Login() {
<Form {...form}> <Form {...form}>
<form <form
onSubmit={form.handleSubmit(onSubmit)} onSubmit={form.handleSubmit(onSubmit)}
className="w-full flex flex-col " className="flex flex-col w-full "
> >
<FormField <FormField
control={form.control} control={form.control}
@ -158,13 +156,13 @@ export default function Login() {
</FormItem> </FormItem>
)} )}
/> />
<div className="flex gap-3 mt-4 items-center"> <div className="flex items-center gap-3 mt-4">
<FormField <FormField
control={form.control} control={form.control}
name="captcha" name="captcha"
rules={{ required: true }} rules={{ required: true }}
render={({ field }) => ( render={({ field }) => (
<FormItem className=" items-center h-10 flex-1"> <FormItem className="items-center flex-1 h-10 ">
{/* <FormLabel className="text-[#7C838A] text-sm font-medium mt-7"> {/* <FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
رمز عبور رمز عبور
</FormLabel> */} </FormLabel> */}
@ -176,7 +174,7 @@ export default function Login() {
)} )}
/> />
{isLoading ? ( {isLoading ? (
<div className=" w-36 flex justify-center text-center"> <div className="flex justify-center text-center w-36">
<ThreeDots <ThreeDots
visible={true} visible={true}
height="50" height="50"
@ -189,31 +187,31 @@ export default function Login() {
/> />
</div> </div>
) : ( ) : (
<div className=" flex items-center justify-center text-center gap-2"> <div className="flex items-center justify-center gap-2 text-center ">
<Image <Image
alt="icon" alt="icon"
src={srcForImage as string} src={srcForImage as string}
className=" h-12 rounded-md shadow-md w-36" className="h-12 rounded-md shadow-md w-36"
width={150} width={150}
height={20} height={20}
quality={100} quality={100}
/> />
<RefreshCcw <RefreshCcw
className=" cursor-pointer" className="cursor-pointer "
onClick={() => refetch()} onClick={() => refetch()}
color="#003778" color="#003778"
/> />
</div> </div>
)} )}
</div> </div>
<div className="flex justify-end gap-2 w-full mt-14"> <div className="flex justify-end w-full gap-2 mt-14">
<Button <Button
disabled={loginMutation.isPending} disabled={loginMutation.isPending}
type="submit" type="submit"
className="bg-blue hover:bg-blue/90 transition text-white w-1/2 md:w-1/3 p-2 rounded-xl" className="w-1/2 p-2 text-white transition bg-blue hover:bg-blue/90 md:w-1/3 rounded-xl"
> >
{loginMutation.isPending ? ( {loginMutation.isPending ? (
<div className="flex justify-center items-center gap-2"> <div className="flex items-center justify-center gap-2">
<Oval <Oval
visible={true} visible={true}
height="20" height="20"

View File

@ -42,12 +42,9 @@ export default function NavbarPanel() {
return ( return (
<div <div
className="fixed flex justify-between items-center gap-3 className="fixed top-0 z-10 flex flex-row items-center justify-between w-full gap-3 px-8 py-4 shadow-md sm:items-center sm:gap-0 bg-blue max-md:px-4 "
flex-row sm:items-center sm:gap-0
w-full px-8 py-4 z-10 top-0 bg-blue max-md:px-4 shadow-md
"
> >
<div className=" flex items-center gap-8 max-md:gap-4"> <div className="flex items-center gap-8 max-md:gap-4">
<div className=" md:hidden"> <div className=" md:hidden">
<Hamburger <Hamburger
toggled={isOpen} toggled={isOpen}
@ -57,7 +54,7 @@ export default function NavbarPanel() {
color="#fff" color="#fff"
/> />
</div> </div>
<p className="text-white inline-block bg-clip-text text-sm font-bold max-md:text-sm max-md:font-medium"> <p className="inline-block text-sm font-bold text-white bg-clip-text max-md:text-sm max-md:font-medium">
پنل کاربری {<span className=" max-md:hidden">|</span>} پنل کاربری {<span className=" max-md:hidden">|</span>}
</p> </p>
@ -127,8 +124,8 @@ export default function NavbarPanel() {
)} )}
</div> </div>
</div> </div>
<div className=" flex gap-4 items-center"> <div className="flex items-center gap-4 ">
<h1 className="text-white inline-block bg-clip-text before:max-md:hidden text-sm font-bold max-md:text-xs max-md:font-medium"> <h1 className="inline-block text-sm font-bold text-white bg-clip-text before:max-md:hidden max-md:text-xs max-md:font-medium">
{data && ( {data && (
<> <>
{role === "Admin" {role === "Admin"
@ -137,7 +134,7 @@ export default function NavbarPanel() {
</> </>
)} )}
</h1> </h1>
<div className="hover:bg-white/50 p-1 rounded-md"> <div className="p-1 rounded-md hover:bg-white/50">
<LogOut <LogOut
onClick={() => { onClick={() => {
deleteCookie("Sootzani_Token"); deleteCookie("Sootzani_Token");
@ -145,7 +142,7 @@ export default function NavbarPanel() {
localStorage.removeItem("privatePassword"); localStorage.removeItem("privatePassword");
router.push("/"); router.push("/");
}} }}
className=" text-white cursor-pointer" className="text-white cursor-pointer "
/> />
</div> </div>
</div> </div>

View File

@ -22,8 +22,9 @@ export default function Verify() {
const verifyMutation = useMutation({ const verifyMutation = useMutation({
mutationFn: verifyStaff, mutationFn: verifyStaff,
onSuccess: (res) => { onSuccess: (res) => {
const decodedToken = jwtDecode<any>(res); const decodedToken = jwtDecode<any>(res.jwtToken);
setCookie("Sootzani_Token", res); setCookie("Sootzani_Token", res.jwtToken);
setCookie("Sootzani_Refresh_Token", res.refreshToken);
const userRole = const userRole =
decodedToken[ decodedToken[
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role" "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
@ -75,19 +76,22 @@ export default function Verify() {
useEffect(() => { useEffect(() => {
if (otp.length == 6) { if (otp.length == 6) {
const payload = { ...userData, verificationCode: otp }; const payload = {
otpToken: localStorage.getItem("verificationToken"),
verificationCode: otp,
};
console.log(userData); console.log(userData);
verifyMutation.mutate(payload); verifyMutation.mutate(payload);
} }
}, [otp]); }, [otp]);
return ( return (
<div className=" w-screen h-screen grid place-content-center bg-gray-200"> <div className="grid w-screen h-screen bg-gray-200 place-content-center">
<div <div
className="w-full sm:[20rem] md:[20rem] xl:w-[30rem] bg-white rounded-lg dark:border xl:p-0 dark:bg-gray-800 dark:border-gray-700 shadow-[0px_0px_15px_0px_#00000040] className="w-full sm:[20rem] md:[20rem] xl:w-[30rem] bg-white rounded-lg dark:border xl:p-0 dark:bg-gray-800 dark:border-gray-700 shadow-[0px_0px_15px_0px_#00000040]
h-fit" h-fit"
> >
<div className="space-y-3 md:space-y-4 flex flex-col md:py-12 md:px-20 h-full justify-center"> <div className="flex flex-col justify-center h-full p-10 space-y-3 md:space-y-4 md:py-10 md:px-12 lg:px-16">
<Image alt="icon" src={LoginIcon} className="self-center w-1/3 " /> <Image alt="icon" src={LoginIcon} className="self-center w-1/3 " />
<p className="text-lg font-bold leading-tight tracking-tight text-blue dark:text-white"> <p className="text-lg font-bold leading-tight tracking-tight text-blue dark:text-white">
تایید کد تایید کد
@ -105,20 +109,20 @@ export default function Verify() {
inputStyle=" !w-10 rounded-md h-10 bg-[#F5F5F5] border border-blue/30 text-black" inputStyle=" !w-10 rounded-md h-10 bg-[#F5F5F5] border border-blue/30 text-black"
/> />
</div> </div>
<label className="label text-center"> <label className="text-center label">
<span className="text-xs text-blue/70 label-text text-center"> <span className="text-xs text-center text-blue/70 label-text">
کد دریافت شده توسط پیامک را وارد نمایید. کد دریافت شده توسط پیامک را وارد نمایید.
</span> </span>
</label> </label>
{/* <div className="flex justify-end gap-2 w-full mt-14"> {/* <div className="flex justify-end w-full gap-2 mt-14">
<Button <Button
disabled={verifyMutation.isPending} disabled={verifyMutation.isPending}
onClick={handelVerify} onClick={handelVerify}
type="submit" type="submit"
className="bg-blue hover:bg-blue/90 text-white w-1/2 md:w-1/3 p-2 rounded-xl" className="w-1/2 p-2 text-white bg-blue hover:bg-blue/90 md:w-1/3 rounded-xl"
> >
{verifyMutation.isPending ? ( {verifyMutation.isPending ? (
<div className="flex justify-center items-center gap-2"> <div className="flex items-center justify-center gap-2">
<Oval <Oval
visible={true} visible={true}
height="20" height="20"

View File

@ -1,8 +1,39 @@
import axios from "axios"; import axios from "axios";
import { CookieValueTypes } from "cookies-next"; import {
CookieValueTypes,
deleteCookie,
getCookie,
setCookie,
} from "cookies-next";
import { redirect } from "next/navigation";
axios.defaults.baseURL = process.env.NEXT_PUBLIC_BASE_URL_APP; axios.defaults.baseURL = process.env.NEXT_PUBLIC_BASE_URL_APP;
axios.interceptors.response.use(
(response) => {
return response;
},
async function (error) {
const originalRequest = error.config;
if (error.response.status === 401) {
const accessToken = getCookie("Sootzani_Token");
const refreshToken = getCookie("Sootzani_Refresh_Token");
const data = await RefreshToken({
token: accessToken,
refreshToken: refreshToken,
});
}
// if (error.response.status === 403 && !originalRequest._retry) {
// originalRequest._retry = true;
// const access_token = await refreshAccessToken();
// axios.defaults.headers.common["Authorization"] = "Bearer " + access_token;
// return axiosApiInstance(originalRequest);
// }
// return Promise.reject(error);
}
);
export async function loginStaff(payload: { export async function loginStaff(payload: {
username: string; username: string;
password: string; password: string;
@ -16,8 +47,7 @@ export async function loginStaff(payload: {
} }
export async function verifyStaff(payload: { export async function verifyStaff(payload: {
username: string; otpToken: string | null;
password: string;
verificationCode: string; verificationCode: string;
}) { }) {
const data = await axios.post("api/Authenticate/VerifyStaff", payload); const data = await axios.post("api/Authenticate/VerifyStaff", payload);
@ -66,3 +96,16 @@ export async function editProfile(payload: {
const data = await axios.put("api/Authenticate/Profile", payload); const data = await axios.put("api/Authenticate/Profile", payload);
return data.data; return data.data;
} }
export async function RefreshToken(payload: { token: any; refreshToken: any }) {
try {
const response = await axios.post("api/Authenticate/Refresh", payload);
setCookie("Sootzani_Token", response.data.jwtToken);
setCookie("Sootzani_Refresh_Token", response.data.refreshToken);
return response.data;
} catch (error) {
deleteCookie("Sootzani_Token");
deleteCookie("Sootzani_Refresh_Token");
window.location.href = "/";
}
}

View File

@ -2,6 +2,7 @@
// import useToken from "@/store/useToken"; // import useToken from "@/store/useToken";
import axios from "axios"; import axios from "axios";
import { CookieValueTypes, getCookie } from "cookies-next"; import { CookieValueTypes, getCookie } from "cookies-next";
import { RefreshToken } from "./authenticateApi";
axios.defaults.baseURL = process.env.NEXT_PUBLIC_BASE_URL_APP; axios.defaults.baseURL = process.env.NEXT_PUBLIC_BASE_URL_APP;
@ -11,6 +12,8 @@ axios.interceptors.request.use(function (config) {
return config; return config;
}); });
export async function getPossibleStates() { export async function getPossibleStates() {
const data = await axios.get(`api/Inspector/PossibleStates`); const data = await axios.get(`api/Inspector/PossibleStates`);
return data.data; return data.data;