Tuesday 11 April 2017

Express App using PassportJS and dynamoDB locates to login page without error

I have a problem regarding my Express Login App. The whole app runs so far and i get the login page. This is not a dynamodb query problem. I posted my login.js file below and can add more files if needed. The problem is that i don't get any errors which could help me debugging. It "should" log errors to the console which it does not so i really can't figure out where the problem might be. Thanks for your help!

This is the login.js file:

const LocalStrategy = require("passport-local").Strategy;
const User = require("../models/user");
const bCrypt = require("bcrypt-nodejs");

const AWS = require("aws-sdk");
const dynamodb = new AWS.DynamoDB({
  apiVersion: "2012-08-10",
  //testing purposes
   "region": "us-west-2",
  "accessKeyId": "abcde",
  "secretAccessKey": "abcde",  
  "endpoint": "http://localhost:8001"
});

module.exports = function(passport) {

  passport.use("login", new LocalStrategy({
      passReqToCallback: true
    },
    function(req,username,password,done) {
      var queryParams = {
    TableName: "users",
    KeyConditionExpression: "username = :user",
    ExpressionAttributeValues: {
      //username entered in jade form
      ":user":{"S": username}
           }
      };
      //querying dynamodb for username
      dynamodb.query(queryParams,
    function(err,data) {
      if(err)
        console.error(err,err.stack);
        return done(err);

      //if no users with said username in db
      if(data.Count < 1) {
        console.error(username + " not found in db");
        return done(null, false, req.flash("message" , "user not found"));
      }
      //too many entries (admin's fault)
      if(data.Count > 1){
        console.error("error, more than one user with " + username + " in db");
        return done(null,false,req.flash("message", "more than version of the username in the db"));
      } else {
        //only one user exists in db, query for username was successful
        data.Items.forEach(function(item){
        //checking if entered password is wrong
        if(!isValidPassword(item.username, item.password)) {
        console.error("invalid username - password combination");
        return done(null,false,req.flash("message","invalid user-password combination"));
      }  
      //successful login - user and password match
      console.log("login successful");
      return done(null,user);
      });
     }
    });     
  }
));


  var isValidPassword = function(user, password) {
    return bCrypt.compareSync(password,user.password);
  }
}



via Torben

No comments:

Post a Comment