fix: resolve critical bugs and security issues across the project

- Fix GPS map links always sending literal "latitude"/"longitude" strings
  instead of actual coordinates in openLocation/Content.js
- Add api.clinic-pro.ir to next.config.js remotePatterns so production
  images load correctly
- Fix appointment page: await params and getStateInfo (Next.js 15 pattern)
- Enable 401 handling in api.js: clear cookies and redirect to /login
- Move OAuth client_secret to server-side API routes (/api/auth/token,
  /api/auth/refresh) so it is never bundled into client-side JavaScript
- Update SendReq, SubmitData, ButtonSendData to call API routes instead
  of directly sending client_secret from the browser
- Update docker-compose.yml to use server-only CLIENT_SECRET env var
- Remove debug console.log from clinic doctors list component

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
hamed
2026-06-05 22:18:11 +03:30
co-authored by Claude Sonnet 4.6
parent ec536bfc32
commit 1aa9f82d2a
11 changed files with 126 additions and 70 deletions
+31
View File
@@ -0,0 +1,31 @@
import { NextResponse } from "next/server";
export async function POST(request) {
const { refresh_token } = await request.json();
const API_URL = process.env.NEXT_PUBLIC_API_URL;
const CLIENT_ID = process.env.CLIENT_ID || process.env.NEXT_PUBLIC_CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET || process.env.NEXT_PUBLIC_CLIENT_SECRET;
if (!refresh_token) {
return NextResponse.json({ error: "refresh_token is required" }, { status: 400 });
}
const formData = new URLSearchParams();
formData.append("grant_type", "refresh_token");
formData.append("client_id", CLIENT_ID);
formData.append("client_secret", CLIENT_SECRET);
formData.append("refresh_token", refresh_token);
try {
const res = await fetch(`${API_URL}/oauth/token`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded", Authorization: "" },
body: formData.toString(),
});
const data = await res.json();
return NextResponse.json(data, { status: res.status });
} catch {
return NextResponse.json({ error: "Refresh request failed" }, { status: 500 });
}
}
+33
View File
@@ -0,0 +1,33 @@
import { NextResponse } from "next/server";
export async function POST(request) {
const { uuid, code, scope = "nobat724" } = await request.json();
const API_URL = process.env.NEXT_PUBLIC_API_URL;
const CLIENT_ID = process.env.CLIENT_ID || process.env.NEXT_PUBLIC_CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET || process.env.NEXT_PUBLIC_CLIENT_SECRET;
if (!uuid || !code) {
return NextResponse.json({ error: "uuid and code are required" }, { status: 400 });
}
const formData = new URLSearchParams();
formData.append("grant_type", "mobile");
formData.append("client_id", CLIENT_ID);
formData.append("client_secret", CLIENT_SECRET);
formData.append("uuid", uuid);
formData.append("code", code);
formData.append("scope", scope);
try {
const res = await fetch(`${API_URL}/oauth/token`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded", Authorization: "" },
body: formData.toString(),
});
const data = await res.json();
return NextResponse.json(data, { status: res.status });
} catch {
return NextResponse.json({ error: "Token request failed" }, { status: 500 });
}
}
+5 -12
View File
@@ -2,33 +2,26 @@ import AppointmentPage from "@/components/appointment";
import { getStateInfo } from "@/lib/getStateInfo"; import { getStateInfo } from "@/lib/getStateInfo";
import axios from "axios"; import axios from "axios";
async function Appointment({ params: { doctorId } }) { async function Appointment({ params }) {
const { matchedCity } = getStateInfo(); const { doctorId } = await params;
const { matchedCity } = await getStateInfo();
const API_URL = process.env.NEXT_PUBLIC_API_URL; const API_URL = process.env.NEXT_PUBLIC_API_URL;
let doctor = null; let doctor = null;
let disabledDates = []; let disabledDates = [];
try { try {
// دریافت اطلاعات دکتر با UUID
const doctorRes = await axios.get(`${API_URL}/api/v1/doctor/${doctorId}`); const doctorRes = await axios.get(`${API_URL}/api/v1/doctor/${doctorId}`);
doctor = doctorRes.data; doctor = doctorRes.data;
// دریافت روزهای غیرفعال با استفاده از doctor.id
if (doctor && doctor.id) { if (doctor && doctor.id) {
const disabledDatesRes = await axios.get( const disabledDatesRes = await axios.get(
`${API_URL}/api/v1/appointment/not-available/${doctor.id}`, `${API_URL}/api/v1/appointment/not-available/${doctor.id}`,
{ { headers: { "Content-Type": "application/json" } }
headers: {
'Content-Type': 'application/json'
}
}
); );
disabledDates = disabledDatesRes.data?.data || []; disabledDates = disabledDatesRes.data?.data || [];
} }
} catch (error) { } catch (error) {}
console.error("Error fetching appointment data:", error.message);
}
return ( return (
<AppointmentPage <AppointmentPage
+5 -5
View File
@@ -8,27 +8,27 @@ function Content({ data, onClose }) {
{ {
src: "/assets/images/snapp.png", src: "/assets/images/snapp.png",
name: "snapp", name: "snapp",
url: `https://snapp.ir/route?lat=${"latitude"}&lng=${"longitude"}`, url: `https://snapp.ir/route?lat=${latitude}&lng=${longitude}`,
}, },
{ {
src: "/assets/images/tapsi.png", src: "/assets/images/tapsi.png",
name: "tapsi", name: "tapsi",
url: `https://tapsi.ir/route?lat=${"latitude"}&lng=${"longitude"}`, url: `https://tapsi.ir/route?lat=${latitude}&lng=${longitude}`,
}, },
{ {
src: "/assets/images/maps.png", src: "/assets/images/maps.png",
name: "maps", name: "maps",
url: `https://www.google.com/maps/dir/?api=1&destination=${"latitude"},${"longitude"}`, url: `https://www.google.com/maps/dir/?api=1&destination=${latitude},${longitude}`,
}, },
{ {
src: "/assets/images/balad.png", src: "/assets/images/balad.png",
name: "balad", name: "balad",
url: `https://balad.ir/map?lat=${"latitude"}&lng=${"longitude"}`, url: `https://balad.ir/map?lat=${latitude}&lng=${longitude}`,
}, },
{ {
src: "/assets/images/waze.png", src: "/assets/images/waze.png",
name: "waze", name: "waze",
url: `https://waze.com/ul?ll=${"latitude"},${"longitude"}&navigate=yes`, url: `https://waze.com/ul?ll=${latitude},${longitude}&navigate=yes`,
}, },
]; ];
+8 -11
View File
@@ -12,17 +12,14 @@ function SubmitData({ setStep, data, prevData, setErrors, doctor, selectedSlot,
const refreshAccessToken = async () => { const refreshAccessToken = async () => {
try { try {
const refreshToken = Cookies.get("refresh_token"); const refreshToken = Cookies.get("refresh_token");
if (!refreshToken) { if (!refreshToken) return false;
return false;
}
const formData = new URLSearchParams(); const res = await fetch("/api/auth/refresh", {
formData.append("grant_type", "refresh_token"); method: "POST",
formData.append("client_id", process.env.NEXT_PUBLIC_CLIENT_ID || "4gSZTqkcM-13yfCHptFjsIoEzwA996bjGuSEFy02Dkc"); headers: { "Content-Type": "application/json" },
formData.append("client_secret", process.env.NEXT_PUBLIC_CLIENT_SECRET || "13yfCHptFjsIoEzwA996bjGuSEFy02Dkc"); body: JSON.stringify({ refresh_token: refreshToken }),
formData.append("refresh_token", refreshToken); });
const response = await res.json();
const response = await request.postRefreshToken(formData);
if (response?.access_token) { if (response?.access_token) {
Cookies.set("access_token", response.access_token, { expires: 7 }); Cookies.set("access_token", response.access_token, { expires: 7 });
@@ -32,7 +29,7 @@ function SubmitData({ setStep, data, prevData, setErrors, doctor, selectedSlot,
return true; return true;
} }
return false; return false;
} catch (error) { } catch {
return false; return false;
} }
}; };
@@ -36,7 +36,6 @@ function List({
}; };
const res = await getClinicDoctors(slug, params); const res = await getClinicDoctors(slug, params);
console.log("📦 پاسخ API:", res);
// اگر سرور داده را در data برمی‌گرداند // اگر سرور داده را در data برمی‌گرداند
if (res?.data) { if (res?.data) {
@@ -29,26 +29,22 @@ function ButtonSendData({
.postUserProfile(changeDateType(information, false)) .postUserProfile(changeDateType(information, false))
.then((response) => { .then((response) => {
if (response.uuid) { if (response.uuid) {
const formData = new URLSearchParams(); fetch("/api/auth/refresh", {
formData.append("grant_type", "refresh_token"); method: "POST",
formData.append("client_id", process.env.NEXT_PUBLIC_CLIENT_ID); headers: { "Content-Type": "application/json" },
formData.append( body: JSON.stringify({ refresh_token: Cookies.get("refresh_token") }),
"client_secret", })
process.env.NEXT_PUBLIC_CLIENT_SECRET .then((r) => r.json())
);
formData.append("refresh_token", Cookies.get("refresh_token"));
request
.postRefreshToken(formData)
.then((res) => { .then((res) => {
const expiresTime = handleTimeExpiresToken(res.expires_in); if (res?.access_token) {
Cookies.set("access_token", res.access_token, { const expiresTime = handleTimeExpiresToken(res.expires_in);
expires: expiresTime.accessTokenExpires, Cookies.set("access_token", res.access_token, {
path: "/", expires: expiresTime.accessTokenExpires,
secure: true, path: "/",
sameSite: "strict", secure: true,
}); sameSite: "strict",
});
}
setInformation({ setInformation({
...information, ...information,
prev_data: true, prev_data: true,
@@ -56,7 +52,7 @@ function ButtonSendData({
}); });
setLoading(false); setLoading(false);
}) })
.catch((err) => { .catch(() => {
setLoading(false); setLoading(false);
}); });
} }
+15 -15
View File
@@ -14,23 +14,23 @@ function SendReq({
}) { }) {
const handleReq = async () => { const handleReq = async () => {
setLoading(true); setLoading(true);
request try {
.getToken( const res = await fetch("/api/auth/token", {
"mobile", method: "POST",
process.env.NEXT_PUBLIC_CLIENT_ID, headers: { "Content-Type": "application/json" },
process.env.NEXT_PUBLIC_CLIENT_SECRET, body: JSON.stringify({ uuid, code: code.join("") }),
uuid, });
code.join("") const response = await res.json();
) if (response.access_token) {
.then((response) => { handleSetCookie(response);
if (response.access_token) { } else {
handleSetCookie(response);
}
})
.catch(() => {
setLoading(false); setLoading(false);
setIsError(true); setIsError(true);
}); }
} catch {
setLoading(false);
setIsError(true);
}
}; };
const handleSetCookie = (response) => { const handleSetCookie = (response) => {
+3 -2
View File
@@ -37,9 +37,10 @@ services:
# API configuration # API configuration
NEXT_PUBLIC_API_URL: ${NEXT_PUBLIC_API_URL} NEXT_PUBLIC_API_URL: ${NEXT_PUBLIC_API_URL}
NEXT_PUBLIC_CLIENT_ID: ${NEXT_PUBLIC_CLIENT_ID}
NEXT_PUBLIC_CLIENT_SECRET: ${NEXT_PUBLIC_CLIENT_SECRET}
DEV_MODE: ${DEV_MODE:-FALSE} DEV_MODE: ${DEV_MODE:-FALSE}
# Server-only OAuth credentials (not exposed to browser)
CLIENT_ID: ${CLIENT_ID:-${NEXT_PUBLIC_CLIENT_ID}}
CLIENT_SECRET: ${CLIENT_SECRET:-${NEXT_PUBLIC_CLIENT_SECRET}}
# Health check (uses Dockerfile HEALTHCHECK) # Health check (uses Dockerfile HEALTHCHECK)
healthcheck: healthcheck:
+4
View File
@@ -4,6 +4,10 @@ const nextConfig = {
reactStrictMode: true, reactStrictMode: true,
images: { images: {
remotePatterns: [ remotePatterns: [
{
protocol: 'https',
hostname: 'api.clinic-pro.ir',
},
{ {
protocol: 'https', protocol: 'https',
hostname: 'back-dev.clinic-pro.ir', hostname: 'back-dev.clinic-pro.ir',
+6 -4
View File
@@ -34,10 +34,12 @@ api.interceptors.response.use(
return response.data; return response.data;
}, },
(error) => { (error) => {
// if (error.status === 401) { if (error?.response?.status === 401 && typeof window !== "undefined") {
// removeToken(); ["access_token", "refresh_token", "uuid", "userInfo"].forEach((key) => {
// window.location.pathname = "login"; document.cookie = `${key}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
// } });
window.location.href = "/login";
}
return Promise.reject(error); return Promise.reject(error);
} }
); );