Building a NodeJS Web App Using PassportJS for Authentication

Richard Debrah on December 20, 2018

Updated!!! This tutorial uses PassportJS to authenticate the NodeJS App with MySQL Database Management Software (DBMS). The reason for this article... [Read Full]
markdown guide
 

Great tutorial I was able to recreate most of it on my own web app but I am getting this error when I try to setup a new account-
Executing (default): SELECT id, FirstName, LastName, Username, Email, Password, createdAt, updatedAt FROM Users AS User WHERE User.email = 'test@test.com' LIMIT 1;
Unhandled rejection Incorrect arguments

 

@cristiano thank you for taking time to read this article. Can you kindly send all the error output so i can help?
unhandled rejection error from sequelize can be from any number of reasons with respect to the model. make sure you are passing the right associations as it is checked against your model when you make a select/read from the db

 

Sure! I only get that error when setting up a new account but it actually inserts the data into the database so i moved on from it.
Now when I try to login using the credentials I used when I first set up an account, I get a Cannot Get /[object %20Response]

I've switched up the code a little so I'll show you what mine looks like. I have an ejs file with a link to the script and a button that calls the submit function :


<script type="text/javascript" src="/scripts/login.js"></script>
<button type="button" onclick="submit()" class="btn">Sign in</button>

Then the login.js looks like this:


``` function submit() {

var emailInput = document.getElementById("email").value;
var passwordInput =document.getElementById("password").value;

var userData = {
email: emailInput.trim(),
password: passwordInput.trim()
};

if (!userData.email || !userData.password) {
return;
}

// If we have an email and password we run the loginUser function and clear the form
loginUser(userData.email, userData.password);
emailInput.val("");
passwordInput.val("");
};

// loginUser does a post to our "APIlogin" route and if successful, redirects us the the members page
function loginUser(email, password) {
fetch("/APIlogin", {
method: 'POST',
email: email,
password: password
}).then(function(data) {
window.location.replace(data);
// If there's an error, log the error
}).catch(function(err) {
console.log(err);
});
}```

and then finally the app.js and APIlogin call looks like this respectively:


app.post('/APIlogin', passport.authenticate("local"), APIlogin);

and


APIlogin:(req, res)=> {
res.json("/questions");
}

 

I believe this is meant for you, @cristianooo ? Looks interesting though. 😃

 

To get the user model to work, I changed the code into the following

module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('User', {
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
password: {
type: DataTypes.STRING,
allowNull: false
}
}, {
hooks: {
beforeCreate: function(user) {
user.password = bcrypt.hashSync(user.password, bcrypt.genSaltSync(10), null);
}
}
})

// Creating a custom method for our User model.
//This will check if an unhashed password entered by the
//user can be compared to the hashed password stored in our database
User.prototype.validPassword = function(password) {
return bcrypt.compareSync(password, this.password);
};
// Hooks are automatic methods that run during various phases of the User Model lifecycle
// In this case, before a User is created, we will automatically hash their password
/*
User.hook("beforeCreate", function(user) {
user.password = bcrypt.hashSync(user.password, bcrypt.genSaltSync(10), null);
});
*/
return User;
};

 

I am glad it worked with the update. I will try to figure out your add and incorporate it for others.

 

Hey Richard,

Thank you for making an effort to solve the issue, I agree they are various tutorials for MongoDB, EJS, Php, etc.. for the login registration with passport but yours is the only one that I could find with MySQL and HTML. Perfect for what I was looking for.

I need your help for an error,
db[model.name] = model;
^

TypeError: Cannot read property 'name' of undefined

this error is in the index.js file.

Looking forward to your reply.

 

Hi there,
anyone getting this?

Cannot GET /[object%20Object]

 

FIX:
bcrypt-nodejs is no longer supported. npmjs.com/package/bcrypt-nodejs
make sure do get the latest version via npm called bcrypt or bcryptjs.

In user.js just change

var bcrypt = require("bcrypt-nodejs");

to

var bcrypt = require("bcryptjs");

 

Great article man

there is a small typo

..... Handlebars as the ORM and MondoDB as the DBMS which at that time, i was not that .....

You wrote MondoDB instead of mongo db

 

Thank you Joshy. You are right. I will fix it.

 

Thank you very much for help. The article is clear to understand.

I am getting this error:
\learningPassportJS\models\index.js:31
db[model.name] = model;
^
TypeError: Cannot read property 'name' of undefined

Not sure what I'm missing :(

 

Error: Can't set headers after they are sent.
Did someone got same problem?

 

i get this error with your code how do i fix this?

models/users.js:36
User.hook("beforeCreate", function(user) {
TypeError: User.hook is not a function

 

Hi @anunes . Thank you for taking time to read the article. Can you kindly (if possible) push your work to github and share with me? that will be easy for me to debug what is happening.

But User.hook not being a function basically means you are calling the hook on the wrong model or instance of User. Kindly check your code to make sure you are passing User as the model as your hook is supposed to be bound to it.

 

Do you have the code of this app somewhere in Github so I can clone directly from there and study. I am also getting User.hook not a function error.

 

How did you solve this, am getting a similar error

 

I think sequelize modified their doc. I had to do this

Users.beforeCreate(user => {
    user.password = bcrypt.hashSync(
      user.password,
      bcrypt.genSaltSync(10),
      null
    );
  });

before it worked. Check out the doc Hooks

code of conduct - report abuse