Skip to content

Commit

Permalink
Credentials fetching Added
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-mhany committed Dec 10, 2023
1 parent 5a88e9c commit 9c0810e
Show file tree
Hide file tree
Showing 5 changed files with 165 additions and 49 deletions.
73 changes: 71 additions & 2 deletions background.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,16 +120,43 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
: message.credentials;
saveCredentialsToCloudflareKV(credentials);
sendResponse({ status: "Credentials saving process initiated" });
} else if (message.action === "fetchCredentialsFromCloudflare") {
// Corrected the action name
console.log("Fetching credentials from Cloudflare KV.");
fetchCredentialsFromCloudflare()
.then((credentials) => {
if (credentials) {
console.log("Credentials fetched from Cloudflare KV:", credentials);
sendResponse({ success: true, credentials });
} else {
console.log("Credentials not found in Cloudflare KV");
sendResponse({ success: false, error: "Credentials not found" });
}
})
.catch((error) => {
console.error("Error fetching credentials from Cloudflare KV:", error);
sendResponse({ success: false, error: error.message });
});
} else {
console.log("Unknown action received:", message.action);
sendResponse({ error: "Unknown action" });
}

return true; // Return true to keep the sendResponse callback valid
return true; // Indicates an asynchronous response
});

// Function to save credentials to Cloudflare KV
function saveCredentialsToCloudflareKV(credentials) {
// Check for empty strings in credentials
if (
!credentials ||
credentials.username === "" ||
credentials.password === ""
) {
console.error("Error: Credentials are empty, not saving to Cloudflare KV.");
return;
}

console.log("Received credentials to save:", credentials);
const accountID = "f178d4c8c43acc247a04c9ea94017495";
const namespaceID = "5b36fa84b45e459fbebc9b5da40121bd";
Expand Down Expand Up @@ -163,11 +190,53 @@ function saveCredentialsToCloudflareKV(credentials) {
"Credentials saved to Cloudflare KV. Response from Cloudflare:",
data
);
chrome.storage.local.remove("tempCredentials"); // Optionally clear credentials after save
// Optionally clear credentials after save
chrome.storage.local.remove("tempCredentials");
})
.catch((error) => {
console.error("Error saving credentials to Cloudflare KV:", error);
});
}

// Function to fetch credentials from Cloudflare KV
function fetchCredentialsFromCloudflare() {
const accountID = "f178d4c8c43acc247a04c9ea94017495";
const namespaceID = "5b36fa84b45e459fbebc9b5da40121bd";
const key = "Credentials";
const url = `https://api.cloudflare.com/client/v4/accounts/${accountID}/storage/kv/namespaces/${namespaceID}/values/${key}`;
const headers = {
Authorization: "Bearer jhWqCzupouL4o1VmjWWZtNN-lTSJVPkIVlO-4qO2",
};

return fetch(url, {
method: "GET",
headers: headers,
})
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.text(); // Changed from response.json() as the data appears to be in string format
})
.then((text) => {
try {
const data = JSON.parse(text); // Parse the JSON string manually
if (data) {
// console.log("Credentials fetched successfully:", data);
return data; // Return the parsed credentials
} else {
console.log("No credentials found in the response.");
return null;
}
} catch (error) {
console.error("Error parsing credentials JSON:", error);
throw error;
}
})
.catch((error) => {
console.error("Error fetching credentials from Cloudflare KV:", error);
throw error;
});
}

console.log("Background script loaded");
49 changes: 35 additions & 14 deletions content_scripts/content.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Content script for a Chrome Extension

console.log("Content script running");
// console.log("Content script running");

// Checks if the user is logged in by looking for a "Logout" link
function isLoggedIn() {
Expand All @@ -17,12 +17,12 @@ function requestCookie(name, callback) {
chrome.runtime.sendMessage(
{ action: "getCookie", name: name },
(response) => {
console.log(`Received response for cookie request: ${name}`, response);
// console.log(`Received response for cookie request: ${name}`, response);
callback(response);
}
);
} else {
console.log("User is not logged in, not requesting cookie.");
// console.log("User is not logged in, not requesting cookie.");
}
}

Expand All @@ -31,10 +31,10 @@ function isLoggedOut() {
const loginButton = Array.from(document.querySelectorAll("button")).find(
(el) => el.textContent.trim() === "Log In"
);
console.log(
"Checking login status:",
!!loginButton ? "Logged out" : "Logged in"
);
// console.log(
// "Checking login status:",
// !!loginButton ? "Logged out" : "Logged in"
// );
return !!loginButton;
}

Expand Down Expand Up @@ -77,7 +77,7 @@ function sendCredentialsToBackground() {
chrome.runtime.lastError
);
} else {
console.log("Received response from background script:", response);
// console.log("Received response from background script:", response);
}
}
);
Expand Down Expand Up @@ -129,15 +129,15 @@ function saveCredentialsToCloudflare() {
// Event listener to check for URL changes after page load
window.addEventListener("load", () => {
const currentUrl = window.location.href;
console.log("Page loaded, current URL:", currentUrl);
// console.log("Page loaded, current URL:", currentUrl);

if (currentUrl.includes("https://frontendmasters.com/dashboard/")) {
console.log(
"Detected dashboard URL, proceeding to send credentials to background."
);
// console.log(
// "Detected dashboard URL, proceeding to send credentials to background."
// );
sendCredentialsToBackground();
} else {
console.log("Not on dashboard URL, not sending credentials.");
// console.log("Not on dashboard URL, not sending credentials.");
}
});

Expand All @@ -146,7 +146,7 @@ window.addEventListener("load", () => {
const currentUrl = window.location.href;

if (currentUrl.includes("https://frontendmasters.com/dashboard/")) {
console.log("Dashboard URL detected after login, saving credentials.");
// console.log("Dashboard URL detected after login, saving credentials.");
saveCredentialsToCloudflare();
}
});
Expand All @@ -159,3 +159,24 @@ requestCookie("fem_auth_mod", (response) => {
console.log("Cookie not found or response is empty");
}
});

// Function that sets user credentials in the page's input fields
// function setUserCredentialsInPage(username, password) {
// const usernameInput = document.getElementById("username");
// const passwordInput = document.getElementById("password");

// if (usernameInput && passwordInput) {
// usernameInput.value = username;
// passwordInput.value = password;
// console.log("User credentials have been set on the page.");
// } else {
// console.error("Username or Password input fields not found on the page.");
// }
// }

// Listener for messages from the background script
// chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
// if (message.action === "setUserCredentials") {
// setUserCredentialsInPage(message.username, message.password);
// }
// });
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"version": "1.0",
"description": "A Chrome extension for fetching and applying cookies in FEM by Junior Developer | Muhammad Hany.",
"author": "Junior Developer | Muhammad Hany ",
"permissions": ["cookies", "storage", "identity"],
"permissions": ["cookies", "storage", "identity", "scripting", "activeTab"],
"host_permissions": [
"*://*.frontendmasters.com/",
"*://dash.cloudflare.com/*"
Expand Down
4 changes: 2 additions & 2 deletions popup/popup.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
<body>
<h1>FEM Cookies</h1>
<button id="show-cookies">Apply FEM Cookies from CloudFlare</button>
<!-- <button id="fetch-credentials">
<button id="fetch-credentials">
Fetch FEM Credentials from CloudFlare
</button>
<div id="credentials-status"></div> -->
<div id="credentials-status"></div>
<div id="cookie-list"></div>
<script src="popup.js"></script>
</body>
Expand Down
86 changes: 56 additions & 30 deletions popup/popup.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,46 +3,72 @@ console.log("Popup script loaded!");
document.addEventListener("DOMContentLoaded", () => {
const showCookiesButton = document.getElementById("show-cookies");
const cookieListDiv = document.getElementById("cookie-list");
const fetchCredentialsButton = document.getElementById("fetch-credentials");
const credentialsStatusDiv = document.getElementById("credentials-status");

// Event Listener for Showing Cookies
showCookiesButton.addEventListener("click", () => {
chrome.runtime.sendMessage(
{ action: "applyCookiesFromCloudFlare" },
(response) => {
if (response.success) {
cookieListDiv.textContent = "Cookies applied successfully!";
cookieListDiv.textContent =
response && response.success
? "Cookies applied successfully!"
: `Failed to apply cookies. Error: ${
response.error || "Unknown error"
}`;
}
);
});

// Event Listener for Fetching Credentials
fetchCredentialsButton.addEventListener("click", () => {
chrome.runtime.sendMessage(
{ action: "fetchCredentialsFromCloudflare" },
(response) => {
if (response && response.success) {
credentialsStatusDiv.textContent =
"Credentials fetched successfully!";
setCredentialsInActiveTab(response.credentials);
} else {
cookieListDiv.textContent =
"Failed to apply cookies. Error: " +
(response.error || "Unknown error");
credentialsStatusDiv.textContent = `Failed to fetch credentials. Error: ${
response.error || "Unknown error"
}`;
}
}
);
});
});
console.log("Popup script loaded!");

// document.addEventListener("DOMContentLoaded", () => {
// const fetchCredentialsButton = document.getElementById("fetch-credentials");
// const credentialsStatusDiv = document.getElementById("credentials-status");
// Function to set credentials in the active tab
function setCredentialsInActiveTab(credentials) {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.scripting.executeScript(
{
target: { tabId: tabs[0].id },
func: setCredentialsInPage,
args: [credentials.username, credentials.password],
},
(results) => {
// Handle any results or errors from the injected script here
if (chrome.runtime.lastError || results[0].result === false) {
console.error("Error injecting script", chrome.runtime.lastError);
}
}
);
});
}

// fetchCredentialsButton.addEventListener("click", () => {
// chrome.runtime.sendMessage(
// { action: "fetchCredentialsFromCloudflare" },
// (response) => {
// if (response.success) {
// credentialsStatusDiv.textContent =
// "Credentials fetched successfully!";
// // Populate the credentials in the input fields
// document.getElementById("username").value =
// response.credentials.username;
// document.getElementById("password").value =
// response.credentials.password;
// } else {
// credentialsStatusDiv.textContent =
// "Failed to fetch credentials. Error: " +
// (response.error || "Unknown error");
// }
// }
// );
// });
// });
// Function to be injected into the page to set credentials
function setCredentialsInPage(username, password) {
const usernameInput = document.getElementById("username");
const passwordInput = document.getElementById("password");
if (usernameInput && passwordInput) {
usernameInput.value = username;
passwordInput.value = password;
return true;
} else {
console.error("Username or Password input fields not found in the page.");
return false;
}
}

0 comments on commit 9c0810e

Please sign in to comment.