Skip to content

Commit

Permalink
m
Browse files Browse the repository at this point in the history
  • Loading branch information
KamyarTaher committed Nov 8, 2024
1 parent 3cb0fc9 commit 408df81
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 26 deletions.
41 changes: 29 additions & 12 deletions src/app/backendAPI/tokenFetch.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,33 @@
export async function fetchToken(reconnect: boolean) {
const response = await fetch(
`https://play.metacube.games/api/set-cookie?reconnect=${reconnect}`,
{
method: "GET",
credentials: "include",
export async function fetchToken(reconnect: boolean): Promise<string> {
try {
const response = await fetch(
`https://play.metacube.games/api/set-cookie?reconnect=${reconnect}`,
{
method: "GET",
credentials: "include", // Ensures cookies are included
}
);

if (!response.ok) {
// Handle specific HTTP error status if needed
throw new Error(
`Failed to set token cookie: ${response.status} ${response.statusText}`
);
}
);

if (!response.ok) {
throw new Error("Failed to set token cookie");
}
// Check if the response contains JSON
let data;
try {
data = await response.json();
} catch (jsonError) {
throw new Error("Failed to parse JSON response");
}

const data = await response.json();
return data.message;
return data.message || "Token cookie set successfully";
} catch (error: any) {
console.error("Error in fetchToken:", error.message);
throw new Error(
error.message || "Unknown error occurred while fetching token"
);
}
}
41 changes: 27 additions & 14 deletions src/pages/api/set-cookie.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// pages/api/set-cookie.ts
// app/pages/api/set-cookie.ts
import type { NextApiRequest, NextApiResponse } from "next";
import axios from "axios";

Expand All @@ -9,34 +9,47 @@ export default async function handler(
res: NextApiResponse
) {
try {
// Define your parameters (assuming `reconnect` is part of req.query)
const reconnect = req?.query?.reconnect || "false"; // Default to 'false' if not provided
// Get reconnect parameter from the request query, default to 'false'
const reconnect = req.query.reconnect?.toString() || "false";

// Make a request to the backend to refresh the token
// Request token from backend
const backendResponse = await axios.get(`${BASE_URL}auth/refresh`, {
params: { reconnect },
withCredentials: true, // Ensures cookies are included in the request if required
});

// Check if the response is successful
// Check if the backend responded successfully
if (backendResponse.status !== 200) {
return res
.status(backendResponse.status)
.json({ error: "Failed to fetch token" });
}

// Extract the token or cookies from the backend response
// Extract the token from the backend response data
const token = backendResponse.data.token;

// Set the token as a cookie in the response
res.setHeader(
"Set-Cookie",
`userToken=${token}; Path=/; HttpOnly; Secure; SameSite=Strict`
);
// Ensure token exists before setting the cookie
if (token) {
// Set the token as a secure, HttpOnly cookie
res.setHeader(
"Set-Cookie",
`userToken=${token}; Path=/; HttpOnly; Secure; SameSite=Lax`
);

res.status(200).json({ message: "Token cookie set successfully" });
} catch (error) {
return res.status(200).json({ message: "Token cookie set successfully" });
} else {
// Handle case where token is missing from backend response
return res.status(500).json({ error: "Token not provided in response" });
}
} catch (error: any) {
// Log and handle errors, check if axios response is available
console.error("Error fetching token from backend:", error);
res.status(500).json({ error: "Internal server error" });

const status = error.response?.status || 500;
const message =
error.response?.data?.error ||
"Internal server error while fetching token";

return res.status(status).json({ error: message });
}
}

0 comments on commit 408df81

Please sign in to comment.