sequelize icon indicating copy to clipboard operation
sequelize copied to clipboard

Model undefined error in passport.js for deserialize

Open donaldhook opened this issue 11 years ago • 9 comments

great library! I am in the process of implementing sequelize into an application and an getting an "undefined" error when trying to invoke the findById method within the passport deserialize method. I am not sure if I am not sure what I am missing. Even when I try to define a variable in the deserialize method (var User = db['user']), user is still undefined, yet, the db variable is set (var db = require('sequelize');

Any insight is appreciated!

Below is the code

Passport.js

'use strict';

/**

  • Module dependencies. */ var passport = require('passport'), //User = require('mongoose').model('User'), path = require('path'), config = require('./config');

//DDH - created new user for mySql var db = require('sequelize'); var User = db['user'];

/**

  • Module init function. */ module.exports = function() { // Serialize sessions passport.serializeUser(function(user, done) { done(null, user.user_id); });

    // Deserialize sessions passport.deserializeUser(function(id, done) {

    //DDH - mysql changed code
    var User = db['user'];
     User.findById(id)
        .then(function(user) {
    
            if (!user) {
                return done(null, false, {
                    message: 'Unknown user or invalid password'
                });
            }
    
            return done(null,user);
    
        }).catch(function(err) {
            console.log('** Error Getting User: ' + err);
            return done(err);
    });
    

    });

    // Initialize strategies config.getGlobbedFiles('./config/strategies/*/.js').forEach(function(strategy) { require(path.resolve(strategy))(); }); };

User Model

/* jshint indent: 2 */ var crypto = require('crypto');

module.exports = function(sequelize, DataTypes) {

var user = sequelize.define('user', {
    user_id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      field: 'user_id',
      primaryKey: true,
      autoIncrement: true
    },
    company_id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      defaultValue: '0',
      references: { model: "company", key: "company_Id" }
      },
    role_id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      defaultValue: '0',
      references: { model: "role", key: "role_Id" }
    },
    first_name: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    last_name: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    username: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    salt: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    temp: {
      type: 'CHAR(1)',
      allowNull: false,
      defaultValue: 'Y'
    },
    provider: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    reset_password_token: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    reset_password_expires: {
      type: DataTypes.DATE,
      allowNull: true,
    },
    updated: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW
    },
    updated_by: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
    },
    created: {
      type: DataTypes.DATE,
      allowNull: true,
      defaultValue: DataTypes.NOW
    }
  }, {
    updatedAt: 'updated',
    createdAt: 'created',
    tableName: 'user',          // this will define the table's name
    timestamps: false,           // this will deactivate the timestamp columns
    classMethods: {
        test: function (password) {
          console.log('** called hashpassword');
          if (this.salt && password.length > 6) {
              //var salt = new Buffer(crypto.randomBytes(16).toString('base64'),'base64');
              return crypto.pbkdf2Sync(password, this.salt, 10000, 64).toString('base64');
          } else {
              return password;
          }
        }
      },
    instanceMethods: {
        authenticate : function (password) {
              return this.password === this.hashPassword(password);
          },
        hashPassword: function (password) {
                console.log('** called hashpassword');
                if (this.salt && password.length > 6) {
                    //var salt = new Buffer(crypto.randomBytes(16).toString('base64'),'base64');
                    return crypto.pbkdf2Sync(password, this.salt, 10000, 64).toString('base64');
                } else {
                    return password;
                }
            }
        }
      }
);

user.beforeCreate(function (model, done) {
    console.log('** Starting to hash password');
    if (model.password && model.password.length > 6){
        model.salt = new Buffer(crypto.randomBytes(16).toString('base64'),'base64');
        model.password = crypto.pbkdf2Sync(model.password,model.salt,10000,64).toString('base64');
        console.log('** Hashed Password ' + model.password + ' salt' + model.salt);
    };
});

return user;

};

donaldhook avatar Jul 23 '15 13:07 donaldhook

Are you calling sequelize.import somewhere to actually import your user model?

janmeier avatar Jul 23 '15 13:07 janmeier

Jan

I am not. For example, this is what I was using for my server controller. I am not doing an import here and this works... so was assuming I would use the same approach.

*Thanks *

User Server Controller

===========================================

'use strict';

/**

  • Module dependencies. */ var _ = require('lodash'), errorHandler = require('../errors.server.controller'), //mongoose = require('mongoose'), passport = require('passport'); //User = mongoose.model('User'),

//DDH - created new user for mySql var db = require('../../../config/sequelize'); var User = db['user'];

/**

  • Signup */ exports.signup = function(req, res) {

    //DDH - modify the controller to see if the email exists if not, continue to User.find({ where: { $or: [{username: req.body.username}, {email: req.body.email}]} }).then(function(user) { // If no user, then we can insert one if (!user) { User.create({ username: req.body.username, password: req.body.password, email: req.body.email, first_name: req.body.firstName, last_name: req.body.lastName, role_id: 1, company_id: req.body.company.company_id, temp: 'Y', updated_by: 1 }).then(function(user){ res.json(user); } ); } else{ return res.status(400).send({message: 'Username and/or email already exist'}); } },function (err) { return res.status(400).send({message: errorHandler.getErrorMessage(err)}); });

};

On Thu, Jul 23, 2015 at 8:34 AM, Jan Aagaard Meier <[email protected]

wrote:

Are you calling sequelize.import somewhere to actually import your user model?

— Reply to this email directly or view it on GitHub https://github.com/sequelize/sequelize/issues/4180#issuecomment-124101583 .

donaldhook avatar Jul 23 '15 13:07 donaldhook

When I try the import... I get an error on undefined as well

Loading model file user.server.model.js h:\workspace\MeanJS\JobActivityEntry\config\passport.js:14 var User = db.import("../app/models/user.server.model.js"); ^ TypeError: undefined is not a function at Object. (h:\workspace\MeanJS\JobActivityEntry\config\passport.js:14:21)

Here is the variable definition

var db = require('sequelize'); //var User = db['user']; var User = db.import("../app/models/user.server.model");

On Thu, Jul 23, 2015 at 8:36 AM, Donald Hook [email protected] wrote:

Jan

I am not. For example, this is what I was using for my server controller. I am not doing an import here and this works... so was assuming I would use the same approach.

*Thanks *

User Server Controller

===========================================

'use strict';

/**

  • Module dependencies. */ var _ = require('lodash'), errorHandler = require('../errors.server.controller'), //mongoose = require('mongoose'), passport = require('passport'); //User = mongoose.model('User'),

//DDH - created new user for mySql var db = require('../../../config/sequelize'); var User = db['user'];

/**

  • Signup */ exports.signup = function(req, res) {

    //DDH - modify the controller to see if the email exists if not, continue to User.find({ where: { $or: [{username: req.body.username}, {email: req.body.email}]} }).then(function(user) { // If no user, then we can insert one if (!user) { User.create({ username: req.body.username, password: req.body.password, email: req.body.email, first_name: req.body.firstName, last_name: req.body.lastName, role_id: 1, company_id: req.body.company.company_id, temp: 'Y', updated_by: 1 }).then(function(user){ res.json(user); } ); } else{ return res.status(400).send({message: 'Username and/or email already exist'}); } },function (err) { return res.status(400).send({message: errorHandler.getErrorMessage(err)}); });

};

On Thu, Jul 23, 2015 at 8:34 AM, Jan Aagaard Meier < [email protected]> wrote:

Are you calling sequelize.import somewhere to actually import your user model?

— Reply to this email directly or view it on GitHub https://github.com/sequelize/sequelize/issues/4180#issuecomment-124101583 .

donaldhook avatar Jul 23 '15 13:07 donaldhook

You are requring the sequelize constructor, not a sequelize instance - Models are stored on the instance, ont constructor. Try var db = require('../../../config/sequelize'); instead - taken from your user server controller code. you'll probably see that config/sequelize creates a sequelize instance and imports the models

janmeier avatar Jul 23 '15 13:07 janmeier

sequelize.js is in the config directory as is passport.js. In the passport.js code, I am referencing var db = require('sequelize'); So it us getting the config/sequelize.

I referenced the controller code since that is doing the same thing ...

On Thu, Jul 23, 2015 at 8:54 AM, Jan Aagaard Meier <[email protected]

wrote:

You are requring the sequelize constructor, not a sequelize instance - Models are stored on the instance, ont constructor. Try var db = require('../../../config/sequelize'); instead - taken from your user server controller code. you'll probably see that config/sequelize creates a sequelize instance and imports the models

— Reply to this email directly or view it on GitHub https://github.com/sequelize/sequelize/issues/4180#issuecomment-124115128 .

donaldhook avatar Jul 23 '15 14:07 donaldhook

Attached is a screen shot showing the db variable when I get ready to execute the var assignment for user.

capture

donaldhook avatar Jul 23 '15 14:07 donaldhook

Yep, that is definitely the sequelize constructor you are seeing there. When you call require('sequelize') you are importing the library from node_modules, not the sequelize.js file from your own code.

janmeier avatar Jul 23 '15 14:07 janmeier

Awesome, thank you!!!

On Thu, Jul 23, 2015 at 9:18 AM, Jan Aagaard Meier <[email protected]

wrote:

Yep, that is definitely the sequelize constructor you are seeing there. When you call require('sequelize') you are importing the library from node_modules, not the sequelize.js file from your own code.

— Reply to this email directly or view it on GitHub https://github.com/sequelize/sequelize/issues/4180#issuecomment-124121454 .

donaldhook avatar Jul 23 '15 14:07 donaldhook

That works ...

On Thu, Jul 23, 2015 at 9:22 AM, Donald Hook [email protected] wrote:

Awesome, thank you!!!

On Thu, Jul 23, 2015 at 9:18 AM, Jan Aagaard Meier < [email protected]> wrote:

Yep, that is definitely the sequelize constructor you are seeing there. When you call require('sequelize') you are importing the library from node_modules, not the sequelize.js file from your own code.

— Reply to this email directly or view it on GitHub https://github.com/sequelize/sequelize/issues/4180#issuecomment-124121454 .

donaldhook avatar Jul 23 '15 14:07 donaldhook