Application Description:
The application is a web-based platform that allows users to register, log in, and interact with a list of user profiles. It includes user authentication for security and uses a database to store user information. Here are the key features and what has been created so far:
Features Implemented:
User Registration: Users can create accounts by providing a username and password. The password is securely hashed for protection.
User Login: Registered users can log in using their credentials.
User Profiles: Upon logging in, users can view a list of user profiles. These profiles contain personal information like username, age, gender, and income.
Sorting: Users can sort the list of profiles in either ascending or descending order based on income.
User Authentication: The application ensures that only authenticated users can access certain features, such as viewing user profiles.
Session Management: It uses session management to keep users logged in across different pages of the website.
now i am going to provide my code and for all the modules
const express = require('express');
const router = express.Router();
const usersController = require('./controllers/usersController');
const bodyParser = require('body-parser');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
const mongoose = require('mongoose');
const User = require('./models/user'); // Replace with your actual User model
const app = express();
const port = process.env.PORT || 3000;
// Route to retrieve and display users using the controller
router.get('/users', usersController.getUsers);
module.exports = router;
app.use(bodyParser.urlencoded({ extended: false }));
app.set('view engine', 'ejs');
// ----------------------------------------
// Connect to MongoDB
// ----------------------------------------
mongoose.connect('mongodb://localhost/user', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log('MongoDB Connected');
})
.catch((err) => {
console.error('MongoDB Connection Error:', err);
});
// ----------------------------------------
// Passport.js Configuration
// ----------------------------------------
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(
(username, password, done) => {
User.findOne({ username: username })
.then((user) => {
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
bcrypt.compare(password, user.password)
.then((result) => {
if (!result) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
})
.catch((err) => done(err));
})
.catch((err) => done(err));
}
));
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id)
.then((user) => done(null, user))
.catch((err) => done(err));
});
// ----------------------------------------
// CRUD Routes
// ----------------------------------------
// Create Route
app.post('/create', (req, res) => {
const { username, age, gender, income } = req.body;
// Replace this with your User model and database logic
User.create({ username, age, gender, income }, (err, user) => {
if (err) {
console.error(err.message);
return res.status(500).send('Create failed');
}
res.redirect('/');
});
});
// Read Route
app.get('/', (req, res) => {
// Replace this with your User model and database logic to fetch and render data
User.find({}, (err, users) => {
if (err) {
console.error(err.message);
return res.status(500).send('Read failed');
}
res.render('index', { users });
});
});
// Update Route
app.post('/update/:id', (req, res) => {
const userId = req.params.id;
const { username, age, gender, income } = req.body;
// Replace this with your User model and database logic
User.findByIdAndUpdate(userId, { username, age, gender, income }, (err, user) => {
if (err) {
console.error(err.message);
return res.status(500).send('Update failed');
}
res.redirect('/');
});
});
// Delete Route
app.get('/delete/:id', (req, res) => {
const userId = req.params.id;
// Replace this with your User model and database logic
User.findByIdAndRemove(userId, (err, user) => {
if (err) {
console.error(err.message);
return res.status(500).send('Delete failed');
}
res.redirect('/');
});
});
// ----------------------------------------
// Authentication Routes
// ----------------------------------------
app.post('/register', (req, res) => {
const { username, password } = req.body;
bcrypt.hash(password, 10)
.then((hashedPassword) => {
User.create({ username, password: hashedPassword })
.then((user) => {
res.redirect('/login');
})
.catch((err) => {
console.error(err.message);
res.status(500).send('Registration failed');
});
})
.catch((err) => {
console.error(err.message);
res.status(500).send('Registration failed');
});
});
app.post('/login', passport.authenticate('local', {
successRedirect: '/profile',
failureRedirect: '/login',
failureFlash: true
}));
app.get('/logout', (req, res) => {
req.logout();
res.redirect('/login');
});
// ----------------------------------------
// Authentication Middleware
// ----------------------------------------
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/login');
}
// ----------------------------------------
// Example: Protect a route
// ----------------------------------------
app.get('/profile', isLoggedIn, (req, res) => {
res.render('profile', { user: req.user });
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
now for authentication
// passport-config.js
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
const User = require('./models/user'); // Replace with your User model import
// Configure Passport.js
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
module.exports = (app) => {
app.use(passport.initialize());
app.use(passport.session());
};
index ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Personal Information</title>
<link rel="stylesheet" href="/styles.css"> <!-- Include your CSS file -->
</head>
<body>
<h1>Personal Information</h1>
<!-- Form for creating a new entry -->
<form action="/create" method="POST">
<input type="text" name="username" placeholder="Username" required>
<input type="number" name="age" placeholder="Age" required>
<input type="text" name="gender" placeholder="Gender" required>
<input type="number" name="income" placeholder="Income" required>
<button type="submit">Add Entry</button>
</form>
<!-- Display personal information -->
<table>
<tr>
<th>Username</th>
<th>Age</th>
<th>Gender</th>
<th>Income</th>
<th>Actions</th>
</tr>
<% data.forEach((entry) => { %>
<tr>
<td><%= entry.username %></td>
<td><%= entry.age %></td>
<td><%= entry.gender %></td>
<td>$<%= entry.income %></td>
<td>
<a href="/update/<%= entry.id %>">Edit</a> |
<a href="/delete/<%= entry.id %>">Delete</a>
</td>
</tr>
<% }); %>
</table>
<!-- Sorting options -->
<div>
<p>Sort by Income:</p>
<a href="/sort/asc">Ascending</a> |
<a href="/sort/desc">Descending</a>
</div>
</body>
</html>
login ejs
<h1>Login</h1>
<form action="/login" method="POST">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<button type="submit">Login</button>
</form>
profile ejs
<h1>Welcome, <%= user.username %></h1>
<p>User-specific content goes here.</p>
<a href="/logout">Logout</a>
register ejs
<!-- Display flash messages for success and error -->
<% if (success) { %>
<div class="alert alert-success">
<%= success %>
</div>
<% } %>
<% if (error) { %>
<div class="alert alert-danger">
<%= error %>
</div>
<% } %>
<h1>Registration</h1>
<form action="/register" method="POST">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<button type="submit">Register</button>
</form>
<h1>Registration</h1>
<form action="/register" method="POST">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<button type="submit">Register</button>
</form>
for styles
body {
font-family: Arial, sans-serif;
margin: 20px;
padding: 0;
}
h1 {
font-size: 24px;
margin-bottom: 20px;
}
form input {
margin-right: 10px;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
table, th, td {
border: 1px solid #ccc;
}
th, td {
padding: 10px;
text-align: center;
}
th {
background-color: #f2f2f2;
font-weight: bold;
}
table tr:nth-child(even) {
background-color: #f2f2f2;
}
a {
text-decoration: none;
color: #007BFF;
}
a:hover {
text-decoration: underline;
}
div {
margin-top: 20px;
}
p {
margin-bottom: 10px;
}
and user js
const mongoose = require('mongoose');
const passportLocalMongoose = require('passport-local-mongoose');
const userSchema = new mongoose.Schema({
username: String,
// You can add more fields like 'name', 'email', 'profilePicture', etc.
});
// Add Passport-Local-Mongoose plugin to User Schema
userSchema.plugin(passportLocalMongoose);
// Create and export the User model
module.exports = mongoose.model('User', userSchema);
i have worked on this please if you can add more feature to it will be most welcomed but help me in adding authentication to this project
i will also add the previous code whose only function was to work on crud
const express = require('express');
const bodyParser = require('body-parser');
const sqlite3 = require('sqlite3').verbose();
const app = express();
const port = process.env.PORT || 3000;
app.use(bodyParser.urlencoded({ extended: false }));
app.set('view engine', 'ejs');
const db = new sqlite3.Database('./data.db');
db.serialize(() => {
db.run(`
CREATE TABLE IF NOT EXISTS personal_info (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT,
age INTEGER,
gender TEXT,
income INTEGER
)
`);
});
app.post('/create', (req, res) => {
const { username, age, gender, income } = req.body;
const stmt = db.prepare('INSERT INTO personal_info (username, age, gender, income) VALUES (?, ?, ?, ?)');
stmt.run(username, age, gender, income, (err) => {
if (err) {
console.error(err.message);
res.status(500).send('Internal Server Error');
} else {
res.redirect('/');
}
});
stmt.finalize();
});
app.get('/', (req, res) => {
db.all('SELECT * FROM personal_info', (err, rows) => {
if (err) {
console.error(err.message);
res.status(500).send('Internal Server Error');
return;
}
res.render('index.ejs', { data: rows });
});
});
app.post('/update/:id', (req, res) => {
const { username, age, gender, income } = req.body;
const id = req.params.id;
const stmt = db.prepare('UPDATE personal_info SET username = ?, age = ?, gender = ?, income = ? WHERE id = ?');
stmt.run(username, age, gender, income, id, (err) => {
if (err) {
console.error(err.message);
res.status(500).send('Internal Server Error');
} else {
res.redirect('/');
}
});
stmt.finalize();
});
app.get('/delete/:id', (req, res) => {
const id = req.params.id;
db.run('DELETE FROM personal_info WHERE id = ?', id, (err) => {
if (err) {
console.error(err.message);
res.status(500).send('Internal Server Error');
} else {
res.redirect('/');
}
});
});
app.get('/sort/asc', (req, res) => {
db.all('SELECT * FROM personal_info ORDER BY income ASC', (err, rows) => {
if (err) {
console.error(err.message);
res.status(500).send('Internal Server Error');
return;
}
res.render('index.ejs', { data: rows });
});
});
app.get('/sort/desc', (req, res) => {
db.all('SELECT * FROM personal_info ORDER BY income DESC', (err, rows) => {
if (err) {
console.error(err.message);
res.status(500).send('Internal Server Error');
return;
}
res.render('index.ejs', { data: rows });
});
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
we were previously using sqlite for this project but now we have added mongo in it so i don’t know which should be easy to work or use it so make changes in it if possible