membros-react-sdk
Version:
React authentication library for Membros platform with subscription management and plan-based access control
122 lines • 5.92 kB
JavaScript
;
"use client";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MembrosAuthButton = exports.useAuthButton = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const cookies_1 = require("./utils/cookies.cjs");
const AuthContext_1 = require("./AuthContext.cjs");
const constants_1 = require("./constants.cjs");
// Hook for auth functionality
const useAuthButton = (onAuthSuccess, redirectMode = "popup") => {
const { loadUserByToken, publicKey } = (0, AuthContext_1.useAuth)();
const fetchToken = async (authorizationCode, useToast) => {
try {
const res = await fetch(`${constants_1.MEMBROS_API_URL}/user/auth/token`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ authorization_code: authorizationCode }),
});
const responseData = await res.json();
if (res.ok && responseData.access_token) {
// Store tokens in cookies
(0, cookies_1.setCookie)(null, "nextauth.token", responseData.access_token, {
path: "/",
});
(0, cookies_1.setCookie)(null, "nextauth.refreshToken", responseData.refresh_token, {
path: "/",
});
await loadUserByToken(responseData.access_token);
// Optionally call a callback with the access token
if (onAuthSuccess)
onAuthSuccess(responseData.access_token);
if (useToast) {
useToast({
title: "Authentication Successful",
description: "Access token received.",
});
}
}
else {
if (useToast) {
useToast({
title: "Error",
description: responseData.message || "Failed to retrieve token.",
status: "error",
});
}
}
}
catch (error) {
console.error("Error fetching token:", error);
if (useToast) {
useToast({
title: "Server Error",
description: "An error occurred while fetching the token.",
status: "error",
});
}
}
};
// Check for auth code in URL on component mount (for redirect mode)
(0, react_1.useEffect)(() => {
if (redirectMode === "redirect") {
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
if (code) {
fetchToken(code);
// Clean up URL
const newUrl = window.location.pathname;
window.history.replaceState({}, document.title, newUrl);
}
}
}, [redirectMode]);
const handleLogin = (useToast) => {
if (redirectMode === "redirect") {
// Full page redirect using OAuth2 page
const redirectUri = encodeURIComponent(window.location.href);
const authUrl = `${constants_1.MEMBROS_ID_URL}/oauth2/${publicKey}?flow=redirect&redirect_uri=${redirectUri}`;
window.location.href = authUrl;
}
else {
// Popup window (default behavior)
const width = 500;
const height = 550;
const left = window.screen.width / 2 - width / 2;
const top = window.screen.height / 2 - height / 2;
const specs = `width=${width},height=${height},top=${top},left=${left},menubar=no,toolbar=no,location=no,status=no`;
const redirectOrigin = encodeURIComponent(window.location.origin);
const authUrl = `${constants_1.MEMBROS_ID_URL}/oauth2/${publicKey}?flow=popup&redirect_origin=${redirectOrigin}`;
const authWindow = window.open(authUrl, "_blank", specs);
const handleAuthCodeFromMessage = (event) => {
// Allow localhost for debugging
console.log("Received message from origin:", event.origin);
console.log("Message data:", event.data);
if (event.origin !== constants_1.MEMBROS_ID_URL) {
console.error("Invalid origin for OAuth response:", event.origin);
return;
}
if (event.data.type === "oauth" && event.data.code) {
const authorizationCode = event.data.code;
// Fetch the token using the authorization code
fetchToken(authorizationCode, useToast);
if (authWindow) {
authWindow.close();
}
window.removeEventListener("message", handleAuthCodeFromMessage);
}
};
// Listen for messages from the popup
window.addEventListener("message", handleAuthCodeFromMessage);
}
};
return { handleLogin, fetchToken };
};
exports.useAuthButton = useAuthButton;
// Default button component
const MembrosAuthButton = ({ onAuthSuccess, className = "", children, useToast, redirectMode = "popup" }) => {
const { handleLogin } = (0, exports.useAuthButton)(onAuthSuccess, redirectMode);
return ((0, jsx_runtime_1.jsx)("button", { className: `border w-full items-center flex bg-[#1F54B3] flex-row min-h-[50px] justify-center rounded-lg px-[20px] ${className}`, onClick: () => handleLogin(useToast), children: children || ((0, jsx_runtime_1.jsx)("div", { className: "text-white text-md xl:text-md font-medium", children: "Entrar com a Membros" })) }));
};
exports.MembrosAuthButton = MembrosAuthButton;
//# sourceMappingURL=AuthButton.js.map