Skip to content
Advertisement

User ID won’t save into session after a log in

I’m new to coding and I’m trying to write one of my first apps. I encountered a problem with my log in function. The user id saves into my session object after user registration but it won’t save into it after a log in. I’m using MongoDB. Here is the code:

Controller

exports.register = function(req, res){
    let user = new User(req.body)
    user.register().then(()=>{
        // what do we do if the registration is succesfull - redirecting to the homepage with updated session data
        req.session.user = {username: user.data.username, avatar: user.avatar, _id: user.data._id}
        req.session.save(function(){
            res.redirect('/')})
            console.log(' After the registration usercontroller line nr 14 ', user.data._id)
    }).catch((regErrors)=>{
        regErrors.forEach(function(error){

            req.flash('regErrors', error)
        })
        req.session.save(function(){
            res.redirect('/')
        })
    })
    
}


exports.login = function(req, res){

    let user = new User(req.body)
    user.login().then(function(result){
        //saving data into a cookie
        req.session.user = {avatar: user.avatar, username: user.data.username, _id: user.data._id}
        req.session.save(function(){
            res.redirect('/')
            console.log('After the log in  line 51 userController', req.session)
        })
        
       
    }).catch(function(e){
        req.flash('errors', e)
        req.session.save(function(){
            
            res.redirect('/')
            // After the failed log in 
            console.log('After the failed log in line 61', req.session)
        })
    })

}

Model

User.prototype.login = function() {

  return new Promise((resolve, reject) => {
    this.cleanUp()
    usersCollection.findOne({
      username: this.data.username
    }).then((attemptedUser) => {
      if (attemptedUser && bcrypt.compareSync(this.data.password, attemptedUser.password)) {
        this.data.attemptedUser
        this.getAvatar()
        resolve("Congrats !")

      } else {
        reject("Invalid username/password")
      }
    }).catch(function() {

      reject("Please try again later.")

    })


  })


}

User.prototype.register = function() {
  return new Promise(async(resolve, reject) => {
    //Step #1: Validate user data
    await this.validate()
    this.cleanUp()

    //Step #2: Only if there are no validation errors save the user data into a database
    if (!this.errors.length) {
      // Hash user password
      let salt = bcrypt.genSaltSync(10)
      this.data.password = bcrypt.hashSync(this.data.password, salt)
      await usersCollection.insertOne(this.data)
      this.getAvatar()
      resolve()
    } else {
      reject(this.errors)

    }


  })
}

Screenshot of the console – registration

Screenshot of mongo – registration

Screenshot of the console – log in

Screenshot of mongo – log in

I’ve been following Brad Schiffs Java Script Full Stack from Scratch course and everything seems to be working fine for him.

Advertisement

Answer

Your model does nothing with found user: try

if(attemptedUser && bcrypt.compareSync(this.data.password, attemptedUser.password)) {
    this.data.attemptedUser = attemptedUser
    this.getAvatar()
    resolve("Congrats !")
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement