Creating an authentication page and implementing its interaction with the backend.

This commit is contained in:
s452624 2024-06-09 18:06:30 +03:00
parent 32c8389ca5
commit 891da27c47
2 changed files with 343 additions and 276 deletions

View File

@ -1,40 +1,109 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<title>PhishGuardian</title> <title>PhishGuardian</title>
<link rel="stylesheet" href="styles.css"> <link rel="stylesheet" href="css/bootstrap.min.css" />
</head> <link
<body> rel="stylesheet"
<h1>PhishGuardian</h1> href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"
<div id="loginSection"> />
<div> <style>
<label>Email:</label> .btn-spacing {
<input type="text" id="email"> margin: 5px;
}
.form-container {
width: 300px;
padding: 20px;
border: 1px solid #ccc;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
background-color: #f9f9f9;
margin: auto;
}
.form-group label {
font-weight: bold;
}
.center-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.password-container {
position: relative;
}
.toggle-password {
position: absolute;
right: 10px;
top: 10px;
cursor: pointer;
}
.error-message {
color: red;
font-size: 12px;
}
</style>
</head>
<body>
<div class="center-container">
<div id="login-section" class="text-center form-container">
<div class="form-group">
<label id="email-label" style="display: none">Email:</label>
<input
type="text"
id="email"
class="form-control"
style="display: none"
/>
<div id="email-error" class="error-message" style="display: none">
Please enter a valid email address.
</div> </div>
<div>
<label>Password:</label>
<input type="password" id="password">
</div> </div>
<button id="loginButton">Log In</button> <div class="form-group password-container" style="display: none">
<label id="password-label" for="password">Password</label>
<div class="input-group">
<input type="password" class="form-control" id="password" />
<button
id="toggle-password"
class="btn btn-outline-secondary"
type="button"
style="display: none"
>
<i class="far fa-eye"></i>
</button>
</div> </div>
<div id="loggedInSection" style="display:none;"> <div id="password-error" class="error-message" style="display: none">
<div id="loggedInInfo"> Password cannot be empty.
Logged in as: <span id="loggedInEmail"></span>
</div> </div>
<button id="logout">Logout</button> <div id="login-error" class="error-message" style="display: none">
<button id="fetchEmails">Fetch Emails</button> Please enter a valid credentials.
</div> </div>
<ul id="emailList"></ul>
<div>
<h2>Email Body</h2>
<textarea id="emailBody" rows="10" cols="50"></textarea>
<button id="classifyEmail">Classify Email</button>
</div> </div>
<div id="result"></div> <div class="form-group">
<div id="actions" style="display:none;"> <label for="email-service">Select email service:</label>
<button id="markSafe">Mark as Safe</button> <select id="email-service" class="form-control">
<button id="deleteEmail">Delete Email</button> <option value="gmail">Gmail</option>
<option value="outlook">Outlook</option>
</select>
</div> </div>
<button id="loginButton" class="btn btn-primary btn-spacing">
Log In
</button>
</div>
<div
id="control-section"
class="text-center form-container"
style="display: none"
>
<button id="check-mail" class="btn btn-success btn-spacing">
Check Mail
</button>
<button id="logout" class="btn btn-danger btn-spacing">Logout</button>
</div>
</div>
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js\node_modules\@popperjs\core\dist\umd\popper.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="popup.js"></script> <script src="popup.js"></script>
</body> </body>
</html> </html>

View File

@ -1,254 +1,252 @@
let classificationResults = {}; // Dictionary to store classification results document.addEventListener("DOMContentLoaded", function () {
const loginButton = document.getElementById("loginButton");
const checkMailButton = document.getElementById("check-mail");
const logoutButton = document.getElementById("logout");
const loginSection = document.getElementById("login-section");
const controlSection = document.getElementById("control-section");
const emailServiceSelect = document.getElementById("email-service");
const emailLabel = document.getElementById("email-label");
const emailInput = document.getElementById("email");
const passwordLabel = document.getElementById("password-label");
const passwordInput = document.getElementById("password");
const togglePasswordButton = document.getElementById("toggle-password");
const emailError = document.getElementById("email-error");
const passwordError = document.getElementById("password-error");
const loginError = document.getElementById("login-error");
const passwordContainer = document.querySelector(".password-container");
document.addEventListener('DOMContentLoaded', () => { emailServiceSelect.addEventListener("change", function () {
loadClassificationResults(); // Load classification results on start if (emailServiceSelect.value === "outlook") {
checkLoginState(); emailLabel.style.display = "block";
emailInput.style.display = "block";
document.getElementById('loginButton').addEventListener('click', () => { passwordContainer.style.display = "block";
const email = document.getElementById('email').value; togglePasswordButton.style.display = "block";
const password = document.getElementById('password').value;
login(email, password);
});
document.getElementById('fetchEmails').addEventListener('click', () => {
fetchEmails();
});
document.getElementById('classifyEmail').addEventListener('click', () => {
const emailBody = document.getElementById('emailBody').value;
const emailId = getCurrentEmailId();
fetch('http://localhost:5000/classify-email', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ body: emailBody })
})
.then(response => response.json())
.then(data => {
classificationResults[emailId] = data.result; // Store the result
saveClassificationResults(); // Save results to chrome storage
updateClassificationResult(emailId); // Update the displayed result
if (data.result === "Suspicious") {
showActions();
} else { } else {
hideActions(); emailLabel.style.display = "none";
} emailInput.style.display = "none";
}) passwordContainer.style.display = "none";
.catch(error => console.error('Error classifying email:', error)); togglePasswordButton.style.display = "none";
}); emailError.style.display = "none";
passwordError.style.display = "none";
document.getElementById('logout').addEventListener('click', () => { loginError.style.display = "none";
chrome.storage.local.remove(['email', 'password', 'classificationResults'], () => {
console.log('Logged out');
clearEmailList(); // Clear the email list
clearCredentials(); // Clear the credentials
showLoginSection();
});
});
document.getElementById('markSafe').addEventListener('click', () => {
const emailId = getCurrentEmailId();
if (emailId) {
markEmailAsSafe(emailId);
} }
}); });
document.getElementById('deleteEmail').addEventListener('click', () => { togglePasswordButton.addEventListener("click", function () {
const emailId = getCurrentEmailId(); const type =
if (emailId) { passwordInput.getAttribute("type") === "password" ? "text" : "password";
deleteEmail(emailId); passwordInput.setAttribute("type", type);
togglePasswordButton.innerHTML =
type === "password"
? '<i class="far fa-eye"></i>'
: '<i class="far fa-eye-slash"></i>';
});
loginButton.addEventListener("click", function () {
const emailService = emailServiceSelect.value;
if (emailService === "outlook") {
const email = emailInput.value;
const password = passwordInput.value;
let valid = true;
// Email validation
if (!email) {
emailError.textContent = "Email cannot be empty.";
emailError.style.display = "block";
valid = false;
} else if (!validateEmail(email)) {
emailError.textContent = "Please enter a valid email address.";
emailError.style.display = "block";
valid = false;
} else {
emailError.style.display = "none";
} }
});
});
function login(email, password) { // Password validation
chrome.storage.local.set({ email: email, password: password }, () => { if (!password) {
console.log('Credentials saved'); passwordError.textContent = "Password cannot be empty.";
showLoggedInSection(email); passwordError.style.display = "block";
}); valid = false;
} } else {
passwordError.style.display = "none";
}
function fetchEmails() { if (!valid) {
chrome.storage.local.get(['email', 'password'], (result) => { return;
if (result.email && result.password) { }
fetch('http://localhost:5000/fetch-emails', {
method: 'POST', // Validate Outlook login
fetch("http://localhost:5000/validate-outlook-login", {
method: "POST",
headers: { headers: {
'Content-Type': 'application/json' "Content-Type": "application/json",
}, },
body: JSON.stringify({ username: result.email, password: result.password }) body: JSON.stringify({ email: email, password: password }),
}) })
.then(response => { .then((response) => response.json())
.then((data) => {
if (data.success) {
loginError.style.display = "none";
saveCredentials(emailService, email, password);
} else {
loginError.textContent = data.error;
loginError.style.display = "block";
}
})
.catch((error) => {
console.error("Error during Outlook login validation:", error);
alert(error);
});
} else {
saveCredentials(emailService);
}
});
function saveCredentials(emailService, email = null, password = null) {
chrome.storage.local.set(
{ emailService: emailService, email: email, password: password },
() => {
if (emailService === "gmail") {
fetch("http://localhost:5000/authorize")
.then((response) => response.json())
.then((data) => {
const authWindow = window.open(
data.url,
"authWindow",
"width=600,height=400"
);
authWindow.onunload = () => {
loginSection.style.display = "none";
controlSection.style.display = "block";
};
})
.catch((error) => {
console.error("Error during authorization request:", error);
alert(
"An error occurred while starting the authorization process"
);
});
} else {
loginSection.style.display = "none";
controlSection.style.display = "block";
}
}
);
}
checkMailButton.addEventListener("click", function () {
chrome.storage.local.get(
["email", "password", "emailService"],
function (result) {
const emailService = result.emailService;
if (emailService === "gmail") {
fetch("http://localhost:5000/check_mail", {
method: "GET",
headers: { "Content-Type": "application/json" },
credentials: "include",
})
.then((response) => response.json())
.then((data) => {
console.log("Check mail response:", data);
chrome.runtime.sendMessage({
type: "phishing-detected",
emails: data,
});
})
.catch((error) => {
console.error("Error during check mail request:", error);
alert("An error occurred while checking mail");
});
} else {
fetch("http://localhost:5000/fetch-emails", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
username: result.email,
password: result.password,
}),
})
.then((response) => response.json())
.then((data) => {
console.log("Check mail response:", data);
chrome.runtime.sendMessage({
type: "phishing-detected",
emails: data,
});
})
.catch((error) => {
console.error("Error during check mail request:", error);
alert("An error occurred while checking mail");
});
}
}
);
});
logoutButton.addEventListener("click", function () {
fetch("http://localhost:5000/logout", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
})
.then((response) => response.json())
.then((data) => {
alert(data.message);
if (data.message === "Logged out") {
chrome.storage.local.remove(
["email", "password", "emailService"],
function () {
loginSection.style.display = "block";
controlSection.style.display = "none";
}
);
}
})
.catch((error) => {
console.error("Error during logout request:", error);
alert("An error occurred while logging out");
});
});
function checkAuthStatus() {
fetch("http://localhost:5000/check_auth_status", { credentials: "include" })
.then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Login failed. Check your email and password.'); throw new Error("Network response was not ok " + response.statusText);
} }
return response.json(); return response.json();
}) })
.then(data => { .then((data) => {
updateEmailList(data); if (data.logged_in) {
}) chrome.storage.local.get(
.catch(error => console.error('Error fetching emails:', error)); ["email", "emailService"],
function (result) {
showLoggedInSection(result.email, result.emailService);
}
);
} else { } else {
alert("Login credentials not found."); loginSection.style.display = "block";
controlSection.style.display = "none";
} }
});
}
function checkLoginState() {
chrome.storage.local.get(['email', 'password'], (result) => {
if (result.email && result.password) {
showLoggedInSection(result.email);
} else {
showLoginSection();
}
});
}
function showLoginSection() {
document.getElementById('loginSection').style.display = 'block';
document.getElementById('loggedInSection').style.display = 'none';
document.getElementById('loggedInEmail').textContent = '';
document.getElementById('actions').style.display = 'none';
clearEmailList(); // Clear the email list when showing the login section
}
function showLoggedInSection(email) {
document.getElementById('loginSection').style.display = 'none';
document.getElementById('loggedInSection').style.display = 'block';
document.getElementById('loggedInEmail').textContent = email;
}
function showActions() {
document.getElementById('actions').style.display = 'block';
}
function hideActions() {
document.getElementById('actions').style.display = 'none';
}
function getCurrentEmailId() {
return document.getElementById('emailBody').dataset.emailId;
}
function markEmailAsSafe(emailId) {
fetch('http://localhost:5000/mark-safe', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ email_id: emailId })
}) })
.then(response => response.json()) .catch((error) => {
.then(data => { console.error("Error checking auth status:", error);
classificationResults[emailId] = "Not suspicious (marked safe by user)"; // Update the classification result
saveClassificationResults(); // Save results to chrome storage
updateClassificationResult(emailId); // Update the displayed result
hideActions(); // Hide actions since it's now marked as safe
})
.catch(error => console.error('Error marking email as safe:', error));
}
function deleteEmail(emailId) {
chrome.storage.local.get(['email', 'password'], (result) => {
if (result.email && result.password) {
fetch('http://localhost:5000/delete-email', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ email_id: emailId, username: result.email, password: result.password })
})
.then(response => response.json())
.then(data => {
alert(data.message);
removeEmailFromList(emailId); // Update the list and reindex
})
.catch(error => console.error('Error deleting email:', error));
} else {
alert("Login credentials not found.");
}
}); });
}
function removeEmailFromList(emailId) {
const emailList = document.getElementById('emailList');
const emailItems = emailList.getElementsByTagName('li');
for (let i = 0; i < emailItems.length; i++) {
if (emailItems[i].dataset.emailId === emailId) {
emailList.removeChild(emailItems[i]);
break;
} }
function showLoggedInSection(email, emailService) {
const isGmail = emailService === "gmail";
loginSection.style.display = "none";
controlSection.style.display = "block";
checkMailButton.textContent = isGmail ? "Check Gmail" : "Check Outlook";
} }
// Reindex the remaining emails
reindexEmailList();
document.getElementById('emailBody').value = ''; // Clear email body display
document.getElementById('result').textContent = ''; // Clear classification result message
hideActions(); // Hide actions
}
function reindexEmailList() { function validateEmail(email) {
const emailList = document.getElementById('emailList'); const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const emailItems = emailList.getElementsByTagName('li'); return re.test(email);
for (let i = 0; i < emailItems.length; i++) {
emailItems[i].textContent = `${i + 1}: ${emailItems[i].textContent.split(': ')[1]}`;
} }
}
function updateClassificationResult(emailId) { checkAuthStatus();
const resultDiv = document.getElementById('result'); });
if (classificationResults[emailId]) {
resultDiv.textContent = `This email is: ${classificationResults[emailId]}`;
if (classificationResults[emailId] === "Suspicious") {
showActions();
} else {
hideActions();
}
} else {
resultDiv.textContent = ''; // Clear message if not classified
hideActions();
}
}
function saveClassificationResults() {
chrome.storage.local.set({ classificationResults: classificationResults }, () => {
console.log('Classification results saved');
});
}
function loadClassificationResults() {
chrome.storage.local.get(['classificationResults'], (result) => {
if (result.classificationResults) {
classificationResults = result.classificationResults;
}
});
}
function clearEmailList() {
document.getElementById('emailList').innerHTML = ''; // Clear the email list
document.getElementById('emailBody').value = ''; // Clear email body display
document.getElementById('result').textContent = ''; // Clear classification result message
}
function clearCredentials() {
document.getElementById('email').value = ''; // Clear email input field
document.getElementById('password').value = ''; // Clear password input field
}
function updateEmailList(emails) {
const emailList = document.getElementById('emailList');
emailList.innerHTML = '';
emails.forEach((email, index) => {
const li = document.createElement('li');
li.textContent = `${index + 1}: ${email.subject} (from ${email.name} <${email.email_address}>)`;
li.dataset.emailId = email.id; // Assuming email objects have an id property
li.addEventListener('click', () => {
document.getElementById('emailBody').value = email.body;
document.getElementById('emailBody').dataset.emailId = email.id; // Store the email ID
updateClassificationResult(email.id); // Update the displayed result
});
emailList.appendChild(li);
});
}