Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions bin/setup/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,80 @@ const RULES_MAP = {
}
}

static async enableApiKey(request) {
try {
const { accessToken, org, site, apiKeyId } = await request.json();

if (!accessToken || !org || !site || !apiKeyId) {
return RequestHelper.errorResponse('accessToken, org, site, and apiKeyId are required');
}

const siteConfigEndpoint = `https://admin.hlx.page/config/${org}/sites/${site}.json`;

console.log(`Getting site config from ${siteConfigEndpoint}`);

// First, get the current site configuration
const getResponse = await fetch(siteConfigEndpoint, {
method: 'GET',
headers: {
'x-auth-token': accessToken
}
});

if (!getResponse.ok) {
const errorText = await getResponse.text();
return RequestHelper.errorResponse(`Failed to get site config: ${getResponse.status} ${getResponse.statusText} - ${errorText}`, getResponse.status);
}

const siteConfig = await getResponse.json();

console.log(`Enabling API key ${apiKeyId} for site ${org}/${site}`);

// Manipulate the JSON to add the API key ID
if (!siteConfig.access) {
siteConfig.access = {};
}
if (!siteConfig.access.admin) {
siteConfig.access.admin = {};
}
if (!siteConfig.access.admin.apiKeyId) {
siteConfig.access.admin.apiKeyId = [];
}

// Add the API key ID if it's not already in the array
if (!siteConfig.access.admin.apiKeyId.includes(apiKeyId)) {
siteConfig.access.admin.apiKeyId.push(apiKeyId);
}

// Make the POST request to update the site configuration
const postResponse = await fetch(siteConfigEndpoint, {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we make the post to the /apiKey.json endpoint specifically, which is safer and wouldn't affect other site configs in any way?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We already do that to create the key, but then we need to enable it for operation, and this is done in the site config.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no this is done on the access configuration, you can try /access/admin.json instead to limit the scope of the change.

method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-auth-token': accessToken
},
body: JSON.stringify(siteConfig)
});

if (!postResponse.ok) {
const errorText = await postResponse.text();
return RequestHelper.errorResponse(`Failed to update site config: ${postResponse.status} ${postResponse.statusText} - ${errorText}`, postResponse.status);
}

const result = await postResponse.json();

return RequestHelper.jsonResponse({
success: true,
siteConfig: result,
message: 'API key enabled successfully'
});

} catch (error) {
console.error('Error enabling API key:', error);
return RequestHelper.errorResponse('Failed to enable API key: ' + error.message, 500);
}
}

static async wizardDone(request) {
console.log("Wizard completed, shutting down server.");
setTimeout(() => process.exit(0), 1000); // Delay to allow response to be sent
Expand Down Expand Up @@ -714,6 +788,7 @@ class Server {
.get('/api/git-info', ApiRoutes.getGitInfo)
.post('/api/aio-config', ApiRoutes.aioConfig)
.post('/api/create-api-key', ApiRoutes.createApiKey)
.post('/api/enable-api-key', ApiRoutes.enableApiKey)
.post('/api/external-submit', ApiRoutes.handleExternalSubmission)
.post('/api/change-detector/rule', ApiRoutes.changeDetectorRule)
.post('/api/wizard/done', ApiRoutes.wizardDone)
Expand Down
34 changes: 31 additions & 3 deletions bin/setup/ui/setup-wizard.js
Original file line number Diff line number Diff line change
Expand Up @@ -673,6 +673,7 @@ export class SetupWizard extends LitElement {

this.loading = true;
try {
// Step 1: Create the API key
const apiKeyEndpoint = `https://admin.hlx.page/config/${this.org}/sites/${this.site}/apiKeys.json`;
const body = {
description: `Key used by PDP Prerender components [${this.org}/${this.site}]`,
Expand Down Expand Up @@ -700,19 +701,46 @@ export class SetupWizard extends LitElement {

const result = await response.json();
this.generatedApiKey = result;

console.log(`API key created successfully with ID: ${result.id}`);
this.showToastNotification('API key created successfully! Now enabling it...', 'positive');

// Step 2: Enable the API key by adding it to site configuration
const enableResponse = await fetch('/api/enable-api-key', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
accessToken: this.accessToken,
org: this.org,
site: this.site,
apiKeyId: result.id
})
});

if (!enableResponse.ok) {
const errorText = await enableResponse.text();
this.showToastNotification(`Failed to enable API key: ${enableResponse.status} ${enableResponse.statusText} - ${errorText}`, 'negative');
return false;
}

const enableResult = await enableResponse.json();
console.log('API key enabled successfully');

// Auto-populate the AEM admin token with the generated API key value
this.token = result.value;
// Set org/site for backward compatibility
this.aioOrg = this.org;
this.aioSite = this.site;
// Auto-validate the token
await this.handleTokenChange(this.token);
this.showToastNotification('API key created successfully!', 'positive');
this.showToastNotification('API key created and enabled successfully!', 'positive');
return true;

} catch (error) {
console.error('Error creating API key:', error);
this.showToastNotification('Error creating API key: ' + error.message, 'negative');
console.error('Error creating or enabling API key:', error);
this.showToastNotification('Error creating or enabling API key: ' + error.message, 'negative');
return false;
} finally {
this.loading = false;
Expand Down