generated from nhcarrigan/template
922dee415a
### Explanation Makes my life so much easier. ### Issue _No response_ ### Attestations - [x] I have read and agree to the [Code of Conduct](https://docs.nhcarrigan.com/community/coc/) - [x] I have read and agree to the [Community Guidelines](https://docs.nhcarrigan.com/community/guide/). - [x] My contribution complies with the [Contributor Covenant](https://docs.nhcarrigan.com/dev/covenant/). ### Dependencies - [x] I have pinned the dependencies to a specific patch version. ### Style - [x] I have run the linter and resolved any errors. - [x] My pull request uses an appropriate title, matching the conventional commit standards. - [x] My scope of feat/fix/chore/etc. correctly matches the nature of changes in my pull request. ### Tests - [ ] My contribution adds new code, and I have added tests to cover it. - [ ] My contribution modifies existing code, and I have updated the tests to reflect these changes. - [ ] All new and existing tests pass locally with my changes. - [ ] Code coverage remains at or above the configured threshold. ### Documentation _No response_ ### Versioning Minor - My pull request introduces a new non-breaking feature. Reviewed-on: #8 Co-authored-by: Naomi Carrigan <commits@nhcarrigan.com> Co-committed-by: Naomi Carrigan <commits@nhcarrigan.com>
515 lines
16 KiB
JavaScript
515 lines
16 KiB
JavaScript
/**
|
|
* @copyright nhcarrigan
|
|
* @license Naomi's Public License
|
|
* @author Naomi Carrigan
|
|
*
|
|
* Simple local server to authenticate with Facebook and obtain a Page Access Token.
|
|
* Run with: node facebookAuth.js
|
|
* Make sure to set FACEBOOK_APP_ID and FACEBOOK_APP_SECRET environment variables.
|
|
*/
|
|
|
|
import http from "http";
|
|
import { URL } from "url";
|
|
|
|
const PORT = 3000;
|
|
const REDIRECT_URI = `http://localhost:${PORT}/callback`;
|
|
|
|
/**
|
|
* Creates the Facebook OAuth authorization URL.
|
|
* @param {string} appId - The Facebook App ID.
|
|
* @returns {string} The authorization URL.
|
|
*/
|
|
const getAuthUrl = (appId) => {
|
|
const params = new URLSearchParams({
|
|
client_id: appId,
|
|
redirect_uri: REDIRECT_URI,
|
|
scope: "pages_manage_posts,pages_show_list",
|
|
response_type: "code",
|
|
});
|
|
return `https://www.facebook.com/v21.0/dialog/oauth?${params.toString()}`;
|
|
};
|
|
|
|
/**
|
|
* Exchanges an authorization code for an access token.
|
|
* @param {string} code - The authorization code from Facebook.
|
|
* @param {string} appId - The Facebook App ID.
|
|
* @param {string} appSecret - The Facebook App Secret.
|
|
* @returns {Promise<{access_token: string, expires_in?: number}>} The access token response.
|
|
*/
|
|
const exchangeCodeForToken = async (code, appId, appSecret) => {
|
|
const params = new URLSearchParams({
|
|
client_id: appId,
|
|
client_secret: appSecret,
|
|
redirect_uri: REDIRECT_URI,
|
|
code: code,
|
|
});
|
|
|
|
const response = await fetch(
|
|
`https://graph.facebook.com/v21.0/oauth/access_token?${params.toString()}`,
|
|
);
|
|
return await response.json();
|
|
};
|
|
|
|
/**
|
|
* Exchanges a short-lived token for a long-lived token.
|
|
* @param {string} shortLivedToken - The short-lived access token.
|
|
* @param {string} appId - The Facebook App ID.
|
|
* @param {string} appSecret - The Facebook App Secret.
|
|
* @returns {Promise<{access_token: string, expires_in?: number}>} The long-lived token response.
|
|
*/
|
|
const exchangeForLongLivedToken = async (shortLivedToken, appId, appSecret) => {
|
|
const params = new URLSearchParams({
|
|
grant_type: "fb_exchange_token",
|
|
client_id: appId,
|
|
client_secret: appSecret,
|
|
fb_exchange_token: shortLivedToken,
|
|
});
|
|
|
|
const response = await fetch(
|
|
`https://graph.facebook.com/v21.0/oauth/access_token?${params.toString()}`,
|
|
);
|
|
return await response.json();
|
|
};
|
|
|
|
/**
|
|
* Gets the user's pages.
|
|
* @param {string} accessToken - The user access token.
|
|
* @returns {Promise<Array>} Array of pages the user manages.
|
|
*/
|
|
const getUserPages = async (accessToken) => {
|
|
const response = await fetch(
|
|
`https://graph.facebook.com/v21.0/me/accounts?access_token=${accessToken}`,
|
|
);
|
|
const data = await response.json();
|
|
return data.data || [];
|
|
};
|
|
|
|
/**
|
|
* Gets a Page Access Token for a specific page.
|
|
* @param {string} pageId - The page ID.
|
|
* @param {string} userAccessToken - The user access token.
|
|
* @returns {Promise<string>} The Page Access Token.
|
|
*/
|
|
const getPageAccessToken = async (pageId, userAccessToken) => {
|
|
const response = await fetch(
|
|
`https://graph.facebook.com/v21.0/${pageId}?fields=access_token&access_token=${userAccessToken}`,
|
|
);
|
|
const data = await response.json();
|
|
return data.access_token;
|
|
};
|
|
|
|
/**
|
|
* Exchanges a short-lived Page Access Token for a long-lived one.
|
|
* @param {string} pageAccessToken - The short-lived Page Access Token.
|
|
* @param {string} appId - The Facebook App ID.
|
|
* @param {string} appSecret - The Facebook App Secret.
|
|
* @returns {Promise<{access_token: string, expires_in?: number}>} The long-lived Page Access Token.
|
|
*/
|
|
const exchangePageTokenForLongLived = async (
|
|
pageAccessToken,
|
|
appId,
|
|
appSecret,
|
|
) => {
|
|
const params = new URLSearchParams({
|
|
grant_type: "fb_exchange_token",
|
|
client_id: appId,
|
|
client_secret: appSecret,
|
|
fb_exchange_token: pageAccessToken,
|
|
});
|
|
|
|
const response = await fetch(
|
|
`https://graph.facebook.com/v21.0/oauth/access_token?${params.toString()}`,
|
|
);
|
|
return await response.json();
|
|
};
|
|
|
|
/**
|
|
* Sends an HTML response.
|
|
* @param {http.ServerResponse} res - The HTTP response object.
|
|
* @param {number} statusCode - The HTTP status code.
|
|
* @param {string} html - The HTML content to send.
|
|
*/
|
|
const sendHtml = (res, statusCode, html) => {
|
|
res.writeHead(statusCode, { "Content-Type": "text/html" });
|
|
res.end(html);
|
|
};
|
|
|
|
/**
|
|
* Sends a JSON response.
|
|
* @param {http.ServerResponse} res - The HTTP response object.
|
|
* @param {number} statusCode - The HTTP status code.
|
|
* @param {object} data - The JSON data to send.
|
|
*/
|
|
const sendJson = (res, statusCode, data) => {
|
|
res.writeHead(statusCode, { "Content-Type": "application/json" });
|
|
res.end(JSON.stringify(data, null, 2));
|
|
};
|
|
|
|
const appId = process.env.FACEBOOK_APP_ID;
|
|
const appSecret = process.env.FACEBOOK_APP_SECRET;
|
|
|
|
if (!appId || !appSecret) {
|
|
console.error(
|
|
"Error: FACEBOOK_APP_ID and FACEBOOK_APP_SECRET environment variables must be set.",
|
|
);
|
|
console.error(
|
|
"Example: FACEBOOK_APP_ID=your_app_id FACEBOOK_APP_SECRET=your_secret node facebookAuth.js",
|
|
);
|
|
process.exit(1);
|
|
}
|
|
|
|
const server = http.createServer(async (req, res) => {
|
|
const url = new URL(req.url, `http://localhost:${PORT}`);
|
|
|
|
// Root route - show auth link
|
|
if (url.pathname === "/") {
|
|
const authUrl = getAuthUrl(appId);
|
|
const html = `
|
|
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<title>Facebook Page Token Generator</title>
|
|
<style>
|
|
body {
|
|
font-family: system-ui, -apple-system, sans-serif;
|
|
max-width: 800px;
|
|
margin: 50px auto;
|
|
padding: 20px;
|
|
background: #f5f5f5;
|
|
}
|
|
.container {
|
|
background: white;
|
|
padding: 30px;
|
|
border-radius: 8px;
|
|
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
|
}
|
|
h1 {
|
|
color: #1877f2;
|
|
margin-top: 0;
|
|
}
|
|
.button {
|
|
display: inline-block;
|
|
background: #1877f2;
|
|
color: white;
|
|
padding: 12px 24px;
|
|
text-decoration: none;
|
|
border-radius: 6px;
|
|
font-weight: 600;
|
|
margin-top: 20px;
|
|
}
|
|
.button:hover {
|
|
background: #166fe5;
|
|
}
|
|
.info {
|
|
background: #e3f2fd;
|
|
padding: 15px;
|
|
border-radius: 6px;
|
|
margin-top: 20px;
|
|
border-left: 4px solid #1877f2;
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="container">
|
|
<h1>🔐 Facebook Page Token Generator</h1>
|
|
<p>Click the button below to authenticate with Facebook and get your Page Access Token.</p>
|
|
<a href="${authUrl}" class="button">Authenticate with Facebook</a>
|
|
<div class="info">
|
|
<strong>Note:</strong> Make sure you're an admin of the Facebook Page you want to post to.
|
|
</div>
|
|
</div>
|
|
</body>
|
|
</html>
|
|
`;
|
|
return sendHtml(res, 200, html);
|
|
}
|
|
|
|
// Callback route - handle OAuth callback
|
|
if (url.pathname === "/callback") {
|
|
const code = url.searchParams.get("code");
|
|
const error = url.searchParams.get("error");
|
|
|
|
if (error) {
|
|
const html = `
|
|
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<title>Authentication Error</title>
|
|
<style>
|
|
body {
|
|
font-family: system-ui, -apple-system, sans-serif;
|
|
max-width: 800px;
|
|
margin: 50px auto;
|
|
padding: 20px;
|
|
background: #f5f5f5;
|
|
}
|
|
.container {
|
|
background: white;
|
|
padding: 30px;
|
|
border-radius: 8px;
|
|
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
|
}
|
|
.error {
|
|
color: #d32f2f;
|
|
background: #ffebee;
|
|
padding: 15px;
|
|
border-radius: 6px;
|
|
border-left: 4px solid #d32f2f;
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="container">
|
|
<h1>❌ Authentication Error</h1>
|
|
<div class="error">
|
|
<p><strong>Error:</strong> ${error}</p>
|
|
<p>${url.searchParams.get("error_description") || ""}</p>
|
|
</div>
|
|
<p><a href="/">Try again</a></p>
|
|
</div>
|
|
</body>
|
|
</html>
|
|
`;
|
|
return sendHtml(res, 400, html);
|
|
}
|
|
|
|
if (!code) {
|
|
return sendHtml(
|
|
res,
|
|
400,
|
|
"<h1>Error</h1><p>No authorization code received.</p><a href='/'>Try again</a>",
|
|
);
|
|
}
|
|
|
|
try {
|
|
// Step 1: Exchange code for short-lived user token
|
|
const tokenResponse = await exchangeCodeForToken(code, appId, appSecret);
|
|
|
|
if (tokenResponse.error) {
|
|
throw new Error(
|
|
tokenResponse.error.message || "Failed to exchange code for token",
|
|
);
|
|
}
|
|
|
|
const shortLivedUserToken = tokenResponse.access_token;
|
|
|
|
// Step 2: Exchange for long-lived user token
|
|
const longLivedUserTokenResponse = await exchangeForLongLivedToken(
|
|
shortLivedUserToken,
|
|
appId,
|
|
appSecret,
|
|
);
|
|
|
|
if (longLivedUserTokenResponse.error) {
|
|
throw new Error(
|
|
longLivedUserTokenResponse.error.message ||
|
|
"Failed to exchange for long-lived token",
|
|
);
|
|
}
|
|
|
|
const longLivedUserToken = longLivedUserTokenResponse.access_token;
|
|
|
|
// Step 3: Get user's pages
|
|
const pages = await getUserPages(longLivedUserToken);
|
|
|
|
if (pages.length === 0) {
|
|
return sendHtml(
|
|
res,
|
|
200,
|
|
`
|
|
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<title>No Pages Found</title>
|
|
<style>
|
|
body {
|
|
font-family: system-ui, -apple-system, sans-serif;
|
|
max-width: 800px;
|
|
margin: 50px auto;
|
|
padding: 20px;
|
|
background: #f5f5f5;
|
|
}
|
|
.container {
|
|
background: white;
|
|
padding: 30px;
|
|
border-radius: 8px;
|
|
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="container">
|
|
<h1>⚠️ No Pages Found</h1>
|
|
<p>You don't have access to any Facebook Pages, or you're not an admin of any pages.</p>
|
|
<p><a href="/">Try again</a></p>
|
|
</div>
|
|
</body>
|
|
</html>
|
|
`,
|
|
);
|
|
}
|
|
|
|
// Step 4: Get Page Access Tokens and exchange for long-lived
|
|
const pageTokens = [];
|
|
for (const page of pages) {
|
|
const pageAccessToken = await getPageAccessToken(
|
|
page.id,
|
|
longLivedUserToken,
|
|
);
|
|
const longLivedPageTokenResponse = await exchangePageTokenForLongLived(
|
|
pageAccessToken,
|
|
appId,
|
|
appSecret,
|
|
);
|
|
|
|
if (!longLivedPageTokenResponse.error) {
|
|
pageTokens.push({
|
|
pageId: page.id,
|
|
pageName: page.name,
|
|
accessToken: longLivedPageTokenResponse.access_token,
|
|
expiresIn: longLivedPageTokenResponse.expires_in,
|
|
});
|
|
}
|
|
}
|
|
|
|
// Display results
|
|
const pagesHtml = pageTokens
|
|
.map(
|
|
(pt) => `
|
|
<div style="background: #f5f5f5; padding: 15px; margin: 10px 0; border-radius: 6px;">
|
|
<h3>${pt.pageName}</h3>
|
|
<p><strong>Page ID:</strong> <code>${pt.pageId}</code></p>
|
|
<p><strong>Access Token:</strong></p>
|
|
<textarea readonly style="width: 100%; padding: 10px; font-family: monospace; border: 1px solid #ddd; border-radius: 4px; background: white;" rows="3">${pt.accessToken}</textarea>
|
|
<p><strong>Expires in:</strong> ${pt.expiresIn ? `${Math.floor(pt.expiresIn / 86400)} days` : "Never (as long as admin access is maintained)"}</p>
|
|
</div>
|
|
`,
|
|
)
|
|
.join("");
|
|
|
|
const html = `
|
|
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<title>Success! Your Page Tokens</title>
|
|
<style>
|
|
body {
|
|
font-family: system-ui, -apple-system, sans-serif;
|
|
max-width: 900px;
|
|
margin: 50px auto;
|
|
padding: 20px;
|
|
background: #f5f5f5;
|
|
}
|
|
.container {
|
|
background: white;
|
|
padding: 30px;
|
|
border-radius: 8px;
|
|
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
|
}
|
|
.success {
|
|
background: #e8f5e9;
|
|
padding: 15px;
|
|
border-radius: 6px;
|
|
border-left: 4px solid #4caf50;
|
|
margin-bottom: 20px;
|
|
}
|
|
h1 {
|
|
color: #4caf50;
|
|
margin-top: 0;
|
|
}
|
|
code {
|
|
background: #f5f5f5;
|
|
padding: 2px 6px;
|
|
border-radius: 3px;
|
|
font-family: 'Courier New', monospace;
|
|
}
|
|
.warning {
|
|
background: #fff3e0;
|
|
padding: 15px;
|
|
border-radius: 6px;
|
|
border-left: 4px solid #ff9800;
|
|
margin-top: 20px;
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="container">
|
|
<h1>✅ Success!</h1>
|
|
<div class="success">
|
|
<p><strong>Your Page Access Tokens:</strong></p>
|
|
<p>Copy these tokens and add them to your environment variables. Use the Page Access Token for the page you want to post to.</p>
|
|
</div>
|
|
${pagesHtml}
|
|
<div class="warning">
|
|
<p><strong>⚠️ Important:</strong></p>
|
|
<ul>
|
|
<li>Store these tokens securely (like your other API credentials)</li>
|
|
<li>Page Access Tokens don't expire as long as you remain an admin</li>
|
|
<li>Add the token to your environment variables as <code>FACEBOOK_PAGE_ACCESS_TOKEN</code></li>
|
|
<li>You'll also need the Page ID as <code>FACEBOOK_PAGE_ID</code></li>
|
|
</ul>
|
|
</div>
|
|
<p><a href="/">Start over</a></p>
|
|
</div>
|
|
</body>
|
|
</html>
|
|
`;
|
|
|
|
return sendHtml(res, 200, html);
|
|
} catch (error) {
|
|
const html = `
|
|
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<title>Error</title>
|
|
<style>
|
|
body {
|
|
font-family: system-ui, -apple-system, sans-serif;
|
|
max-width: 800px;
|
|
margin: 50px auto;
|
|
padding: 20px;
|
|
background: #f5f5f5;
|
|
}
|
|
.container {
|
|
background: white;
|
|
padding: 30px;
|
|
border-radius: 8px;
|
|
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
|
}
|
|
.error {
|
|
color: #d32f2f;
|
|
background: #ffebee;
|
|
padding: 15px;
|
|
border-radius: 6px;
|
|
border-left: 4px solid #d32f2f;
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="container">
|
|
<h1>❌ Error</h1>
|
|
<div class="error">
|
|
<p><strong>Error:</strong> ${error.message}</p>
|
|
</div>
|
|
<p><a href="/">Try again</a></p>
|
|
</div>
|
|
</body>
|
|
</html>
|
|
`;
|
|
return sendHtml(res, 500, html);
|
|
}
|
|
}
|
|
|
|
// 404
|
|
sendHtml(res, 404, "<h1>Not Found</h1><p><a href='/'>Go home</a></p>");
|
|
});
|
|
|
|
server.listen(PORT, () => {
|
|
console.log(`\n🚀 Facebook Auth Server running at http://localhost:${PORT}`);
|
|
console.log(`\n📋 Make sure you've set:`);
|
|
console.log(` - FACEBOOK_APP_ID`);
|
|
console.log(` - FACEBOOK_APP_SECRET`);
|
|
console.log(`\n🔗 Open http://localhost:${PORT} in your browser to start!\n`);
|
|
});
|
|
|