Open mahendra785 opened 2 months ago
Implement a login and signup feature that allows users to create an account and log in to the website. Ensure that user credentials are securely handled and stored in the database.
User Schema Structure:
username
: Unique identifier for the user (e.g., String
, required)email
: User's email address (e.g., String
, required, unique)password
: User's hashed password (e.g., String
, required)createdAt
: Timestamp for when the account was created (e.g., Date
, default: current date/time)Mongoose Schema Example:
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
createdAt: {
type: Date,
default: Date.now
}
});
// Pre-save hook to hash the password before saving to the database
userSchema.pre('save', async function(next) {
if (!this.isModified('password')) return next();
this.password = await bcrypt.hash(this.password, 10);
next();
});
// Method to compare entered password with the hashed password
userSchema.methods.matchPassword = async function(enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
};
const User = mongoose.model('User', userSchema);
Implement a login and signup feature that allows users to create an account and log in to the website. Ensure that user credentials are securely handled and stored in the database.