I've been trying to delete a user in a MySql database using Sequelize ORM but it's not deleting.
without paranoid, here's the query generate:
UPDATE `Users` SET `active`=?,`updatedAt`=? WHERE `id` = ?
with paranoid set to true, here's the query generate:
UPDATE `Users` SET `active`=?,`updatedAt`=? WHERE (`deletedAt` IS NULL AND `id` = ?)
digging around the internet i found out that the the query is supposed to take this form UPDATE "posts" SET "deletedAt"=[timestamp] WHERE "deletedAt" IS NULL AND "id" = 1 accounding to this Documentation.
Here's my model:
'use strict';
const sequelizePaginate = require('sequelize-paginate')
const bcrypt = require('bcrypt')
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
photo: DataTypes.STRING,
firstName: DataTypes.STRING,
lastName: DataTypes.STRING,
email: DataTypes.STRING,
phone: DataTypes.STRING,
password: DataTypes.STRING,
role: DataTypes.STRING,
verifyEmailAt: DataTypes.DATE,
referralCode: DataTypes.STRING,
active: DataTypes.BOOLEAN,
referrer: DataTypes.STRING,
rememberToken: DataTypes.STRING
}, { instanceMethods: {
comparePasswords: (password, prevPassword,callback) => {
bcrypt.compare(password, prevPassword, (error, isMatch) => {
if(error) {
return callback(error);
}
return callback(null, isMatch);
});
}
},
hooks: {
beforeValidate: (user) => {
if(user.changed('password')) {
return bcrypt.hash(user.password, 10).then(function(password) {
user.password = password;
});
}
}
}});
User.associate = (models) => {
// associations can be defined here
models.User.hasMany(models.Booking)
models.User.hasMany(models.DriversLocation)
models.User.hasMany(models.DriverReview)
models.User.hasMany(models.Payment)
};
sequelizePaginate.paginate(User)
return User;
};
And also my query snippet:
const { validationResult } = require('express-validator')
const models = require('../models')
deleteAdmin: (req, res) => {
const result = validationResult(req);
if (!result.isEmpty()) {
return res.status(422).json({ success: false, message: 'input validation failure',
code: 422, properties:{ userId : req.params.userId}, error: result.array() });
}
models.User.destroy({
where: {
id: req.params.userId
}
})
.then((data) => {
return res.status(200).json({ success: true, message: "success",
code: 200, properties:{params: {userId: req.params.userId }},
data: {content: data}});
}).catch((error) => {
return res.status(520).json({ success: false, message: "unknown error",
code: 520, properties:{params: {userId: req.params.userId }},
data: { error: error} });
})
}
Is there something am doing wrong here?
Thank you for your help in advance
destroy usage seems fine to me. Please verify your User model import & req params values.
Also, there is no id field defined in schema definition. How is id being saved in DB record ?
Related
I am a nodeJs developer, I failed to get the list of users, when I tested my code on postman it gives me the error below:
User.find is not a function
The following is my user.js file
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class User extends Model {
static associate(models) {
}
}
User.init({
username: {
type:DataTypes.STRING,
allowNull: false,
},
email: {
type:DataTypes.STRING,
allowNull: false,
},
password: {
type:DataTypes.STRING,
allowNull: false,
},
role: {
type:DataTypes.STRING,
allowNull: false,
},
}, {
sequelize,
tableName:'users',
modelName: 'User',
});
return User;
};
and this is where it's imported/required
const router = require('express').Router();
let User = require('../models/user');
router.route('/getUser').post((req, res) => {
User.find({})
.then(users => res.json(users))
.catch(err => res.status(400).json('Error: ', err));
});
The user.js file that you provided is exporting a function that create the User class (and not actually the User model class)
Did you already init this class elsewhere and you are importing the wrong file ?
It didn't work, I did as you told me but it gives me back:
sequelize id not defined
Also I don't think that the problem is in the model because I have used it before and in the login I used .find and it worked without any problem!
this login code :
router.post('/login', async (req,res,next) => {
const user = await User.findOne({ where: { email: req.body.email }});
if (user) {
const password_valid = await bcrypt.compare(req.body.password,user.password);
if (password_valid) {
token = JWT.sign({
isLogin: true,
"id": user.id,
"email": user.email,
"username": user.username
},"12345678");
res.status(200).json({token :token});
} else {
res.status(400).json({isLogin : false, error: "password incorrect" });
}
} else {
res.status(404).json({isLogin : false, error :"User does not exist"});
}
});
I've defined a user model in Sequelize, and also defined a custom class method and an instance method for it. I'm calling these two methods in my login api (which works fine). The problem is that the class method works perfectly, but the instance method results an error, and I cannot recognize what is wrong with my code. PLEASE HELP.
This is my user model and its methods:
const Sequelize = require("sequelize");
const sequelize = require("../db/db.config");
const bcrypt = require("bcryptjs");
const _ = require("lodash");
const jwt = require("jsonwebtoken");
const User = sequelize.define("user", {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
first_name: {
type: Sequelize.STRING(50),
allowNull: false,
},
last_name: {
type: Sequelize.STRING(50),
allowNull: false,
},
email: {
type: Sequelize.STRING(50),
allowNull: false,
validate: {
isEmail: true,
},
},
password: {
type: Sequelize.STRING(100),
allowNull: false,
},
});
User.prototype.testMethod = function () {
console.log("THIS IS A TEST");
};
User.beforeCreate(async (user, options) => {
const hashedPassword = await bcrypt.hash(user.password, 10);
user.password = hashedPassword;
});
User.findByEmailAndPassword = async function (inputEmail, inputPassword) {
try {
const user = await User.findOne({ where: { email: inputEmail } });
if (user === null) {
return null;
}
const passwordMatch = await bcrypt.compare(inputPassword, user.password);
if (!passwordMatch) {
return null;
}
return _.pick(user, "id", "first_name", "last_name", "email");
} catch (error) {
console.log("FIND BY EMAIL AND PASSWORD ERROR: ", error);
}
};
module.exports = User;
And this is my login router:
const express = require("express");
const router = express.Router();
const User = require("../models/user.model");
router.post("/api/login", async (req, res) => {
try {
const user = await User.findByEmailAndPassword(
req.body.email,
req.body.password
);
console.log("USER: ", user);
await user.testMethod();
if (!user) {
return res.status(400).send({
errorMessage: "Username and password combination is not correct!",
});
}
return res.status(200).send(user);
} catch (error) {
res.status(400).send({ errorMessage: error });
}
});
module.exports = router;
Thanks.
First, the reason that you get the issue is that findByEmailAndPassword is returning the regular object from _.pick and you are defining the instance method for Sequelize instance. This instance method can be callable on Sequelize instance and not on regular object.
However, your goal is
What I'm trying to do here is to avoid sending user password in my response body.
defaultScope is great for this use case. It allows you to define some repetitive options on a model.
You can define your User model as
const User = sequelize.define("user", {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
...
}, {
defaultScope: {
attributes: {
exclude: ['password']
}
}
});
Defining the defaultScope on the model, this will be applied to many Sequelize functions by default.
Scopes apply to .find, .findAll, .count, .update, .increment and .destroy.
I also tested that it also applied to .findByPk, .findOne.
So, how to use...
Call regular Sequelize findOne function.
const user = User.findOne({
where: {
email: req.body.email,
password: req.body.password
}
});
By default, since defaultScope is applied, this won't return password in response.
In some scenarios where you need to return the password, use unscoped to disable the defaultScope.
// This will return `password` in response.
User.unscoped().fineOne(...)
For reference: https://sequelize.org/master/manual/scopes.html
Right now I'm hashing the password on the route function and providing the hash when creating the user but I know there's a way to have this be handled through Sequelize itself. I have searched around but every answer seems to be outdated or the methods never got called. Here is my config:
server/models/User.js
module.exports = (sequelize, type) => {
const User = sequelize.define(
"User",
{
user_id: {
type: type.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: type.STRING,
allowNull: false
},
email: {
type: type.STRING,
allowNull: false
},
password: {
type: type.STRING,
allowNull: false
},
reg_date: {
type: type.DATEONLY,
allowNull: false,
defaultValue: sequelize.fn("now")
}
},
{
timestamps: false
}
);
return User;
};
server/config/sequelize.js
const Sequelize = require("sequelize");
const sequelize = new Sequelize(process.env.CLEARDB_DATABASE_URL);
sequelize
.authenticate()
.then(() => {
console.log("Connection has been established successfully.");
})
.catch(err => {
console.error("Unable to connect to the database:", err);
});
const UserModel = require("../models/User");
const User = UserModel(sequelize, Sequelize);
module.exports = User;
This is how I'm handling hashing right now:
server/routes/register.js
User.findOne({ where: { email: email } }).then(user => {
if (!user) {
bcrypt.hash(password, 10, (err, hash) => {
if (err) throw err;
User.create({
name: req.body.name,
email: email,
password: hash
})
.then(user => {
return user;
})
.catch(err => console.log(err));
});
}
});
This did the trick:
...
{
timestamps: false
}
);
User.addHook(
"beforeCreate",
user => (user.password = bcrypt.hashSync(user.password, 10))
);
return User;
};
Please don't mix your model definition with a business or a security logic (or another one). In future you might want to change an encryption library or a hashing algorithm and you will have to change your model accordingly. A security layer should be separated from your models.
am building an app with nodes qraphQl using apollo, am trying to do a login page, but ater signing up and and i try to sign in, my bcrypt would always return false,
in my user model
import bcrypt from 'bcryptjs';
const user = (sequelize, DataTypes) => {
const User = sequelize.define('user', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
unique: true,
primaryKey: true,
field: 'id'
},
fullname: DataTypes.STRING,
username: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notEmpty: true,
},
},
email: {
type: DataTypes.STRING,
allowedNull: false,
validate: {
notEmpty: true,
isEmail: true,
}
},
password: {
type: DataTypes.STRING,
allowedNull: false,
validate: {
notEmpty: true,
len: [7, 42],
},
},
role: {
type: DataTypes.ENUM,
values: ['ADMIN', 'INSTRUCTOR', 'STUDENT'],
defaultValue: 'STUDENT'
}
});
User.beforeCreate(async user => {
user.password = await user.generatePasswordHash()
});
User.beforeSave(async user => {
user.password = await user.generatePasswordHash()
});
User.prototype.generatePasswordHash = async function() {
const saltRounds = 10;
return await bcrypt.hash(this.password, saltRounds)
};
User.prototype.validatePassword = async function(password) {
return await bcrypt.compare(password, this.password);
};
User.associate = models => {
User.hasMany(models.Message, { onDelete: 'CASCADE' });
};
User.findByLogin = async login => {
let user = await User.findOne({
where: { username: login },
});
if (!user) {
user = await User.findOne({
where: { email: login },
});
}
return user;
};
return User;
};
export default user;
And in my users resolver, here is the code
import { combineResolvers } from 'graphql-resolvers';
import Joi from 'joi'
import { isAuthenticated, isAdmin } from './authorization';
import {SignUp, SignIn} from '../functions/joi'
import {createToken} from '../functions/jwt'
export default {
Mutation: {
signUp: async (parent, { username, fullname, email, password, Rpassword}, { models, secret }) => {
if(password !== Rpassword){
return new Error('Password did not match')
}
var thejoi = { username, fullname, email, password }
const checkUserEm = await models.User.find({ where: { email: email }})
if (checkUserEm) {
return new Error('Email address already Exist')
}
const checkUserUs = await models.User.find({ where: { username: username }})
if (checkUserUs) {
return new Error('Username already Exist')
}
await Joi.validate(thejoi, SignUp, {abortEarly:false})
const user = await models.User.create({
username,
fullname,
email,
password,
role:'STUDENT'
});
return { token: createToken(user) };
},
signIn: async (parent, { login, password }, { models, secret }, ) => {
var varrh = { password }
await Joi.validate(varrh, SignIn, {abortEarly:false})
const user = await models.User.findByLogin(login);
if (!user) {
return new Error('No user found with this login credentials.');
}
const isValid = await user.validatePassword(password);
if (!isValid) {
return new Error('Invalid password .');
}
return { token: createToken(user) };
}
},
User: {
messages: async (user, args, { models }) => {
return await models.Message.findAll({
where: {
userId: user.id
}
});
},
},
}
pls am really confused because its it suppose to work, i have searched google but it didnt help me, pls how can i solve this issue thanks
inside generatePasswordHash you referencing to this, but you also using arrow functions for beforeCreate and beforeSave hooks.
Two options:
Do not use arrow function for beforeCreate and beforeSave hooks.
User.beforeCreate(async function (user) {
user.password = await user.generatePasswordHash()
});
User.beforeSave(async function (user) {
user.password = await user.generatePasswordHash()
});
Provide user object to generatePasswordHash and replace this with user.
User.beforeCreate(async user => {
user.password = await user.generatePasswordHash(user)
});
User.beforeSave(async user => {
user.password = await user.generatePasswordHash(user)
});
User.prototype.generatePasswordHash = async function(user) {
const saltRounds = 10;
return await bcrypt.hash(user.password, saltRounds)
};
I have a route for creating users in Node/Express. I am getting a weird error about a method on the model not existing.
Here is the model for users:
'use strict';
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
mongoose.Promsie = global.Promise;
const UserSchema = mongoose.Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
email: { type: String, required: true },
firstName: { type: String },
lastName: { type: String },
families: [
{
family_key: { type: String, required: true },
family_name: { type: String }
}
]
});
UserSchema.methods.apiRepr = function() {
return {
id: this._id,
firstName: this.firstName,
lastName: this.lastName,
username: this.username,
email: this.email,
families: this.families
};
};
UserSchema.methods.hashPassword = function(password) {
return bcrypt.hash(password, 10);
}
UserSchema.methods.validatePassword = function(password) {
return bcrypt.compare(password, this.password);
}
const User = mongoose.models.User || mongoose.model('User', UserSchema);
module.exports = { User };
Not particularly complicated. BUT, my the route is having trouble with the "hashPassword" method. When I try to use this route, I get an error that says "TypeError: User.hashPassword is not a function"
Here is the route (the issue is close to the bottom):
router.post('/', jsonParser, (req, res) => {
// checking that required fields are present
const requiredFields = ['username', 'password', 'email'];
const missingField = requiredFields.find(field => !(field in req.body));
if(missingField) {
return res.status(422).json({
code: 422,
reason: 'Validation Error',
message: 'Missing field',
location: missingField
});
}
// checking the format of string fields
const stringFields = ['username', 'password', 'email', 'lastname', 'firstname'];
const nonStringField = stringFields.find(
field => field in req.body && typeof req.body[field] !== 'string'
);
if (nonStringField) {
return res.status(422).json({
code: 422,
reason: 'Validation Error',
message: 'Incorrect field type: expected string',
location: nonStringField
});
}
// checking the trimming on fields
const trimmedFields = ['username', 'password', 'email'];
const nonTrimmedField = trimmedFields.find(
field => req.body[field].trim() !== req.body[field]
);
if (nonTrimmedField) {
return res.status(422).json({
code: 422,
reason: 'Validation Error',
message: 'Cannot start or end with whitespace',
location: nonTrimmedField
});
}
// checking length of fields with required length
const sizedFields = {
username: { min: 1 },
password: { min: 10, max: 72 }
};
const tooSmallField = Object.keys(sizedFields).find(field =>
'min' in sizedFields[field] &&
req.body[field].trim().length < sizedFields[field].min
);
const tooLargeField = Object.keys(sizedFields).find(field =>
'max' in sizedFields[field] &&
req.body[field].trim().length > sizedFields[field].max
);
if (tooSmallField || tooLargeField) {
return res.status(422).json({
code: 422,
reason: 'Validation Error',
message: tooSmallField
? `Must be at least ${sizedFields[tooSmallField].min} characters long`
: `Must be at most ${sizedFields[tooLargeField].max} characters long`,
location: tooSmallField || tooLargeField
});
}
// creating the user
let { username, firstname, lastname, families, email, password } = req.body;
return User.find({ username })
.count()
.then(count => {
if(count > 0) {
return Promise.reject({
code: 422,
reason: 'Validation Error',
message: 'Username already taken',
location: 'username'
});
}
return User.hashPassword(password);
})
.then(hash => {
return User.create({ username, firstname, lastname, families, email, password: hash })
})
.then(user => {
return res.status(201).json(user.apiRepr());
})
.catch(err => {
console.error(err)
res.status(500).json({ code: 500, message: 'Internal server error'})
})
})
It does not like the return User.hashPassword(password) part. Any thoughts about what is causing this? I'm copying from a working app. Not sure what I'm doing wrong here.
The methods in node.js can not be used directly using the SchemaName you need to create an object of the schema name and then use the methods of the schema.
Ex:
var AnimalSchema = new Schema({
name: String
, type: String
});
AnimalSchema.methods.findSimilarType = function findSimilarType (cb) {
return this.model('Animal').find({ type: this.type }, cb);
};
var Animal = mongoose.model('Animal', AnimalSchema);
var dog = new Animal({ name: 'Rover', type: 'dog' });
dog.findSimilarType(function (err, dogs) {
if (err) return ...
dogs.forEach(..);
})
Source: http://mongoosejs.com/docs/2.7.x/docs/methods-statics.html
In your code you are trying to access the methods from the model.
Instantiate the model then use the methods.
If need use like the way you are using in the code try using function instead of methods.
module.exports.funtionName = function(/*function params*/){
//function body here
};