Skip to content

Commit

Permalink
Merge pull request #48 from remote007/backend
Browse files Browse the repository at this point in the history
auth role
  • Loading branch information
remote007 authored Jan 19, 2025
2 parents 1f2f1b7 + 169ea1f commit 5777935
Show file tree
Hide file tree
Showing 5 changed files with 186 additions and 171 deletions.
10 changes: 7 additions & 3 deletions login.html
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,21 @@
<div id="login-section" class="auth-section">
<h2>Login</h2>
<form id="login-form">
<input type="text" id="login-username" class="input_class" placeholder="Username" required>
<input type="password" id="login-password" class="input_class" placeholder="Password" required>
<div id="admin-extra-fields" style="display: none;">
<input type="text" id="login-empid" placeholder="Employee ID">
<input type="text" id="login-empid" placeholder="Employee ID" required>
</div>
<div id="customer-extra-fields" style="display: none;">
<input type="email" id="login-email" class="input_class" placeholder="Email" required>
</div>
<input type="password" id="login-password" class="input_class" placeholder="Password" required>
<button type="submit" class="btn">Login</button>
</form>
<p class="switch-text">
Don't have an account? <span id="show-signup" class="switch-link">Signup</span>
</p>
</div>


<div id="signup-section" class="auth-section" style="display: none;">
<h2>Sign Up</h2>
<form id="signup-form">
Expand Down
105 changes: 82 additions & 23 deletions scripts/auth.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,92 @@
const API_URL = "https://casserolecoserver.glitch.me/users";

export const auth = {
async login(username, password, authType, empid = '') {
const response = await fetch(`${API_URL}/${authType}`);
const users = await response.json();

const user = users.find(
(u) => u.username === username && u.password === password && (authType !== 'admin' || u.empid === empid)
);

if (user) {
sessionStorage.setItem('user', JSON.stringify(user));
return user;
} else {
throw new Error("Invalid credentials.");
// Login function for admin or customer
async login(identifier, password, authType) {
try {
// Fetch users based on authType (admin or customer)
const response = await fetch(`${API_URL}`);
const data = await response.json();

const users = data[0][authType]; // Choose the correct array based on authType

// For admin: Find by empid
if (authType === 'admin') {
const admin = users.find((u) => u.empid === identifier);

if (!admin) {
throw new Error("Employee ID not found.");
}

if (admin.password !== password) {
throw new Error("Incorrect password.");
}

// Set the admin in sessionStorage
sessionStorage.setItem('user', JSON.stringify(admin));
return admin;
}

// For customer: Find by email
if (authType === 'customer') {
const customer = users.find((u) => u.email === identifier);

if (!customer) {
throw new Error("Email not found.");
}

if (customer.password !== password) {
throw new Error("Incorrect password.");
}

// Set the customer in sessionStorage
sessionStorage.setItem('user', JSON.stringify(customer));
return customer;
}

throw new Error("Invalid auth type.");
} catch (error) {
console.error('Login error:', error);
throw new Error(error.message || 'Login failed.');
}
},

// Signup function for admin or customer
async signup(data, authType) {
const response = await fetch(`${API_URL}/${authType}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});

if (response.ok) {
return response.json();
} else {
throw new Error("Signup failed.");
try {
const response = await fetch(`${API_URL}`);
const dataFromDB = await response.json();

const users = dataFromDB[0][authType]; // Array containing admin or customer users

if (authType === 'admin') {
const adminExists = users.find((u) => u.empid === data.empid);
if (adminExists) {
throw new Error("Admin with this Employee ID already exists.");
}
users.push(data); // Add new admin to the admin array
} else if (authType === 'customer') {
const customerExists = users.find((u) => u.email === data.email);
if (customerExists) {
throw new Error("Customer with this email already exists.");
}
users.push(data); // Add new customer to the customer array
}

const responseUpdate = await fetch(`${API_URL}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(dataFromDB), // Update the whole users object
});

if (responseUpdate.ok) {
return responseUpdate.json();
} else {
throw new Error('Signup failed.');
}
} catch (error) {
console.error('Signup error:', error);
throw new Error('Signup failed.');
}
},

Expand Down
193 changes: 69 additions & 124 deletions scripts/modal.js
Original file line number Diff line number Diff line change
@@ -1,123 +1,4 @@
// import { auth } from './auth.js';

// document.addEventListener('DOMContentLoaded', async () => {
// const modal = document.getElementById('auth-modal');
// const closeModal = document.querySelector('.close-modal');
// const loginForm = document.getElementById('login-form');
// const signupForm = document.getElementById('signup-form');
// const loginSection = document.getElementById('login-section');
// const signupSection = document.getElementById('signup-section');
// const showSignup = document.getElementById('show-signup');
// const showLogin = document.getElementById('show-login');

// // Additional fields for admin and customer
// const loginEmpId = document.getElementById('login-empid');
// const signupEmail = document.getElementById('signup-email');
// const signupAddress = document.getElementById('signup-address');
// const signupPhone = document.getElementById('signup-phone');
// const signupEmpId = document.getElementById('signup-empid');

// // Get authType from the URL
// const authType = new URLSearchParams(window.location.search).get('authType');
// sessionStorage.setItem('authType', authType);

// if (modal) {
// if (await auth.isLoggedIn()) {
// alert("Already Logged In");
// window.location.href = "index.html";
// return;
// }

// // Configure fields and sections based on authType
// const configureFields = () => {
// if (authType === 'admin') {
// // Show admin-specific fields
// loginEmpId.style.display = 'block';
// signupEmpId.style.display = 'block';

// // Hide customer-specific fields
// signupEmail.style.display = 'none';
// signupAddress.style.display = 'none';
// signupPhone.style.display = 'none';
// } else if (authType === 'customer') {
// // Hide admin-specific fields
// loginEmpId.style.display = 'none';
// signupEmpId.style.display = 'none';

// // Show customer-specific fields
// signupEmail.style.display = 'block';
// signupAddress.style.display = 'block';
// signupPhone.style.display = 'block';
// }
// };

// const openModal = () => {
// modal.style.display = 'flex';
// document.body.classList.add('modal-open');
// configureFields(); // Configure fields based on authType
// };

// const closeAndRedirect = () => {
// modal.style.display = 'none';
// document.body.classList.remove('modal-open');
// window.location.href = 'index.html';
// };

// openModal();
// closeModal.addEventListener('click', closeAndRedirect);

// // Switch between login and signup
// showSignup.addEventListener('click', () => {
// loginSection.style.display = 'none';
// signupSection.style.display = 'block';
// });

// showLogin.addEventListener('click', () => {
// signupSection.style.display = 'none';
// loginSection.style.display = 'block';
// });

// // Handle login form submission
// loginForm.addEventListener('submit', async (e) => {
// e.preventDefault();
// const username = document.getElementById('login-username').value;
// const password = document.getElementById('login-password').value;
// const empId = loginEmpId.value; // Optional for admin

// try {
// const user = await auth.login(username, password, authType, empId);
// alert(`Welcome back, ${user.username}!`);
// closeAndRedirect();
// } catch (error) {
// alert(error.message);
// }
// });

// // Handle signup form submission
// signupForm.addEventListener('submit', async (e) => {
// e.preventDefault();
// const username = document.getElementById('signup-username').value;
// const password = document.getElementById('signup-password').value;
// const email = signupEmail.value;
// const address = signupAddress.value;
// const phone = signupPhone.value;
// const empId = signupEmpId.value; // Optional for admin

// const data =
// authType === 'admin'
// ? { username, password, empId }
// : { username, password, email, address, phone };

// try {
// await auth.signup(data, authType);
// alert(`Account created for ${username}!`);
// closeAndRedirect();
// } catch (error) {
// alert(error.message);
// }
// });
// }
// });
import { auth } from './auth.js';

document.addEventListener('DOMContentLoaded', () => {
const modal = document.getElementById('auth-modal');
Expand All @@ -126,27 +7,46 @@ document.addEventListener('DOMContentLoaded', () => {
const signupSection = document.getElementById('signup-section');
const showSignup = document.getElementById('show-signup');
const showLogin = document.getElementById('show-login');
const loginForm = document.getElementById('login-form');
const signupForm = document.getElementById('signup-form');

// Check if user is already logged in
if (sessionStorage.getItem("user") != null) {
alert("Already Logged In");
window.location.href = "index.html";
return;
}

// AuthType logic
// Get authType from URL or sessionStorage, and set it in sessionStorage
const authType = new URLSearchParams(window.location.search).get('authType') || sessionStorage.getItem('authType');
sessionStorage.setItem('authType', authType);

// Adjust modal fields based on authType
// Elements for the extra fields (admin or customer)
const adminExtraFields = document.getElementById('admin-extra-fields');
const customerExtraFields = document.getElementById('customer-extra-fields');
const adminExtraSignupFields = document.getElementById('admin-extra-signup-fields');

// Adjust modal fields based on authType
if (authType === 'admin') {
adminExtraFields.style.display = 'block';
adminExtraSignupFields.style.display = 'block';
const email = document.getElementById("login-email");
email.removeAttribute('required');
email.style.display = 'none';
email.classList.remove('input_class');
customerExtraFields.style.display = 'none';
} else if (authType === 'customer') {
customerExtraFields.style.display = 'block';
const empid = document.getElementById('login-empid');
empid.removeAttribute('required');
empid.style.display = 'none';
empid.classList.remove('input_class');
adminExtraFields.style.display = 'none';
adminExtraSignupFields.style.display = 'none';
adminExtraSignupFields.removeAttribute('required');
}

// Open modal
// Open the modal
modal.style.display = 'flex';
document.body.classList.add('modal-open');

Expand All @@ -157,7 +57,7 @@ document.addEventListener('DOMContentLoaded', () => {
window.location.href = 'index.html';
});

// Switch between Login and Signup
// Switch between Login and Signup sections
showSignup.addEventListener('click', () => {
loginSection.style.display = 'none';
signupSection.style.display = 'block';
Expand All @@ -167,4 +67,49 @@ document.addEventListener('DOMContentLoaded', () => {
signupSection.style.display = 'none';
loginSection.style.display = 'block';
});

// Handle login form submission
loginForm.addEventListener('submit', async (e) => {
e.preventDefault();
const identifier = authType === 'admin'
? document.getElementById('login-empid').value
: document.getElementById('login-email').value;
const password = document.getElementById('login-password').value;

try {
const user = await auth.login(identifier, password, authType);
alert(`Welcome back, ${user.username}!`);
closeAndRedirect();
} catch (error) {
alert(error.message);
}
});

// Handle signup form submission
signupForm.addEventListener('submit', async (e) => {
e.preventDefault();
const email = document.getElementById('signup-email').value;
const password = document.getElementById('signup-password').value;
const empId = document.getElementById('signup-empid') ? document.getElementById('signup-empid').value : ''; // Only for admin

const data =
authType === 'admin'
? { empid: empId, password }
: { email, password };

try {
await auth.signup(data, authType);
alert(`Account created for ${authType === 'admin' ? empId : email}!`);
closeAndRedirect();
} catch (error) {
alert(error.message);
}
});

// Redirect after successful login/signup
const closeAndRedirect = () => {
modal.style.display = 'none';
document.body.classList.remove('modal-open');
window.location.href = 'index.html';
};
});
Loading

0 comments on commit 5777935

Please sign in to comment.