Cannot create a mysql entry using nodejs and mysql - mysql

I have a simple node service that should add a db entry to my mysql Users table.
With console log statements, I confirmed that the endpoint is receiving the correct parameter values from the client for username, password and email. However, the entry is not added to my db. I also see in the node logs that the mySQL query appears to ultimately include question marks rather than the actual parameter values. What am I missing here?
My create user query is defined in this file, usercontroller.js
const db = require("../models");
const User = db.users;
const Op = db.Sequelize.Op;
const util = require("util");
var AWS = require("aws-sdk");
const { resolve } = require("path");
const { rejects } = require("assert");
var s3 = new AWS.S3({
accessKeyId: "************",
secretAccessKey: "*************",
region: "us-east-2",
});
// Create and Save a new User
exports.create = (req, res) => {
console.log("creating user");
const username = req.body.username;
const password = req.body.password;
const email = req.body.email;
console.log('username: ' + username)
console.log('password: ' + password)
console.log('email: ' + email)
User.create({
username: username,
email: email,
password: password,
})
.then((data) => {
console.log('data: ' + JSON.stringify(data))
res.send(data);
})
.catch((err) => {
res.status(500).send({
message: err.message || "Some error occurred while creating user.",
});
});
};
This is the output log of calling the create user function above...
creating user
username: A
password: c
email: B
Executing (default): INSERT INTO `Users` (`id`,`username`,`password`,`email`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?,?,?,?);
Here is my index.js file...
const dbConfig = require("../config/db.config.js");
const Sequelize = require("sequelize");
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.dialect,
operatorsAliases: false,
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
}
});
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.users = require("./users.model.js")(sequelize, Sequelize);
module.exports = db;
and user.model.js...
module.exports = (sequelize, Sequelize) => {
const User = sequelize.define("User", {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
firstname: {
type: Sequelize.STRING
},
lastname: {
type: Sequelize.STRING
},
username: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
skill_level: {
type: Sequelize.STRING
},
location: {
type: Sequelize.STRING
},
country: {
type: Sequelize.STRING
},
instagram_username: {
type: Sequelize.STRING
},
facebook_username: {
type: Sequelize.STRING
},
profile_image: {
type: Sequelize.STRING
},
country_code: {
type: Sequelize.STRING
},
age: {
type: Sequelize.INTEGER
},
bio: {
type: Sequelize.TEXT
}
});
return User;
};

Related

How do I skip the primary key auto increment in nodejs ORM sequelize when unique constraint error occurs

How do I skip the primary key auto increment in sequelize node.js when unique constraint error occurs
When I enter same username twice that was defined as unique into mysql by using of Postman my program is running correct way but the problem is the incremental primary key is still continuing.
For example
when I insert another different username value the program is jumping at one of the sequential primary key as expected.
So that, How can I stop the auto increment id as I restricted not to insert duplicate username values in my database
/* DATABASE CONFIGURATION FILE */
const { Sequelize, QueryTypes, DataTypes, Op, UniqueConstraintError, ValidationErrorItem } = require(`sequelize`);
const sequelize = new Sequelize(`tutorialdb`, `root`, ``, {
host: `localhost`,
dialect: `mysql`,
logging: true,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000,
},
});
sequelize
.authenticate()
.then(() => {
console.log(`Connection has been established successfully...`);
})
.catch((err) => {
console.log(`Unable to connect to the database: `, err);
});
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.QueryTypes = QueryTypes;
db.DataTypes = DataTypes;
db.Op = Op;
db.ValidationErrorItem = ValidationErrorItem;
db.UniqueConstraintError = UniqueConstraintError;
db.postModel = require(`../models/post.model.jsx`)(sequelize, DataTypes);
db.sequelize.sync({ force: false, alter: false, match: /tutorialdb$/ }).then(() => {
console.log(`Tables were synced successfully`);
});
module.exports = db;
/* Model definition File */
module.exports = (sequelize, DataTypes) => {
const Post = sequelize.define(
`post`,
{
id: {
type: DataTypes.INTEGER.UNSIGNED,
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
title: {
type: DataTypes.STRING(30),
allowNull: false,
validate: {
notEmpty: {
args: true,
msg: `Title is required`,
},
len: {
args: [3, 50],
msg: `Title must between 3 and 30 characters`,
},
},
},
text: {
type: DataTypes.STRING(100),
allowNull: false,
validate: {
notEmpty: {
args: true,
msg: `Text is required`,
},
len: {
args: [5, 100],
msg: `Text must between 5 and 100 characters`,
},
},
},
username: {
type: DataTypes.STRING(20),
allowNull: false,
unique: true,
validate: {
notEmpty: {
args: true,
msg: `Username is required`,
},
len: {
args: [3, 20],
msg: `Username must between 3 and 20 characters`,
},
},
},
},
{
timestamps: true,
paranoid: true,
}
);
Post.beforeCreate(async (post, options) => {
post.username = post.username.toLowerCase();
});
Post.beforeUpdate(async (post, options) => {
post.username = post.username.toLowerCase();
});
return Post;
};
/* Controller File */
const db = require(`../config/db.config.jsx`);
const postModel = db.postModel;
const Sequelize = db.Sequelize;
const sequelize = db.sequelize;
const QueryTypes = db.QueryTypes;
const DataTypes = db.DataTypes;
const Op = db.Op;
const ValidationErrorItem = db.ValidationErrorItem;
const UniqueConstraintError = db.UniqueConstraintError;
/* Create new Post */
exports.create = async (req, res) => {
const transactions = await sequelize.transaction();
try {
const trim = (noSpace) => {
return noSpace.replace(/\s/g, ``);
};
const post = await postModel.create(
{
title: req.body.title,
text: req.body.text,
username: trim(req.body.username),
},
{ transaction: transactions }
);
await transactions.commit();
res.status(200).json(post);
} catch (err) {
await transactions.rollback();
const messages = {};
let message;
err.errors.forEach((error) => {
messages[error.path] = error.message;
message = messages[error.path];
});
res.status(500).json(message);
}
};
/* Find All posts */
exports.findAll = async (req, res) => {
const transactions = await sequelize.transaction();
try {
const title = req.query.title;
const text = req.query.text;
const username = req.query.username;
let finder = title ? { title: { [Op.like]: `%${title}%` } } : text ? { text: { [Op.like]: `%${text}%` } } : username ? { username: { [Op.like]: `%${username}%` } } : null;
const posts = await postModel.findAll({
as: `posts`,
attributes: [`id`, `title`, `text`, `username`, `createdAt`, `updatedAt`, `deletedAt`],
transaction: transactions,
lock: false,
paranoid: false,
order: [[`id`, `DESC`]],
where: finder,
});
await transactions.commit();
res.status(200).json(posts);
} catch (err) {
await transactions.rollback();
res.status(500).json(err.message);
}
};
/* Router File */
module.exports = (app) => {
const router = require(`express`).Router();
const postCtrl = require(`../controllers/post.controller.jsx`);
router.route(`/post`).post(postCtrl.create).get(postCtrl.findAll);
app.use(`/api/v1`, router);
};
/* MiddleWare Logger File */
const moment = require(`moment`);
/* Create Logger */
const logger = (req, res, next) => {
console.log(`${req.protocol}://${req.get(`host`)}${req.originalUrl} : ${moment().format()}`);
next();
};
module.exports = logger;
/* Server File */
const express = require(`express`);
const cors = require(`cors`);
const logger = require(`./src/middleware/logger.jsx`);
const app = express();
const corsOptions = {
origin: `http://localhost:4001`,
optionsSuccessStatus: 200,
};
app
.use(cors(corsOptions))
.use(logger)
.use(express.json())
.use(express.urlencoded({ extended: false }))
.get(`/`, (req, res) => res.status(200).send(`Welcome to fullstack tutorial application`));
require(`./src/routes/routers.jsx`)(app);
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => console.log(`Server is running on port ${PORT}...`));
The output result is working well. But the primary Key auto-increment is still continuing
http://localhost:4000/api/v1/post : 2022-08-28T11:02:47+03:00
Executing (ac12d76f-d7dc-4040-9692-3d6b853feac9): START TRANSACTION;
Executing (ac12d76f-d7dc-4040-9692-3d6b853feac9): INSERT INTO posts
(id,title,text,username,createdAt,updatedAt) VALUES
(DEFAULT,?,?,?,?,?); Executing (ac12d76f-d7dc-4040-9692-3d6b853feac9):
ROLLBACK;
I had attempted the following solution and works me perfectly.
/* Create new User */
exports.create = async (req, res) => {
const trim = (noSpace) => {
return noSpace.replace(/\s/g, ``);
};
const transactions = await sequelize.transaction();
try {
const { username, password } = req.body;
const users = await userModel.findOne({
where: { username: trim(username) },
transaction: transactions,
});
if (users !== null) {
await transactions.rollback();
res.json(`Username ${username} already exist`);
} else {
const user = await userModel.create(
{
username: trim(username),
password: trim(password),
},
{
transaction: transactions,
}
);
await transactions.commit();
res.status(200).json(user);
}
} catch (err) {
await transactions.rollback();
const messages = {};
let message;
err.errors.forEach((error) => {
messages[error.path] = error.message;
message = messages[error.path];
});
res.status(500).json(message);
}
};
exports.create = async (req, res) => {
const transactions = await sequelize.transaction();
try {
const trim = (noSpace) => {
return noSpace.replace(/\s/g, ``);
};
const [user, created] = await userModel.findOrCreate({
where: { username: trim(req.body.username) },
defaults: { password: trim(req.body.password) },
transaction: transactions,
});
return created ? (await transactions.commit(), res.status(200).json(user)) : user ? (await transactions.rollback(), res.json(`Username already exist`)) : err;
} catch (err) {
await transactions.rollback();
const messages = {};
let message;
err.errors.forEach((error) => {
messages[error.path] = error.message;
message = messages[error.path];
});
res.status(500).json(message);
}
};
I am not sure about issue's existence in previous versions of sequelize. But this issue does not exist if using Object.findOrCreate() with following mentioned versions.
However this issue does appear if using Object.create() method with unique constraint set for field value and not checking field value existence prior to using Object.create() e.g in following code email unique property is set and if user.create() is used for an existing email in db an error is thrown but userid is incremented thus for next successful creation userid is not as expected.
An alternate solution is using user.findOne() prior to use user.create() but out of the scope of this answer and issue can be avoided using object.findOrCreate() as following
Versions: "mysql2": "^2.3.3", "sequelize": "^6.28.0"
To avoid the issue try using following approach
const router = require("express").Router();
const { Sequelize, DataTypes, Model } = require("sequelize");
const dotenv = require("dotenv");
dotenv.config();
const sequelize = new Sequelize(
process.env.MYSQL_DB_NAME,
process.env.MYSQL_DB_USER,
process.env.MYSQL_DB_PASS,
{
host: process.env.MYSQL_DB_HOST,
dialect: "mysql",
}
);
class User extends Model {}
User.init(
{
userid: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
field: "fUserID",
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
field: "fEmail",
},
password: {
type: DataTypes.STRING(1024),
allowNull: false,
field: "fPassword",
},
firstname: {
type: DataTypes.STRING,
field: "fFirstName",
},
lastname: {
type: DataTypes.STRING,
field: "fLastName",
},
metadata: {
type: DataTypes.STRING(2048),
field: "fMetaData",
},
created: {
type: DataTypes.DATE,
field: "fCreated",
},
updated: {
type: DataTypes.DATE,
field: "fUpdated",
},
},
{
sequelize,
tableName: "tbl_user",
timestamps: true,
id: "userid",
createdAt: "created",
updatedAt: "updated",
}
);
router.post("/register", async (req, res) => {
try {
const [user, created] = await User.findOrCreate({
where: { email: req.body.email },
defaults: {
password: req.body.password,
firstname: req.body.firstname,
lastname: req.body.lastname,
metadata: "Any thing",
},
});
if (created === false) return res.status(400).send("email already exist");
res.send(user.toJSON());
} catch (ex) {
res.status(400).send(ex.errors[0].message);
}
});
module.exports = router;

I am not able to connect mysql database to reactjs .I am using nodejs for midddle ware

I made database called oldage_help. In mysql workbench. but i am not able to connect my database to React router by using nodejs as middleware
Database.js
const Sequelize = require("sequelize");
const databaseName = "oldage_help";
const databaseUserName = "root";
const databasePassword = "";
const databaseHost = "localhost";
const sequelize = new Sequelize(
databaseName,
databaseUserName,
databasePassword,
{
dialect: "mysql",
host: "localhost",
}
);
module.exports = sequelize;
app.js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const sequelize = require("./helpers/database");
const User = require("./models/user");
const encryption = require("./helpers/encryption");
const authRoutes = require("./routes/user");
const PORT = 8000;
const app = express();
app.use(cors());
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(authRoutes);
sequelize
.sync() // This will run all the mgirations from the model and create tables in the database.
.then((result) => {
return User.findByPk(1);
})
.then(async (user) => {
if (!user) {
const ecryptedPassword = await encryption.encryptPassword("12345678");
return User.create({
firstName: "admin",
lastName: "admin",
email: "admin#help.com",
address: "some address line with street name in india",
city: "pune",
state: 1,
pincode: 411028,
password: ecryptedPassword,
});
}
return user;
})
.then((user) => {
app.listen(PORT);
})
.catch((err) => console.log(err));
user.js..\controllers
const encryption = require("../helpers/encryption");
const User = require("../models/user");
module.exports = {
register: async function (req, res, next) {
try {
console.log("req.body", req.body);
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const email = req.body.email;
const address = req.body.address;
const address2 = req.body.address2;
const city = req.body.city;
const state = req.body.state;
const pincode = req.body.pincode;
const password = req.body.password;
const ecryptedPassword = await encryption.encryptPassword(password);
const user = await User.create({
firstName: firstName,
lastName: lastName,
email: email,
address: address,
address2: address2,
city: city,
state: state,
pincode: pincode,
password: ecryptedPassword,
});
return user;
} catch (error) {
if (error.name == "SequelizeUniqueConstraintError") {
return {
error: true,
message: "email address already exists",
};
}
return {
error: true,
message: "something went wrong",
};
}
},
login: async function (req, res, next) {
try {
console.log("req.body", req.body);
const email = req.body.email;
const password = req.body.password;
const ecryptedPassword = await encryption.encryptPassword(password);
console.log("email. password", {
email: email,
password: ecryptedPassword,
});
const user = await User.findOne({
where: {
email: email,
},
});
if (user && user.id) {
const isPasswordMatch = await encryption.comparePassword(
password,
user.password
);
if (isPasswordMatch) {
return {
id: user.id,
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
address: user.address,
address2: user.address2,
city: user.city,
state: user.state,
pincode: user.pincode,
};
} else {
return {
error: true,
message: "invalid credentials, no user found with this credentials",
};
}
}
} catch (error) {
return {
error: true,
message: "invalid credentials, no user found with this credentials",
};
}
return {
error: true,
message: "invalid credentials, no user found with this credentials",
};
},
};
user.js../models
const Sequelize = require("sequelize");
const sequelize = require("../helpers/database");
const User = sequelize.define("users", {
id: {
type: Sequelize.BIGINT,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
firstName: {
type: Sequelize.STRING,
allowNull: false,
},
lastName: {
type: Sequelize.STRING,
allowNull: false,
},
email: {
type: Sequelize.STRING,
allowNull: false,
uniqueKey: true,
},
address: {
type: Sequelize.TEXT,
allowNull: false,
},
address2: {
type: Sequelize.TEXT,
allowNull: true,
},
city: {
type: Sequelize.TEXT,
allowNull: false,
},
state: {
type: Sequelize.TEXT,
allowNull: false,
},
pincode: {
type: Sequelize.TEXT,
allowNull: false,
},
password: {
type: Sequelize.TEXT,
allowNull: false,
},
});
module.exports = User;
Not giving such error msg but data is not going to database.I made web frontend through Reactjs and i want connect mysql to reactjs by use of nodejs as middleware.

Sequelize model.create is not a function

I'm new to sequelize and trying to set it up for my new project. I checked some answers on this, but couldnt get past my error. Can someone point out how to fix this.
models/index.js
// Database service
// Connects to the database
const { Sequelize } = require('sequelize');
const path = require('path');
const sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASS, {
host: process.env.DB_HOST,
dialect: 'mysql',
logging: process.env.QUERY_LOGGING == "true" ? console.log : false,
pool: {
max: 10,
min: 0,
acquire: 30000,
idle: 10000
}
});
module.exports = sequelize
models/users.js
const sequelize = require("./index")
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('Users', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
firstName: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING
},
profileURL: {
type: DataTypes.STRING
},
emailId: {
type: DataTypes.STRING,
allowNull: false
},
passwordHash: {
type: DataTypes.STRING,
allowNull: false
},
street: {
type: DataTypes.STRING
},
city: {
type: DataTypes.STRING,
allowNull: false
},
phone: {
type: DataTypes.STRING
},
newsletter: {
type: DataTypes.STRING
},
visibility: {
type: DataTypes.BOOLEAN,
defaultValue: true
},
},{
});
return User;
};
And finally, I'm importing the User model in my service file like below:
const User = require("../models/users")
const createUser = async(req) => {
const {firstName, lastName, profileURL, emailId, passwordHash, street, city, phone, newsletter, visibility} = req.body
const user = await User.create({
firstName,
lastName,
profileURL,
emailId,
passwordHash,
street,
city,
phone,
newsletter,
visibility
})
console.log("new user==>>", user)
return
}
module.exports = { createUser }
However, I get the following error.
TypeError: User.create is not a function
Can someone point out what I could be doing wrong? I realize it could be something minor.
Thank you
You export a function that registers the User model and not the model itself. So you just need to call it passing sequelize instance and DataTypes somewhere like database.js where you will register all models and their associations or directly in models/index.js:
const UserModelConstructor = require("../models/users")
const { DataTypes } = require("sequelize");
...
const UserModel = UserModelConstructor(sequelize, DataTypes);
module.exports = {
sequelize,
User: UserModel
}
You can look at how to register multiple models and association in my other answer here
Please don't forget to remove this line
const sequelize = require("./index")
from models/users.js

error: SequelizeValidationError: string violation: created cannot be an array or an object

I am implementing MERN Stack Login / Registration and trying to test my response in Postman step by step. Firstly, I written the code for Registration then for Login but in case of calling registration link I am getting the following error in postman:
error: SequelizeValidationError: string violation: created cannot be an array or an object
Can someone provide any suggestions to help? I think in User.js findone() function is having some sort of miss from my side.
Could there be any other solution?
./database/DB.js
const db = {}
const sequelize = new Sequelize("mern", "root", "", {
host: "localhost",
dialect: "mysql",
port: "3307",
operatorsAliases: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
})
db.sequelize = sequelize
db.sequelize = sequelize
module.exports = db
./models/User.js
const db = require("../database/db")
module.exports = db.sequelize.define(
'user',
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
first_name: {
type: Sequelize.STRING
},
last_name: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
created: {
type: Sequelize.STRING
}
},
{
timestamps: false
}
);
./routes/User.js
const users = express.Router()
const cors = require('cors')
const jwt = require("jsonwebtoken")
const bcrypt = require('bcrypt')
const User = require("../models/User")
users.use(cors())
process.env.SECRET_KEY = 'secret'
users.post('/register', (req, res) => {
const today = new Date()
const userData = {
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
password: req.body.password,
created: today
}
User.findOne({
where: {
email: req.body.email
}
})
.then(user => {
if(!user){
bcrypt.hash(req.body.password, 10, (err, hash) => {
userData.password = hash
User.create(userData)
.then(user => {
res.json({status: user.email + ' registered'})
})
.catch(err => {
res.send('error: ' + err)
})
})
} else {
res.json({error: "User already exists"})
}
})
.catch(err => {
res.send('error: ' + err)
})
})
users.post('/login', (req, res) => {
User.findOne({
where: {
email: req.body.email
}
})
.then(user => {
if(user) {
if(bcrypt.compareSync(req.body.password, user.password)) {
let token = jwt.sign(user.dataValues, process.env.SECRET_KEY, {
expiresin: 1440
})
res.send(token)
}
} else {
res.status(400).json({error: 'User does not exist'})
}
})
.catch(err => {
res.status(400).json({ error: err})
})
})
module.exports = users
package.json
"name": "login-registration",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^3.0.6",
"bcryptjs": "^2.4.3",
"body-parser": "^1.17.2",
"cors": "^2.8.4",
"express": "^4.16.3",
"jsonwebtoken": "^7.4.2",
"mysql": "^2.14.1",
"mysql2": "^1.6.1",
"nodemon": "^1.18.3",
"sequelize": "^4.38.0"
}
}
Server.js
var cors = require ('cors')
var bodyParser = require("body-parser")
var app = express()
var port = process.env.PORT || 5000
app.use(bodyParser.json())
app.use(cors())
app.use(bodyParser.urlencoded({extended: false}))
var Users = require('./routes/users')
app.use('/users', Users)
app.listen(port, () => {
console.log("Server is running at port: " + port)
})
In ./routes/User.js, under the /post register route, the userData object has a created field with today property which is a Date object.
In ./models/User.js you specify that created should have type Sequelize.STRING.
This is the contradiction that is causing the error. When you call User.create(userData), it gives you that error because the input parameter is of the wrong type.
To fix this, you either need to have created expect a type of Sequlize.Date or convert the today date object to a string.
const today = new Date().toJSON();
There are many different to string functions for the Date class. You should pick the one that best suits you here
This error is as a result of submitting a value of a wrong type compared to the
one declared in the model. Therefore, change it to the appropriate
type which is "JSON" instead of "STRING".
./models/User.js
const db = require("../database/db")
module.exports = db.sequelize.define(
'user',
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
first_name: {
type: Sequelize.STRING
},
last_name: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
created: {
type: Sequelize.JSON
}
},
{
timestamps: false
}
);
Its the "today" attribute that's causing the issue, you are trying to save a date obj instead of string. Change it to string while saving.

TypeError: Cannot read property 'findOne' of undefined while using sequelize in node

I am getting belo mentioned error when trying to make user authentication using passport-local and sequelize for MySQL. When running server it is creating new table in SQL if not already, but as soon as I hit sign up button it is showing error.
Error:
TypeError: Cannot read property 'findOne' of undefined
at Strategy._verify (E:\Web Development\node-SQL-Sequelize-passport-local\config\passport\passport.js:19:13)
at Strategy.authenticate (E:\Web Development\node-SQL-Sequelize-passport-local\node_modules\passport-local\lib\strategy.js:88:12)
at attempt (E:\Web Development\node-SQL-Sequelize-passport-local\node_modules\passport\lib\middleware\authenticate.js:361:16)
at authenticate (E:\Web Development\node-SQL-Sequelize-passport-local\node_modules\passport\lib\middleware\authenticate.js:362:7)
My server.js look like :
app.use(passport.initialize());
app.use(passport.session());
//Models
var models = require("./app/models");
//Routes
var authRoute = require('./app/routes/auth.js')(app,passport);
require('./config/passport/passport.js')(passport, models.user);
//Sync Database
models.sequelize.sync().then(function() {
console.log('Nice! Database looks fine')
}).catch(function(err) {
console.log(err, "Something went wrong with the Database Update!")
});
app.get('/', function(req, res) {
res.send('Welcome to Passport with Sequelize');
});
My user.js file:
module.exports = function(sequelize, Sequelize) {
var User = sequelize.define('userInfo', {
id: {
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
firstname: {
type: Sequelize.STRING,
notEmpty: true
},
lastname: {
type: Sequelize.STRING,
notEmpty: true
},
username: {
type: Sequelize.TEXT
},
about: {
type: Sequelize.TEXT
},
email: {
type: Sequelize.STRING,
validate: {
isEmail: true
}
},
password: {
type: Sequelize.STRING,
allowNull: false
},
last_login: {
type: Sequelize.DATE
},
status: {
type: Sequelize.ENUM('active', 'inactive'),
defaultValue: 'active'
}
});
return User;
}
My passport.js file :
var bCrypt = require('bcrypt-nodejs');
module.exports = function(passport, user) {
var User = user;
var LocalStrategy = require('passport-local').Strategy;
passport.use('local-signup', new LocalStrategy(
{
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true // allows us to pass back the entire request to the callback
},function(req, email, password, done) {
var generateHash = function(password) {
return bCrypt.hashSync(password, bCrypt.genSaltSync(8), null);
};
User.findOne({
where: {
email: email
}
}).then(function(user) {
if (user)
{
return done(null, false, {
message: 'That email is already taken'
});
} else
{
var userPassword = generateHash(password);
var data =
{
email: email,
password: userPassword,
firstname: req.body.firstname,
lastname: req.body.lastname
};
User.create(data).then(function(newUser, created) {
if (!newUser) {
return done(null, false);
}
if (newUser) {
return done(null, newUser);
}
});
}
});
}
));
}
Review this example: github.com/sequelize/express-example. In particular models/index.js for models load.
That way is handled in that example is:
require('./config/passport/passport.js')(passport, models.userInfo);
Because "userInfo" is defined in your model user.js: