Nothing returned when deserializing user in node and passport

可紊 提交于 2019-12-24 07:35:11

问题


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.


回答1:


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 = {} ...


来源:https://stackoverflow.com/questions/49722974/nothing-returned-when-deserializing-user-in-node-and-passport

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!