Express/Passport creating session but not sending cookie to front end

Viewed 881

right now I have a react and node.js project running.

I am currently trying to implement the user authentication session. So far, it will send the username, password, and email(when registering) to the server. The server will then parse the data and attempt to register/login the user. The user credential is stored in an MongoDB atlas database. If it is successful, it will send the info back to the server.

After a successful authentication, the server is supposed to create a session and cookie pair. The session will be stored and the cookie will be sent to the client. However, the latter part isn't happening. I know the session is being created successfully as it is stored in another database in the MongoDB, but no matter what I do, I can't seem to get the cookie to the front end.

UserModel

const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const passportLocalMongoose = require('passport-local-mongoose');
const bcrypt = require('bcrypt');
const SALT_WORK_FACTOR = 10;
const userSchema = new mongoose.Schema({
    username:{
        type: String,
        lowercase:true,
        unique: true,
        required:[true, 'Username is required'], 
        match:[/^[a-zA-Z0-9]+$/, 'is an invalid username'],
        index: true
    },
    password:{
        type: String,
        required:[true, 'Password is required']
    },
    email:{
        type:String,
        lowercase:true,
        unique:true,
        required:[true, 'Email is required'],
        match:[/\S+@\S+\.\S+/, 'is an invalid email'],
        index: true, 
        uniqueCaseInsensitive: true
    }
}, {timestap: true})

userSchema.plugin(uniqueValidator, {message: '{PATH} is already taken.'});


//encrypt the password
userSchema.pre('save', function(next) {
    var user = this;
// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next();

// generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
    if (err) return next(err);

    // hash the password using our new salt
    bcrypt.hash(user.password, salt, function(err, hash) {
        if (err) return next(err);

        // override the cleartext password with the hashed one
        console.log("hashedPassword stored");
        user.password = hash;
        next();
    });
});
});

//validatePassword
userSchema.methods.comparePassword = function(candidatePassword, cb) {
    bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
        if (err) return cb(err);
        cb(null, isMatch);
    });
};



userSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model('users', userSchema, 'userInfo');

authRouter.js

router.post("/register-login",
            //this section checks the authentication
        (req, res, next) =>{

            passport.authenticate('local'
            ,   
            {   successRedirect: '/',
                failureRedirect: '/listingsForm'
            }
            ,
            //this will be called if authenticate was successful
            (err, user, info) => {
                if(req.body.isSignUp){

                    if(err){
                        return res.status(400).json({errors:err});
                    }
                    if(!user){

                        return res.status(400).json({errors:info});
                    }
                    else{   

                        return res.status(200).json({success: `created ${user.username}`});
                    }
                }
                else{
                    if(err){
                        return res.status(400).json({errors:err});
                    }
                    if(!user){
                        return res.status(400).json({errors:info});
                    }
                    else{
                        console.log(user.id);
                        req.login(user, (err)=>{
                            if(err){
                                throw err;
                            }
                        });
                        return res.status(200).json({success:`Welcome back ${user.username}`});
                    }
                }
            })(req,res,next)
        }

authUser.js


const User = require('../schemes/User')
const passport = require('passport');
const LocalStrategy = require('passport-local');

passport.serializeUser((user,done) =>{
    console.log(user.id);
    done(null,user.id);
})

passport.deserializeUser((id, done) => {
    User.findById(id, (err, user) => {
        done(err, user);
    });
});

passport.use(
    new LocalStrategy(

        {
            usernameField: 'username',
            passwordField: 'password',
            passReqToCallback: true
        },

        (req, username, password, done) =>{

        // console.log(username, password);
        console.log(req.body);
        //For Register  
        if(req.body.isSignUp){
            //determine it is a register attempt
            const newUser = new User({
            username: username,
            password: password,
            email: req.body.email
            });



            newUser.save()
            .then(
                user => {

                    return done(null,user);
                }
            )
            .catch(
                err => {
                    console.log('there is error');
                    console.log(err);
                    return done(null, false, {message:err.message});
                }
            )
        }

        //For Login
        else{
            User.findOne({username: username})
            .then(user => {

                let attemptPassword = password;
                if(!user){
                    return done(null, false, {message:'This username/password does not exist'})
                }
                else{
                    console.log("will verify now");

                    user.comparePassword(attemptPassword, function(err, isMatch) {
                        if (err){
                            console.log('hihi');

                            return done(null, false, {message:err})
                        }
                        if(!isMatch){

                            return done(null, false, {message:'This username/password does not exist'})
                        }
                        return done(null, user), {message:'Successfully Logged In'};
                    });
                }

            })
        }
    }  
));

module.exports = passport;

Index.js

app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

//expression session
app.use(session({
    secret: 'secret',
    resave: false,
    saveUninitialized: true,
    store: new MongoStore({mongooseConnection:mongoose.connection})
  }))

app.use(passport.initialize());
app.use(passport.session());
//express-router
const authRouter = require('./routes/auth-router');

app.use('/users',authRouter);


server.listen(PORT, () => console.log(`Server has started on port ${PORT}`));
1 Answers

I guess app.use(cors({credentials:true})); will solve your problem, gyus.

Related