I am trying to implement passport. What i am trying to achive is only logged in users will be able to access /create route and create new posts.
I imported necessary libraries.
import passport from "passport";
import localStrategy from "passport-local";
import session from "express-session";
import connectPgSimple from 'connect-pg-simple';
I implement passpor logic.
passport.use(new localStrategy(async function verify(username, password, cb) {
try {
const result = await db.query(`SELECT * FROM loginDetail WHERE username = $1`, [username]);
if (result.rows.length === 0) {
return cb(null, false, { message: "Incorrect username or password" });
}
const row = result.rows[0];
bcrypt.compare(password, row.password, (err, result) => {
if (err) {
console.error("Error comparing passwords:", err);
return cb(null, false, { message: "Failed to compare passwords" });
} else if (result) {
// Passwords match, user is authorized
return cb(null, row);
} else {
// Passwords don't match, render login page with error message
return cb(null, false, { message: "Invalid credentials. Please try again." });
}
});
} catch (err) {
return cb(err);
}
}));
app.use(
session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
cookie: { secure: true }
})
);
passport.serializeUser(function(user, cb) {
cb(null, user.id);
});
// passport.deserializeUser(function(id, cb) {
// // Retrieve user from the database based on the provided ID
// // Example assuming you have a `User` model:
// db.query('SELECT * FROM users WHERE id = $1', [id], function(err, result) {
// if (err) { return cb(err); }
// cb(null, user);
// });
// });
passport.deserializeUser(function(id, done) {
db.query('SELECT * FROM loginDetail WHERE id = $1', [id], function(err, result) {
if(err)
return done(err, user);
if(result.rows.length > 0){
const user = result.rows[0];
done(null, user)
}else{done(null, false)}
});
});
app.use(passport.initialize());
app.use(passport.session());
app.post("/login",passport.authenticate('local', { failureRedirect: '/login',successRedirect:"/" }), async (req, res) => {
});
I create ensureAuthenticated to make sure only loggedin users will be able to access /create route.
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
// If the user is authenticated, allow the request to proceed
return next();
} else {
// If the user is not authenticated, redirect to the login page
res.redirect("/login");
}
}
app.get("/create",ensureAuthenticated, (req, res) => {
res.render("create.ejs");
});
app.post("/create",ensureAuthenticated, async (req, res) => {
const result = await db.query("SELECT MAX(id) AS max_id FROM posts");
const maxId = result.rows[0].max_id || 0; // If no posts exist, set maxId to 0
// Increment the maximum ID by one to generate a new unique ID
const newId = maxId + 1;
const post = {
id: newId,
author: req.body.author,
title: req.body.title,
content: req.body.content,
};
const postPush = await db.query(
"INSERT INTO posts (id,author,title,content) VALUES($1,$2,$3,$4) RETURNING *;",
[post.id, post.author, post.title, post.content]
);
});
I implemented passport logic and created function ensureAuthenticated to allow only loggedin users to access and create post. I successfully login and be redirected to /.
user23773270 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.