Files
nobat724_front/components/register/verificationPage/SendReq.js
T
hamedandClaude Opus 4.8 f584f581e5 fix(auth): correct login detection + return to origin after login
- isUserLoggedIn() checked the access_token cookie, which is never set
  (access_token lives in memory / tokenStore; only userInfo + uuid are
  cookies). It therefore always returned false — the claim modal (and
  comment auth checks) kept showing the login prompt even when logged in.
  Now reads the userInfo cookie.
- Claim modal login link carries ?redirect=<current path>; after OTP login
  SendReq returns to that path (guarded to internal "/..." only, blocks
  protocol-relative //) instead of always going to "/".

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 15:12:58 +03:30

128 lines
3.8 KiB
JavaScript

import { Button, CircularProgress } from "@mui/material";
import { request } from "@/services/response";
import Cookies from "js-cookie";
import { toast } from "react-toastify";
import { handleTimeExpiresToken } from "@/helper";
import { setAccessToken } from "@/lib/tokenStore";
function SendReq({
loading,
setLoading,
code,
setIsSendMsg,
setStep,
setIsError,
uuid,
}) {
const handleReq = async () => {
setLoading(true);
try {
const res = await fetch("/api/auth/token", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ uuid, code: code.join("") }),
});
const response = await res.json();
if (response.access_token) {
handleSetCookie(response);
} else {
setLoading(false);
setIsError(true);
const message = response?.errors?.[0]?.message || "کد تأیید نادرست یا منقضی شده است.";
toast.error(message);
}
} catch {
setLoading(false);
setIsError(true);
toast.error("خطا در برقراری ارتباط. دوباره تلاش کنید.");
}
};
const handleSetCookie = (response) => {
const expiresTime = handleTimeExpiresToken(response.expires_in);
const hostname = window.location.hostname;
const isHttps = window.location.protocol === "https:";
const isLocalhost = hostname.includes("localhost");
// فقط داده‌های غیرحساس در کوکی JS؛ access_token در memory، refresh_token در کوکی HttpOnly سرور
let cookieOptions = {
path: "/",
sameSite: "lax",
expires: expiresTime.refreshTokenExpires,
};
if (!isLocalhost && isHttps) {
cookieOptions = {
...cookieOptions,
secure: true,
domain: `.${hostname.split(".").slice(-2).join(".")}`,
};
}
setAccessToken(response.access_token);
Cookies.set("uuid", uuid, cookieOptions);
getInfo(response.access_token, cookieOptions);
};
const getInfo = (token, cookieOptions) => {
request
.getUserInfo({
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((res) => {
setLoading(false);
const profile = res?.data;
if (profile?.uuid) {
const userInfo = { ...profile, username: profile.mobile_number };
Cookies.set("userInfo", JSON.stringify(userInfo), cookieOptions);
// overwrite the OTP uuid set in handleSetCookie with the real user uuid
Cookies.set("uuid", profile.uuid, cookieOptions);
// اگر در صفحه appointment هستیم، به مرحله 3 (Detail) می‌رویم
if (setStep) {
setStep(3);
} else {
// بازگشت به صفحهٔ مبدأ اگر ?redirect= داده شده (فقط مسیر داخلی امن)
const redirect = new URLSearchParams(window.location.search).get("redirect");
window.location.href =
redirect && redirect.startsWith("/") && !redirect.startsWith("//")
? redirect
: "/";
}
} else {
setIsError(true);
toast.error("دریافت اطلاعات کاربر ناموفق بود. دوباره تلاش کنید.");
}
})
.catch(() => {
setLoading(false);
setIsError(true);
});
};
return (
<Button
fullWidth
disabled={loading}
variant="contained"
onClick={() => {
setIsSendMsg && setIsSendMsg(true);
if (code.join("").length !== 5) {
setIsError(true);
} else {
handleReq();
}
}}
className="!rounded-[8px] !bg-[#5559CE]"
>
{loading ? <CircularProgress size={22} sx={{ color: "#fff" }} /> : "تایید"}
</Button>
);
}
export default SendReq;