I have a problem with passport middleware, when I am authenticating a user it doesn't redirect I have no idea what's wrong.
Here is the code and whole project on GitHub:
const express = require("express");
const router = express.Router();
const passport = require("passport");
const genPassword = require("../passwordUtils").genPassword;
const connection = require("../database");
const User = connection.models.User;
// const logRegController = require("../controllers/log-reg-controller");
router.post(
"/login",
passport.authenticate("local", {
successRedirect: "/",
failureRedirect: "/register",
})
);
router.post("/register", async (req, res) => {
const existingUser = await User.findOne({ username: req.body.username });
if (existingUser) return res.json({ message: "User already exists" });
const saltHash = genPassword(req.body.password);
const { salt, hash } = saltHash;
const newUser = new User({
username: req.body.username,
hash: hash,
salt: salt,
});
newUser.save().then((user) => console.log(user));
res.status(201).json({ message: "All good" });
});
module.exports = router;
https://github.com/Oliwier965/Photo-App/tree/main
CodePudding user response:
You can try it with a callback function that redirects you can do it like this according to Docs
router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/register'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
//If Successful
return res.redirect('/');
});
})(req, res, next);
});
CodePudding user response:
Dear StackOverflow community, this was a challenging battle but I come from it with an answer.
The problem was that I was sending post request using javascript fetch() which is an interface for making AJAX requests. And it is specifically designed to not change your URL. My solution is to send the URL that I want to redirect through res.json() with status 302 and redirect using the frontend. Hope it will help someone I attach the code below.
BACKEND
router.post("/login", function (req, res, next) {
passport.authenticate("local", function (err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(320).json({ redirectUrl: "/register" });
}
req.logIn(user, function (err) {
if (err) {
return next(err);
}
//If Successful
return res.status(320).json({ redirectUrl: "/" });
});
})(req, res, next);
});
FRONTEND
const login = async function (e) {
e.preventDefault();
const username = loginForm.querySelector("#email").value;
const password = loginForm.querySelector("#password").value;
const response = await fetch("/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
username,
password,
}),
});
const result = response.json();
const data = await result;
const { redirectUrl } = data;
window.location.href = redirectUrl;
};