在节点和护照

时间:2018-04-08 21:31:20

标签: node.js express passport.js

我正在尝试在节点应用程序中登录我的用户,使用OrientDB作为数据库并使用节点js和express。我有进口护照实际上采用了我的一个mongo db项目的解决方案。

问题是,当我尝试登录时,我得到[对象,对象]但没有错误。

这就是我的代码:

用户模型文件:

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;

所以在OrientDB中我有一个名为Account的类,它有属性名,电子邮件,密码和id。目前我登录和注册的路线在app.js中(稍后会更改)。

我可以注册,我的密码已成功哈希并且新用户已创建。

我的app.js文件:

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}`);
});

oriento.js文件只是在我的应用程序和OrientDB数据库之间创建数据库连接。以下是代码:

// 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;

最后这是我的passport.js文件:

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)  
        })
    });


}

从代码中可以看出,我能够在serializeUser函数中成功获取用户的所有文件,但deserializeUser中没有任何内容。我猜这个问题不是我的数据库连接,因为我能够创建新用户,让他们的属性到序列化用户。

但它并没有将用户存储在我认为的会话中,并且desirializeUser只返回空白网页上的[object,object],而不是将我带到app.js中定义的索引路径

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

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

请告知我做错了什么。 提前谢谢。

1 个答案:

答案 0 :(得分: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 = {} ...