Skip to content

Commit

Permalink
Merge pull request swaraj-das#681 from DeekshaVarshney123/main
Browse files Browse the repository at this point in the history
Implement User Authentication and Registration Features
  • Loading branch information
AnitSarkar123 authored Oct 27, 2024
2 parents 3122a8e + 675cccf commit 8194620
Show file tree
Hide file tree
Showing 7 changed files with 113 additions and 145 deletions.
19 changes: 8 additions & 11 deletions SignUp/signup.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
<link rel="shortcut icon" href="../images/logo.png" type="image/x-icon">
<style>
.condition {
color: gray; /* Default color */
color: gray;
font-size: 0.9em;
}
.condition.met {
color: lightgreen; /* Turns green when condition is met */
color: lightgreen;
}
.error-message {
color: red;
Expand All @@ -29,35 +29,32 @@

<div class="signup-container">
<h1>Create Your Account</h1>
<form action="#" method="post">
<form id="signup-form" action="#" method="post">
<div class="input-group">
<label for="username">Username</label>
<input type="text" id="username" name="username" placeholder="Create a Username" required>
</div>
<div class="input-group">
<label for="email">Email</label>
<div id="email-error" class="error-message"></div> <!-- Error message container -->
<div id="email-error" class="error-message"></div>
<input type="email" id="email" name="email" placeholder="Enter your mail-id" required>
</div>
<div class="input-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" placeholder="Create password" required>
</div>

<!-- Password Recommendations Section -->
<div class="password-recommendations">
<p id="length" class="condition">At least 8 characters</p>
<p id="uppercase" class="condition">Contains uppercase letters</p>
<p id="lowercase" class="condition">Contains lowercase letters</p>
<p id="number" class="condition">Contains numbers</p>
<p id="special" class="condition">Contains special characters</p>


</div>
<div class="input-group">
<label for="confirm-password">Confirm Password</label>
<input type="password" id="confirm-password" name="confirm-password" placeholder="Re-enter password" required>
</div>
<div id="password-error" class="error-message"></div> <!-- Password error container -->
<div id="password-error" class="error-message"></div>
<button type="submit" class="signup-button">Sign Up</button>
</form>
<div class="or-divider">
Expand All @@ -72,7 +69,7 @@ <h1>Create Your Account</h1>
</div>
</div>

<script src="https://accounts.google.com/gsi/client" async defer></script>
<script src="signup.js"></script> <!-- Link to the signup.js file -->
<script src="signup.js"></script>
</body>
</html>

52 changes: 10 additions & 42 deletions SignUp/signup.js
Original file line number Diff line number Diff line change
@@ -1,59 +1,24 @@
document.addEventListener("DOMContentLoaded", () => {
const signupButton = document.querySelector(".signup-button");

// List of trusted email domains
const trustedDomains = ["gmail.com", "outlook.com", "yahoo.com", "hotmail.com" , "protonmail.com" , "icloud.com" , "tutanota.com"];

signupButton.addEventListener("click", (e) => {
e.preventDefault();

const name = document.querySelector("#username").value;
const email = document.querySelector("#email").value;
const password = document.querySelector("#password").value;
const confirmPassword = document.querySelector("#confirm-password").value;
const emailError = document.querySelector("#email-error"); // Reference to email error div
const passwordError = document.querySelector("#password-error"); // Reference to password error div

// Clear any previous error messages
emailError.textContent = "";
emailError.style.display = "none"; // Hide the error message by default
passwordError.textContent = "";
passwordError.style.display = "none"; // Hide the error message by default

if (!name || !email || !password || !confirmPassword) {
emailError.textContent = "Every field is required.";
emailError.style.display = "block";
alert("Every field is required.");
return;
}

// Email domain validation
const emailDomain = email.split("@")[1]; // Get the domain from the email
if (!trustedDomains.includes(emailDomain)) {
emailError.textContent = "Please use an email address from a trusted provider (e.g., Gmail, Outlook, Yahoo) etc.";
emailError.style.display = "block";
return;
}

// Password matching validation
if (password !== confirmPassword) {
passwordError.textContent = "Passwords do not match.";
passwordError.style.display = "block";
alert("Passwords do not match.");
return;
}

const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
if (!emailPattern.test(email)) {
alert("Please enter a valid email address.");
return; // Stop the function if the email is not in the right format
}

const userdata = {
name,
email,
password,
confirmPassword
};

const userdata = { name, email, password };
registerUser(userdata);
});

Expand All @@ -64,12 +29,15 @@ document.addEventListener("DOMContentLoaded", () => {
headers: { "content-type": "application/json" },
body: JSON.stringify(user)
});

const data = await res.json();
console.log(data);
window.location.href = "http://127.0.0.1:5500/Collect-your-GamingTools/login/login.html";
if (data.success) {
alert('Signup successful! Redirecting to login...');
window.location.href = "../login/login.html"; // Redirect after signup
} else {
alert(data.message); // Show error message
}
} catch (err) {
console.log(err.message);
alert('Error: ' + err.message); // Show error message
}
};

Expand Down
4 changes: 3 additions & 1 deletion backend/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ databaseconnect();
app.use(express.json()); // Built-in middleware
app.use(cookieParser()); // Third-party middleware

app.use(cors({ origin: [process.env.CLIENT_URL], credentials: true })); //Third-party middleware
// app.use(cors({ origin: [process.env.CLIENT_URL], credentials: true })); //Third-party middleware
app.use(cors({ origin: "https://collect-your-gamingtools.netlify.app", credentials: true }));


// Auth router
app.use('/auth', authRouter);
Expand Down
26 changes: 26 additions & 0 deletions backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@
"crypto": "^1.0.1",
"dotenv": "^16.4.5",
"email-validator": "^2.0.4",
"nodemailer": "^6.9.15",
"express": "^4.21.0",
"express-rate-limit": "^7.4.1",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.7.0",
"nodemailer": "^6.9.15",
"nodemon": "^3.1.5"
}
}
104 changes: 46 additions & 58 deletions login/auth.js
Original file line number Diff line number Diff line change
@@ -1,68 +1,56 @@

import { initializeApp } from "https://www.gstatic.com/firebasejs/10.14.1/firebase-app.js";
import { getAuth, signOut, onAuthStateChanged, GoogleAuthProvider, signInWithPopup } from "https://www.gstatic.com/firebasejs/10.14.1/firebase-auth.js";

// Firebase configuration
const firebaseConfig = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.FIREBASE_APP_ID,
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.14.1/firebase-app.js";
import { getAuth, signOut, onAuthStateChanged, GoogleAuthProvider, signInWithPopup } from "https://www.gstatic.com/firebasejs/10.14.1/firebase-auth.js";

// Firebase configuration
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const provider = new GoogleAuthProvider();


// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
auth.languageCode = "en";
const provider = new GoogleAuthProvider();

// Sign in with Google
const googleLoginBtn = document.getElementById('google-login-btn');
googleLoginBtn?.addEventListener('click', function () {
// Sign in with Google
document.getElementById('google-login-btn').addEventListener('click', function () {
signInWithPopup(auth, provider)
.then((result) => {
const user = result.user;
console.log('User logged in:', user);

// Redirect to the home page
window.location.href = "../index.html";
})
.catch((error) => {
console.error('Login error:', error);
});
});

// Handle auth state change and toggle login/logout button
window.addEventListener('load', () => {
.then((result) => {
const user = result.user;
alert(`Welcome ${user.displayName}!`);
window.location.href = "../index.html";
})
.catch((error) => {
alert('Login failed: ' + error.message);
});
});

// Handle auth state change
onAuthStateChanged(auth, (user) => {
const authLink = document.getElementById('auth-link');

onAuthStateChanged(auth, (user) => {
if (user) {
// If the user is logged in, change the link to "Logout"
if (user) {
authLink.textContent = 'Logout';
authLink.removeAttribute('href');
authLink.addEventListener('click', handleLogout);
} else {
// If the user is not logged in, change the link to "Login"
authLink.onclick = handleLogout;
} else {
authLink.textContent = 'Login';
authLink.setAttribute('href', 'login/login.html');
authLink.removeEventListener('click', handleLogout);
}
});
});
}
});

// Handle logout
function handleLogout() {
// Handle logout
function handleLogout() {
signOut(auth)
.then(() => {
console.log('User logged out');
window.location.reload(); // Reload the page if needed
})
.catch((error) => {
console.error('Logout error:', error);
});
}
.then(() => {
alert('Logged out successfully!');
window.location.reload();
})
.catch((error) => {
alert('Logout failed: ' + error.message);
});
}


Loading

0 comments on commit 8194620

Please sign in to comment.