Saturday, 11 September 2021

Why I'm not kept logged in when using Passport and sessions? Passport's "isAuthenticated()" always returns false

What I want to achieve: to add a middleware to my /recipes route to allow users to see the recipes only if they are logged in. I think I did it but when I add the middleware I get an error in my console I'm not sure what I am doing wrong. If you guys have any idea I would really appreciate it. Question Can I use passport and sessions with Angular? I can log in, but Passport's "isAuthenticated()" always returns false

This is the error

enter image description here

Backend code

const cors = require('cors');
const express = require("express");
const app = express();
const PORT = 3000;
const mongoose = require('mongoose');
const Recipe = require('./models/recipe');
const passport = require("passport");
const LocalStrategy = require("passport-local");
const User = require("./models/user");
const Profile = require("./models/profile");
const {isLoggedIn} = require("./middleware/auth");

app.use(cors());
app.options('*', cors());
app.use(express.json())

app.use(express.urlencoded({ extended: true }));

app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));

passport.use(User.createStrategy());

passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

mongoose.connect('mongodb://localhost:27017/foodAppCopy', {useNewUrlParser: true, useUnifiedTopology: true})
    .then(() => {
        console.log("Mongo Connection open")
    })
    .catch((error) => {
        console.log("No, Mongo -> Connection Error " + error)
    })

app.post('/register', async (req, res) => {
    try {
        const {name, email, password} = req.body
        const user = new User({name, email});
        const registeredUser = await User.register(user, password);
        res.send(registeredUser._id)
    } catch(e) {
        console.log(e.message)
    }
})

app.post('/login', passport.authenticate('local', {successRedirect: '/recipes', failureRedirect: "/login"}), 
    async(req, res) => {
})

app.get('/recipes', isLoggedIn ,async (req, res) => {
    const recipes = await Recipe.find({});
    res.send(recipes);
})

Middleware file

    module.exports.isLoggedIn = (req, res, next) => {
        if(req.isAuthenticated()) {
            return next()
        } 
        res.status(403).send("Please login");
     }


  [1]: https://i.stack.imgur.com/GsfG8.png

User Model

const mongoose = require("mongoose");
const passportLocalMongoose = require("passport-local-mongoose");

const UserSchema = new mongoose.Schema({
    email: {
        type: String, 
        required: true,
    },
})

UserSchema.plugin(passportLocalMongoose, {
    usernameField: "email"
});

module.exports = mongoose.model("User",UserSchema);


from Why I'm not kept logged in when using Passport and sessions? Passport's "isAuthenticated()" always returns false

No comments:

Post a Comment