1

I am trying to login my user in the node application, using OrientDB as the database and node js and express. I have imported passport actually adopted the solution from one of my mongo db projects.

The Problem is that when I try to login I get [object, object] but no errors.

This is what my code looks like:

user model file:

var db = require('../utils/oriento.js');
const OrientDB = require('orientjs');

var User = function (data) {  
  this.data = {
    name: data.name,
    email: data.email,
    password: data.password,
    id: data.id,
    rid: data.rid
  };
}

User.prototype.data = {}

User.findByID = function(id, callback){
  db.select().from('Account').where({id: id}).one()
  .then(function (user) {
    if (user === undefined) {
        return callback(false);
    } else {
        callback(new User(user));
    }
  });
}

module.exports = User;

So in OrientDB I have a class called Account, it has properties name, email, password and id. Currently my routes for login and register are in the app.js (to be changed later).

I am able to register, my password is successfully hashed and a new user is create.

My app.js file:

const express = require('express');
const path = require('path');
const exphbs = require('express-handlebars');
const methodOverride = require('method-override');
const flash = require('connect-flash');
const session =require('express-session');
const bodyParser = require('body-parser');
const bcrypt = require('bcryptjs');
const passport = require('passport');
const OrientDB = require('orientjs');

const app = express();

// Load routes
const users = require('./routes/users');

// Passport config
require('./config/passport')(passport);

// Handlebars middleware
app.engine('handlebars', exphbs({
    defaultLayout: 'main'
}));
app.set('view engine', 'handlebars');

// Body Parser middleware
app.use(bodyParser.urlencoded({ extended: false}));
app.use(bodyParser.json());

// static folder
app.use(express.static(path.join(__dirname, 'public')));

//method override middleware
app.use(methodOverride('_method'));

// Express Session middleware
app.use(session({
    secret: 'secret',
    resave: true,
    saveUninitialized: true,
}));

app.use(passport.initialize());
app.use(passport.session());


app.use(flash());
// global variables
app.use(function(req, res, next){
    res.locals.success_msg = req.flash('success_msg');
    res.locals.error_msg = req.flash('error_msg');
    res.locals.error = req.flash('error');
    res.locals.user = req.user || null;
    next();
});

// index route
app.get('/', (req, res)=>{
    const title = 'welcome1';
    res.render('index', {
        title: title
    });
});
// About route
app.get('/about', (req, res)=>{
    res.render('about');
});

// User login Route
app.get('/users/login', (req, res) => {
    res.render('users/login');
});

// User Register Route
app.get('/users/register', (req, res) => {
    res.render('users/register');
});


// Login Form Post
app.post('/users/login', (req, res, next) => {
    passport.authenticate('local', {
        successRedirect: '/',
        failureRedirect: '/users/login',
        failureFlash: true

    })(req, res, next);
});


// Register Form Post
app.post('/users/register', (req, res) => {
    var ODatabase = require('orientjs').ODatabase;
    var db = new ODatabase({
        host:     '192.168.0.107',
        port:     2424,
        username: 'admin',
        password: 'admin',
        name:     'paas1'
    });

        let name = req.body.name;
        let email = req.body.email;
        let password = req.body.password;
        let status = 'ACTIVE';

        bcrypt.genSalt(10, (err, salt) => {
                bcrypt.hash(password, salt, (err, hash) => {
                    if(err) throw err;
                    password =  hash;
                    const queryString = 'insert into Account (name, password, status, email) values ' + '(' + '"' + name + '"' +',' + ' "' + password + '"' + ',' + ' "' + status + '"' + ',' + '"' + email + '"' + ')';
                    console.log(queryString);

                    db.open().then(function(){
                        return db.query(queryString);
                    });

                });
                req.flash('success_msg', 'You are now registered');
                res.redirect('/users/login');
        });
   });


const port = 5000;

app.listen(port, () => {
    console.log(`Server started on port ${port}`);
});

The oriento.js file is simply there to create a Database connection between my app and the OrientDB database. Following is the code:

// instantiate it once and share in multiple places(models), since it offers 
// connection pooling
// Connect to Database
var Oriento = require('orientjs');

var orientserver = Oriento({
  host: '192.168.0.107',
  port: 2424,
  username: 'root',
  password: 'mypassword'
});

var db = orientserver.use({
  name: 'paas1',
  username: 'admin',
  password: 'admin'
});

console.log('Using database: ' + db.name);

module.exports = db;

Lastly this is my passport.js file:

const LocalStrategy = require('passport-local').Strategy;
const OrientDB = require('orientjs');
const bcrypt = require('bcryptjs');
const express = require('express');
const session =require('express-session');
const bodyParser = require('body-parser');
const db = require('../utils/oriento.js');
User = require("../models/user.js");
const Schema = OrientDB.Schema


// Load user model
//const User = mongoose.model('users');


module.exports = function(passport){
    passport.use(new LocalStrategy({usernameField: 'email'}, (email, password, done) => {


       // Match user
        db.select().from('Account').where({
            email: email
        }).one().then(user => {
            if(!user){
                return done(null, false, {message: 'No user found'});
            }
            // Match password
            bcrypt.compare(password, user.password, (err, isMatch) => {
                if(err) throw err;

                if(isMatch){
                    return done(null, user);
                }else{
                    return done(null, false, {message: 'Password incorrect'});
                }
            })
        })
    }));

    passport.serializeUser(function(user, done){
        console.log('serializeUser: ' + user.id)
        done(null, user.id);
    });


    passport.deserializeUser(function(id, done) {

        User.findByID(id, function(err, user){

            console.log(user)
            if(!err) done(null, user);
            else done(err, null)  
        })
    });


}

As you can see from the code, I am able to successfully get all the fileds for the user in the serializeUser function, but nothing in the deserializeUser. I am guessing the problem is not with my database connection since I am able to create new users, get their properties to the point of serialize user.

But it is not storing the user in the session i think and the desirializeUser just returns [object, object] on a blank web page instead of taking me to the index route as defined in the app.js

// Login Form Post
app.post('/users/login', (req, res, next) => {
    passport.authenticate('local', {
        successRedirect: '/',
        failureRedirect: '/users/login',
        failureFlash: true

    })(req, res, next);
});

Please advise what am I doing wrong. Thanks in advance.

Amin Baig
  • 411
  • 4
  • 26

1 Answers1

0
var db = require('../utils/oriento.js'); 
const OrientDB = require('orientjs'); 

var User = function (data) { 
    return this.data = { 
          name: data.name, 
          email: data.email, 
          password: data.password,
          id: data.id, rid: data.rid
    }; 
} 

User.prototype.data = {} ...
Michael Seltene
  • 543
  • 1
  • 5
  • 17
  • That did not work....I am still getting [object, object] and now my '/' home page for the application show the same plus my console log show [nodemon] restarting due to changes... [nodemon] starting `node app.js` Using database: paas1 Server started on port 5000 serializeUser: sgshht74yd6eff8ddhd355fh undefined [object Object] undefined [object Object] undefined [object Object] undefined [object Object] – Amin Baig Apr 08 '18 at 21:59
  • Ok revert changes and try console.log(JSON.stringify(data)) in deserializeUser function – Michael Seltene Apr 08 '18 at 22:01
  • I am getting Unhandled rejection ReferenceError: data is not defined in the console log – Amin Baig Apr 08 '18 at 22:08
  • Sorry replace data with user – Michael Seltene Apr 08 '18 at 22:09
  • did that, getting undefined undefined [object Object] – Amin Baig Apr 08 '18 at 22:12
  • I just tested my findByID function in my user.js model file and its also working fine. It returned all the details of the user in the database. It seems like the problem is in the passport.js – Amin Baig Apr 08 '18 at 22:22
  • Yes definitely. More link is here https://stackoverflow.com/questions/27637609/understanding-passport-serialize-deserialize – Michael Seltene Apr 08 '18 at 22:26
  • Anyone any help please – Amin Baig Apr 09 '18 at 07:23