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>
511 lines
17 KiB
JavaScript
511 lines
17 KiB
JavaScript
/**
|
|
* @copyright nhcarrigan
|
|
* @license Naomi's Public License
|
|
* @author Naomi Carrigan
|
|
*
|
|
* Simple local server to authenticate with LinkedIn and obtain a Company Page Access Token.
|
|
* Run with: node linkedinAuth.js
|
|
* Make sure to set LINKEDIN_CLIENT_ID and LINKEDIN_CLIENT_SECRET environment variables.
|
|
*/
|
|
|
|
import http from "http";
|
|
import { URL } from "url";
|
|
|
|
const PORT = 3001; // Different port from Facebook auth server
|
|
const REDIRECT_URI = `http://localhost:${PORT}/callback`;
|
|
|
|
/**
|
|
* Creates the LinkedIn OAuth authorization URL.
|
|
* @param {string} clientId - The LinkedIn Client ID.
|
|
* @returns {string} The authorization URL.
|
|
*/
|
|
const getAuthUrl = (clientId) => {
|
|
const params = new URLSearchParams({
|
|
client_id: clientId,
|
|
redirect_uri: REDIRECT_URI,
|
|
// LinkedIn requires OpenID Connect scopes as base, plus organization permission
|
|
scope: "openid profile email w_organization_social",
|
|
response_type: "code",
|
|
state: "linkedin-auth-state", // CSRF protection
|
|
});
|
|
return `https://www.linkedin.com/oauth/v2/authorization?${params.toString()}`;
|
|
};
|
|
|
|
/**
|
|
* Exchanges an authorization code for an access token.
|
|
* @param {string} code - The authorization code from LinkedIn.
|
|
* @param {string} clientId - The LinkedIn Client ID.
|
|
* @param {string} clientSecret - The LinkedIn Client Secret.
|
|
* @returns {Promise<{access_token: string, expires_in?: number}>} The access token response.
|
|
*/
|
|
const exchangeCodeForToken = async (code, clientId, clientSecret) => {
|
|
const params = new URLSearchParams({
|
|
grant_type: "authorization_code",
|
|
code: code,
|
|
redirect_uri: REDIRECT_URI,
|
|
client_id: clientId,
|
|
client_secret: clientSecret,
|
|
});
|
|
|
|
const response = await fetch("https://www.linkedin.com/oauth/v2/accessToken", {
|
|
body: params.toString(),
|
|
headers: {
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
},
|
|
method: "POST",
|
|
});
|
|
return await response.json();
|
|
};
|
|
|
|
/**
|
|
* Gets the authenticated user's profile information.
|
|
* @param {string} accessToken - The access token.
|
|
* @returns {Promise<object>} The user profile.
|
|
*/
|
|
const getUserProfile = async (accessToken) => {
|
|
const response = await fetch(
|
|
"https://api.linkedin.com/v2/userinfo",
|
|
{
|
|
headers: {
|
|
"Authorization": `Bearer ${accessToken}`,
|
|
},
|
|
},
|
|
);
|
|
return await response.json();
|
|
};
|
|
|
|
/**
|
|
* Gets the organizations/companies the user manages.
|
|
* @param {string} accessToken - The access token.
|
|
* @returns {Promise<Array>} Array of organizations.
|
|
*/
|
|
const getUserOrganizations = async (accessToken) => {
|
|
// First, get the user's profile to get their ID
|
|
const profile = await getUserProfile(accessToken);
|
|
|
|
if (!profile.sub) {
|
|
return [];
|
|
}
|
|
|
|
// Get organizations using the Organization API
|
|
// Note: This requires the organization to be associated with your app
|
|
const response = await fetch(
|
|
`https://api.linkedin.com/v2/organizationalEntityAcls?q=roleAssignee&role=ADMINISTRATOR&state=APPROVED`,
|
|
{
|
|
headers: {
|
|
"Authorization": `Bearer ${accessToken}`,
|
|
},
|
|
},
|
|
);
|
|
|
|
const data = await response.json();
|
|
|
|
if (data.elements && data.elements.length > 0) {
|
|
// Get organization details for each
|
|
const orgDetails = [];
|
|
for (const element of data.elements) {
|
|
const orgId = element.organizationalTarget?.split(":")[1];
|
|
if (orgId) {
|
|
try {
|
|
const orgResponse = await fetch(
|
|
`https://api.linkedin.com/v2/organizations/${orgId}`,
|
|
{
|
|
headers: {
|
|
"Authorization": `Bearer ${accessToken}`,
|
|
},
|
|
},
|
|
);
|
|
const orgData = await orgResponse.json();
|
|
orgDetails.push({
|
|
id: orgId,
|
|
name: orgData.localizedName || orgData.name || `Organization ${orgId}`,
|
|
accessToken: accessToken, // Same token works for organization
|
|
});
|
|
} catch (error) {
|
|
// Skip if we can't get org details
|
|
console.error(`Failed to get org details for ${orgId}:`, error);
|
|
}
|
|
}
|
|
}
|
|
return orgDetails;
|
|
}
|
|
|
|
return [];
|
|
};
|
|
|
|
/**
|
|
* 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);
|
|
};
|
|
|
|
const clientId = process.env.LINKEDIN_CLIENT_ID;
|
|
const clientSecret = process.env.LINKEDIN_CLIENT_SECRET;
|
|
|
|
if (!clientId || !clientSecret) {
|
|
console.error(
|
|
"Error: LINKEDIN_CLIENT_ID and LINKEDIN_CLIENT_SECRET environment variables must be set.",
|
|
);
|
|
console.error(
|
|
"Example: LINKEDIN_CLIENT_ID=your_client_id LINKEDIN_CLIENT_SECRET=your_secret node linkedinAuth.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(clientId);
|
|
const html = `
|
|
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<title>LinkedIn Company 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: #0077b5;
|
|
margin-top: 0;
|
|
}
|
|
.button {
|
|
display: inline-block;
|
|
background: #0077b5;
|
|
color: white;
|
|
padding: 12px 24px;
|
|
text-decoration: none;
|
|
border-radius: 6px;
|
|
font-weight: 600;
|
|
margin-top: 20px;
|
|
}
|
|
.button:hover {
|
|
background: #006399;
|
|
}
|
|
.info {
|
|
background: #e3f2fd;
|
|
padding: 15px;
|
|
border-radius: 6px;
|
|
margin-top: 20px;
|
|
border-left: 4px solid #0077b5;
|
|
}
|
|
.warning {
|
|
background: #fff3e0;
|
|
padding: 15px;
|
|
border-radius: 6px;
|
|
margin-top: 20px;
|
|
border-left: 4px solid #ff9800;
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="container">
|
|
<h1>🔐 LinkedIn Company Page Token Generator</h1>
|
|
<p>Click the button below to authenticate with LinkedIn and get your Company Page Access Token.</p>
|
|
<a href="${authUrl}" class="button">Authenticate with LinkedIn</a>
|
|
<div class="info">
|
|
<strong>Note:</strong> Make sure you're an administrator of the LinkedIn Company Page you want to post to.
|
|
</div>
|
|
<div class="warning">
|
|
<strong>⚠️ Important:</strong> Your LinkedIn app must be associated with the Company Page. This requires:
|
|
<ul>
|
|
<li>The Company Page super admin must approve the app association</li>
|
|
<li>Your app must have "Sign In with LinkedIn using OpenID Connect" enabled in Products</li>
|
|
<li>The w_organization_social permission requires App Review approval</li>
|
|
<li>Business verification may be required</li>
|
|
</ul>
|
|
<p><strong>Note:</strong> If you get an invalid_scope_error, make sure OpenID Connect is enabled in your app settings.</p>
|
|
</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");
|
|
const errorDescription = url.searchParams.get("error_description");
|
|
|
|
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>${errorDescription || ""}</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 access token
|
|
const tokenResponse = await exchangeCodeForToken(code, clientId, clientSecret);
|
|
|
|
if (tokenResponse.error) {
|
|
throw new Error(
|
|
tokenResponse.error_description || tokenResponse.error || "Failed to exchange code for token",
|
|
);
|
|
}
|
|
|
|
const accessToken = tokenResponse.access_token;
|
|
const expiresIn = tokenResponse.expires_in;
|
|
|
|
// Step 2: Get user's organizations
|
|
const organizations = await getUserOrganizations(accessToken);
|
|
|
|
if (organizations.length === 0) {
|
|
return sendHtml(
|
|
res,
|
|
200,
|
|
`
|
|
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<title>No Organizations 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);
|
|
}
|
|
.warning {
|
|
background: #fff3e0;
|
|
padding: 15px;
|
|
border-radius: 6px;
|
|
border-left: 4px solid #ff9800;
|
|
margin-top: 20px;
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="container">
|
|
<h1>⚠️ No Organizations Found</h1>
|
|
<p>You don't have administrator access to any LinkedIn Company Pages, or your app isn't associated with any pages.</p>
|
|
<div class="warning">
|
|
<p><strong>Troubleshooting:</strong></p>
|
|
<ul>
|
|
<li>Make sure you're an administrator of the Company Page</li>
|
|
<li>Ensure your LinkedIn app is associated with the Company Page (requires super admin approval)</li>
|
|
<li>Check that your app has been approved for the w_organization_social permission</li>
|
|
<li>Verify your app is in Live mode if required</li>
|
|
</ul>
|
|
</div>
|
|
<p><a href="/">Try again</a></p>
|
|
</div>
|
|
</body>
|
|
</html>
|
|
`,
|
|
);
|
|
}
|
|
|
|
// Display results
|
|
const orgsHtml = organizations
|
|
.map(
|
|
(org) => `
|
|
<div style="background: #f5f5f5; padding: 15px; margin: 10px 0; border-radius: 6px;">
|
|
<h3>${org.name}</h3>
|
|
<p><strong>Organization ID:</strong> <code>${org.id}</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">${org.accessToken}</textarea>
|
|
<p><strong>Expires in:</strong> ${expiresIn ? `${Math.floor(expiresIn / 86400)} days` : "Check token expiration"}</p>
|
|
</div>
|
|
`,
|
|
)
|
|
.join("");
|
|
|
|
const html = `
|
|
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<title>Success! Your Organization 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 Organization Access Tokens:</strong></p>
|
|
<p>Copy these tokens and add them to your environment variables. Use the Access Token for the organization you want to post to.</p>
|
|
</div>
|
|
${orgsHtml}
|
|
<div class="warning">
|
|
<p><strong>⚠️ Important:</strong></p>
|
|
<ul>
|
|
<li>Store these tokens securely (like your other API credentials)</li>
|
|
<li>LinkedIn access tokens typically expire after 60 days</li>
|
|
<li>Add the token to your environment variables as <code>LINKEDIN_ACCESS_TOKEN</code></li>
|
|
<li>You'll also need the Organization ID as <code>LINKEDIN_ORG_ID</code></li>
|
|
<li>Make sure your app is associated with the Company Page before posting</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🚀 LinkedIn Auth Server running at http://localhost:${PORT}`);
|
|
console.log(`\n📋 Make sure you've set:`);
|
|
console.log(` - LINKEDIN_CLIENT_ID`);
|
|
console.log(` - LINKEDIN_CLIENT_SECRET`);
|
|
console.log(`\n🔗 Open http://localhost:${PORT} in your browser to start!\n`);
|
|
});
|
|
|