Open Jamesabira opened 1 year ago
Step 1: Project Setup and Dependencies
Create a new Node.js project and install the necessary dependencies:
mkdir login-register-system cd login-register-system npm init -y npm install express mongoose body-parser bcrypt express-session express-validator
Step 2: Set Up MongoDB Database
Set up a MongoDB database and create a collection called "users."
Step 3: Application Code
Create an
app.js
file and build your application. This is a detailed process, so I'll provide the complete code. You'll need to break it down and thoroughly test each component.const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const bcrypt = require('bcrypt'); const session = require('express-session'); const { check, validationResult } = require('express-validator'); const MongoStore = require('connect-mongo')(session); const app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(session({ secret: 'your-secret-key', resave: false, saveUninitialized: true, store: new MongoStore({ mongooseConnection: mongoose.connection }), })); mongoose.connect('mongodb://localhost/login-register-system', { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, }); const userSchema = new mongoose.Schema({ firstName: String, lastName: String, email: String, phoneNumber: String, username: { type: String, unique: true }, password: String, failedLoginAttempts: { type: Number, default: 0 }, isLockedOut: { type: Boolean, default: false }, lockoutUntil: { type: Date, default: Date.now }, }); userSchema.pre('save', async function(next) { if (!this.isModified('password')) { return next(); } try { const hash = await bcrypt.hash(this.password, 10); this.password = hash; next(); } catch (error) { next(error); } }); const User = mongoose.model('User', userSchema); app.post('/register', [ check('email', 'Invalid email').isEmail(), check('username', 'Username must be at least 5 characters').isLength({ min: 5 }), check('password', 'Password must be at least 6 characters').isLength({ min: 6 }), ], async (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const { firstName, lastName, email, phoneNumber, username, password } = req.body; try { const user = new User({ firstName, lastName, email, phoneNumber, username, password }); await user.save(); res.json({ message: 'Registration successful.' }); } catch (error) { console.error(error); res.status(500).json({ error: 'Registration failed.' }); } }); app.post('/login', async (req, res) => { const { username, password } = req.body; try { const user = await User.findOne({ username }); if (!user) { return res.status(401).json({ error: 'Invalid username or password.' }); } if (user.isLockedOut && user.lockoutUntil > Date.now()) { return res.status(403).json({ error: 'Account locked. Try again later.' }); } const isValidPassword = await bcrypt.compare(password, user.password); if (isValidPassword) { user.failedLoginAttempts = 0; return res.json({ message: 'Login successful.' }); } else { user.failedLoginAttempts++; if (user.failedLoginAttempts >= 3) { user.isLockedOut = true; user.lockoutUntil = new Date(Date.now() + 60000); } await user.save(); return res.status(401).json({ error: 'Invalid username or password.' }); } } catch (error) { console.error(error); res.status(500).json({ error: 'Login failed.' }); } }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
Alternatively
Step 1: Install and Run MongoDB
Ensure you have MongoDB installed and running. If not, follow the installation steps in the previous response.
Step 2: Set Up a Node.js Project
Create a new Node.js project and install the required dependencies:
mkdir login-register-app cd login-register-app npm init -y npm install express mongoose body-parser
Step 3: Define Your Data Model
Create a
models
directory in your project and define a user schema. Create a file namedUser.js
:const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ firstName: String, lastName: String, email: { type: String, unique: true, }, phoneNumber: String, username: { type: String, unique: true, }, password: String, googleId: String, // For Google login // Add more fields as needed }); const User = mongoose.model('User', userSchema); module.exports = User;
Step 4: Set Up the Express App
Create an Express app in your
app.js
file:const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const User = require('./models/User'); const app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // Connect to the MongoDB database mongoose.connect('mongodb://localhost/login-register-db', { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, }); // Routes for registration and login app.post('/register', async (req, res) => { try { // Create a new user const newUser = new User(req.body); await newUser.save(); res.json({ message: 'Registration successful.' }); } catch (error) { console.error(error); res.status(500).json({ error: 'Registration failed.' }); } }); app.post('/login', async (req, res) => { const { username, password } = req.body; try { // Find the user by username const user = await User.findOne({ username }); if (!user) { return res.status(401).json({ error: 'Invalid username or password.' }); } // Validate the password (you should use bcrypt here) if (user.password === password) { return res.json({ message: 'Login successful.' }); } else { res.status(401).json({ error: 'Invalid username or password.' }); } } catch (error) { console.error(error); res.status(500).json({ error: 'Login failed.' }); } }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
Step 5: Test Your Application
You can now run your Node.js application and test the registration and login functionality with MongoDB as your database.
To test Follow this
node app.js
.curl -X POST \
http://localhost:3000/register \
-H 'Content-Type: application/json' \
-d '{
"firstName": "John",
"lastName": "Doe",
"email": "john.doe@example.com",
"username": "johndoe",
"password": "password123"
}'
{
"message": "Registration successful."
}
curl -X POST \
http://localhost:3000/login \
-H 'Content-Type: application/json' \
-d '{
"username": "johndoe",
"password": "password123"
}'
{
"message": "Login successful."
}
Step 1: Project Setup and Dependencies
Create a new Node.js project and install the necessary dependencies:
Step 2: Set Up MongoDB Database
Set up a MongoDB database and create a collection called "users."
Step 3: Application Code
Create an
app.js
file and build your application. This is a detailed process, so I'll provide the complete code. You'll need to break it down and thoroughly test each component.Alternatively
Step 1: Install and Run MongoDB
Ensure you have MongoDB installed and running. If not, follow the installation steps in the previous response.
Step 2: Set Up a Node.js Project
Create a new Node.js project and install the required dependencies:
Step 3: Define Your Data Model
Create a
models
directory in your project and define a user schema. Create a file namedUser.js
:Step 4: Set Up the Express App
Create an Express app in your
app.js
file:Step 5: Test Your Application
You can now run your Node.js application and test the registration and login functionality with MongoDB as your database.