Nodejs bcrypt compare not working properly - node.js

I am building an app with nodes qraphQl using apollo and I am trying to do a login page, but after 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 function(user) {
user.password = await user.generatePasswordHash(user)
});
User.beforeSave(async function(user) {
user.password = await user.generatePasswordHash(user)
});
User.prototype.generatePasswordHash = async function(user) {
const saltRounds = 10;
return await bcrypt.hash(user.password, saltRounds)
};
User.prototype.validatePassword = async function(password) {
console.log(this.password)
const theReturn = await bcrypt.compare(password, this.password)
console.log(theReturn)
return theReturn;
};
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
}
});
},
},
}
when i tried to signup, it worked, it stored the hassed password in the database, but when i tried to signIn i got this error message
{
"errors": [
{
"message": "Invalid password .",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"signIn"
],
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"exception": {
"stacktrace": [
"Error: Invalid password .",
" at signIn (C:\\Users\\De Stone Of David\\Desktop\\node projects\\vue\\cybersec\\server\\src\\resolvers\\user.js:65:16)"
]
}
}
}
],
"data": null
}
In the console i got this
Executing (default): INSERT INTO `users` (`id`,`fullname`,`username`,`email`,`password`,`role`,`createdAt`,`updatedAt`) VALUES (DEFAULT,'nsalknlsa','stones4semper','Eloike95#gmail.com','$2a$10$eX8zvI7/EJv6N.2RzbBh9e.qKoJXtmDNDw22nAY6dixTi4btWCB6G','STUDENT','2019-02-17 09:51:44','2019-02-17 09:51:44');
Executing (default): SELECT `id`, `fullname`, `username`, `email`, `password`, `role`, `createdAt`, `updatedAt` FROM `users` AS `user` WHERE `user`.`username` = 'Eloike95#gmail.com' LIMIT 1;
Executing (default): SELECT `id`, `fullname`, `username`, `email`, `password`, `role`, `createdAt`, `updatedAt` FROM `users` AS `user` WHERE `user`.`email` = 'Eloike95#gmail.com' LIMIT 1;
$2a$10$eX8zvI7/EJv6N.2RzbBh9e.qKoJXtmDNDw22nAY6dixTi4btWCB6G
false
Please I am really confused because its suppose to work, i have searched google but it didn't help me, how can i solve this issue? Thanks in advance.

OK so I faced the same problem and the solution is this.
In your user model file
line :- const theReturn = await bcrypt.compare(password, this.password)
here password has already hashed the thing with compare or compareSync is that the first parameter should be the unhashed password that you enter in the login form.
The second parameter is an already hashed password that you want to compare your data with.
So all you have to do is not hash the password, because you are already hashing it and then sending it into the compare function it gets hashed twice. So you get an invalid password.
FYI, compare is used and required to handle the Promise; and compareSync is used, without a Promise. Also, compareSync returns a boolean value.
Hope that helps, thanks!

Related

Can't update User informations MongoDB validation error

Why can't I Update User if my passwordConfirm is required: true? This is my User model:
const crypto = require('crypto');
const mongoose = require('mongoose');
const validator = require('validator');
const bcrypt = require('bcryptjs');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Please tell us your name!'],
},
email: {
type: String,
required: [true, 'Please provide your email'],
unique: true,
lowercase: true,
validate: [validator.isEmail, 'Please provide a valid email'],
},
photo: {
type: String,
default: 'default.jpg',
},
role: {
type: String,
enum: ['user', 'guide', 'lead-guide', 'admin'],
default: 'user',
},
password: {
type: String,
required: [true, 'Please provide a password'],
minlength: 8,
select: false,
},
passwordConfirm: {
type: String,
required: [true, 'Please confirm your password'],
validate: {
validator: function (el) {
return el === this.password;
},
message: 'Passwords are not the same!',
},
},
passwordChangedAt: Date,
passwordResetToken: String,
passwordResetExpires: Date,
active: {
type: Boolean,
default: true,
select: false,
},
});
userSchema.pre('save', async function (next) {
// Only run this function if password was actually modified
if (!this.isModified('password')) return next();
// Hash the password with cost of 12
this.password = await bcrypt.hash(this.password, 12);
// Delete passwordConfirm field
this.passwordConfirm = undefined;
next();
});
userSchema.pre('save', function (next) {
if (!this.isModified('password') || this.isNew) return next();
this.passwordChangedAt = Date.now() - 1000;
next();
});
userSchema.pre(/^find/, function (next) {
// this points to the current query
this.find({ active: { $ne: false } });
next();
});
userSchema.methods.correctPassword = async function (
candidatePassword,
userPassword
) {
return await bcrypt.compare(candidatePassword, userPassword);
};
userSchema.methods.changedPasswordAfter = function (JWTTimestamp) {
if (this.passwordChangedAt) {
const changedTimestamp = parseInt(
this.passwordChangedAt.getTime() / 1000,
10
);
return JWTTimestamp < changedTimestamp;
}
// False means NOT changed
return false;
};
userSchema.methods.createPasswordResetToken = function () {
const resetToken = crypto.randomBytes(32).toString('hex');
this.passwordResetToken = crypto
.createHash('sha256')
.update(resetToken)
.digest('hex');
console.log({ resetToken }, this.passwordResetToken);
this.passwordResetExpires = Date.now() + 10 * 60 * 1000;
return resetToken;
};
const User = mongoose.model('User', userSchema);
module.exports = User;
And this is my controller:
exports.updateUserProfile = catchAsync(async (req, res) => {
const user = await User.findById(req.user._id);
if (user) {
user.name = req.body.name || user.name;
user.email = req.body.email || user.email;
if (req.body.password) {
user.password = req.body.password;
}
const updatedUser = await user.save();
res.json({
name: updatedUser.name,
});
} else {
res.status(404);
throw new Error('User not found');
}
});
res.json doesn't matter, I just want to get something back except error..
This is error from postman:
"error": {
"errors": {
"passwordConfirm": {
"name": "ValidatorError",
"message": "Please confirm your password",
"properties": {
"message": "Please confirm your password",
"type": "required",
"path": "passwordConfirm"
},
"kind": "required",
"path": "passwordConfirm"
}
},
"_message": "User validation failed",
"statusCode": 500,
"status": "error",
"name": "ValidationError",
"message": "User validation failed: passwordConfirm: Please confirm your password"
},
When I remove required: true code passwordConfirm then it does everything properly, I do not require anywhere in the controller to change the password or something like that
you can try this
exports.updateUserProfile = catchAsync(async (req, res) => {
const user = await User.findById(req.user._id);
const userToSave = {}
if (user) {
const userToSave = Object.assign({}, user)
userToSave.name = req.body.name || user.name;
userToSave.email = req.body.email || user.email;
if (req.body.password) {
userToSave.password = req.body.password;
}
const dbSave = new User(userToSave);
await dbSave.save();
res.json({
name: updatedUser.name,
});
} else {
res.status(404);
throw new Error('User not found');
}
});

beforeBulkDestroy not finding model property to change

I am trying to use the beforeBulkDestory Sequelize hook on a user delete that will switch the deleted column boolean to true prior to updating the record to add a timestamp for deleted_at. However, when I console.log the function parameter it provides a list of options and not the model object that I can update for the record of focus. Am I approaching this the wrong way? Is this something that should be set using model instances?
API Call:
import db from '../../../models/index';
const User = db.users;
export default (req, res) => {
const {
query: { id },
} = req
console.log(User)
if (req.method === 'DELETE') {
User.destroy({
where: {
id: id
}
}).then(data => {
res.json({
message: 'Account successfully deleted!'
})
})
} else {
const GET = User.findOne({
where: {
id: id
}
});
GET.then(data => {
res.json(data)
})
}
}
Parameter Values (beforeBulkDestroy, afterBulkDestroy):
beforeBulkDestroy
{
where: { id: '5bff3820-3910-44f0-9ec1-e68263c0f61f' },
hooks: true,
individualHooks: false,
force: false,
cascade: false,
restartIdentity: false,
type: 'BULKDELETE',
model: users
}
afterDestroy
{
where: { id: '5bff3820-3910-44f0-9ec1-e68263c0f61f' },
hooks: true,
individualHooks: true,
force: false,
cascade: false,
restartIdentity: false,
type: 'BULKUPDATE',
model: users
}
Model (users.js):
'use strict';
const Sequelize = require('sequelize');
const { Model } = require('sequelize');
const bcrypt = require("bcrypt");
module.exports = (sequelize, DataTypes) => {
class users extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
}
};
users.init({
id: {
type: DataTypes.UUID,
defaultValue: Sequelize.UUIDV4,
primaryKey: true
},
first_name: DataTypes.STRING,
last_name: DataTypes.STRING,
password: {
type: DataTypes.STRING
},
email: DataTypes.STRING,
active: {
type: DataTypes.BOOLEAN,
defaultValue: true
},
deleted: {
type: DataTypes.BOOLEAN,
defaultValue: false
}
}, {
hooks: {
beforeDestroy: (user, options) => {
console.log("beforeDestroy")
console.log(user)
console.log(options)
user.deleted = true
}
},
sequelize,
freezeTableName: true,
modelName: 'users',
omitNull: true,
paranoid: true,
underscored: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
deletedAt: 'deleted_at',
hooks: {
beforeCreate: async function(user){
console.log("beforeCreate")
console.log(user)
const salt = await bcrypt.genSalt(12);
user.password = await bcrypt.hash(user.password, salt);
console.log(user.password)
},
beforeBulkDestroy: async function(user){
console.log("beforeBulkDestroy")
console.log(user)
},
afterBulkDestroy: async function(user){
console.log("afterDestroy")
console.log(user)
}
}
});
users.prototype.validPassword = async function(password) {
console.log("validatePassword")
console.log(password)
return await bcrypt.compare(password, this.password);
}
return users;
};
the before/after bulkDestroy hooks only receive the options, not the instances. One way you could do this is defining a before/after Destroy hook:
hooks: {
beforeDestroy: (user, { transaction }) => {
user.update({ deleted: true }, { transaction });
}
}
and calling User.destroy with the individualHooks option:
User.destroy({ where: { id: id }, individualHooks: true });
Be aware that this will load all selected models into memory.
Docs
Note: In your case, since you're only deleting one record by id, it would be better to just user = User.findByPk(id) then user.destroy(). This would always invoke the hooks and it also makes sure the record you want to delete actually exists.
Note 2: Not sure why you need a deleted column, you could just use deletedAt and coerce it into a boolean (with a virtual field if you want to get fancy).

How to update Password with new password on Reset Password

The GITHUB REPO i'm using code repository
I'm trying to reset the user password on redirecting the user to reset password page. On the 1st Singup I'm hashing the password and salt is generated and stored in database using CRYPTO. On reset password the new password is not getting updated it does not allow to signin using the updated password.
I tried using response.password which gives the updated password.Still couldn't figure out the solution.
Reset password :
exports.resetPassword = (req,res) => {
const {resetPasswordLink, newPassword } = req.body
if(resetPasswordLink){
jwt.verify(resetPasswordLink,process.env.JWT_RESET_PASSWORD, function(err,decoded){
if(err){
return res.status(401).json({
error : ' The Link has been expired ! , Try Again '
})
}
User.findOne({resetPasswordLink},(err,user)=>{
if(err || !user){
return res.status(401).json({
error: ' The Link has been expired ! , Try Again '
})
}
const updatedFields = {
password: newPassword,
resetPasswordLink: ''
}
user = _.extend(user,updatedFields)
user.save((err,result)=>{
if(err){
return res.status(400).json({
error: errorHandler(err)
})
}
return res.json({
message: ` Your Password Has Been Successfully Reset , Please Return to the SignIn Page to SignIn `
// result.password
})
})
})
})
}
}
UPDATE 4th August :
Here's the complete USER model
User Schema :
const mongoose = require('mongoose');
const crypto = require('crypto');
const userSchema = new mongoose.Schema(
{
username: {
type: String,
trim: true,
required: true,
max: 32,
unique: true,
index: true,
lowercase: true
},
name: {
type: String,
trim: true,
required: true,
max: 32
},
email: {
type: String,
trim: true,
required: true,
unique: true,
lowercase: true
},
profile: {
type: String,
required: true
},
hashed_password: {
type: String,
required: true
},
salt: String,
about: {
type: String
},
role: {
type: Number,
default: 0
},
photo: {
data: Buffer,
contentType: String
},
resetPasswordLink: {
data: String,
default: ''
}
},
{ timestamp: true }
);
userSchema
.virtual('password')
.set(function(password) {
// create a temporarity variable called _password
this._password = password;
// generate salt
this.salt = this.makeSalt();
// encryptPassword
this.hashed_password = this.encryptPassword(password);
})
.get(function() {
return this._password;
});
userSchema.methods = {
authenticate: function(plainText) {
return this.encryptPassword(plainText) === this.hashed_password;
},
encryptPassword: function(password) {
if (!password) return '';
try {
return crypto
.createHmac('sha1', this.salt)
.update(password)
.digest('hex');
} catch (err) {
return '';
}
},
makeSalt: function() {
return Math.round(new Date().valueOf() * Math.random()) + '';
}
};
module.exports = mongoose.model('User', userSchema);
problem is in your signin function where you have set expiry of 'jwt' and 'cookie' use { expiresIn: '1d' } instead of { expiresIn: '1' } because '1' means your jwt and cookie expires in 1 ms
const token = jwt.sign({ _id: user._id }, process.env.JWT_SECRET, { expiresIn: '1d' });
res.cookie('token', token, { expiresIn: '1d' });

Cannot access Sequelize instance methods

I get the following error when I attempt to call the generateHash instance method I've defined on my User model:
User.generateHash(...).then is not a function
Here's the model definition itself:
const User = sequelize.define('User',
{
firstName: {
type: Sequelize.TEXT,
field: 'first_name'
},
lastName: {
type: Sequelize.TEXT,
allowNull: false,
field: 'last_name'
},
userName: {
type: Sequelize.TEXT,
field: 'user_name',
allowNull: false
},
password: {
type: Sequelize.TEXT,
allowNull: false
}
}, {
tableName: 'users',
underscored: true,
classMethods: {
associate: function(models) {
User.hasMany(
models.Trip,
{
as: 'trips',
foreignKey: {
name: 'userId',
field: 'user_id',
allowNull: false
},
onDelete: 'CASCADE'
});
},
},
instanceMethods: {
generateHash: function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
},
validatePassword: function(password) {
return bcrypt.compareSync(password, this.password);
},
apiRepr: function() {
return {
id: this.id,
firstName: this.firstName,
lastName: this.lastName,
userName: this.userName
};
}
}
});
Here's the endpoint where I attempt to call the method:
router.post('/', (req, res) => {
let {userName, password, firstName, lastName} = req.body;
// if no existing user, hash password
return User.generateHash(password)
.then(hash => {
// create new user
return User.create({
firstName: firstName,
lastName: lastName,
userName: userName,
password: hash
});
})
.then(user => {
// send back apirRepr data
return res.status(201).json(user.apiRepr());
})
// error handling
.catch(err => {
if (err.name === 'AuthenticationError') {
return res.status(422).json({message: err.message});
}
res.status(500).json({message: 'Internal server error'});
});});
I'm totally stuck. Any ideas?
In sequelize V4 class and instance methods are removed.
Now you have to make it this way:
const Model = sequelize.define('Model', {
...
});
// Class Method
Model.associate = function (models) {
...associate the models
};
// Instance Method
Model.prototype.someMethod = function () {..}
More information here Sequelize v4 breaking changes
You are calling .then() on something that does not return a promise. Try this:
router.post('/', (req, res) => {
let {userName, password, firstName, lastName} = req.body;
let hash = User.generateHash(password);
// if no existing user, hash password
return User.create({
firstName: firstName,
lastName: lastName,
userName: userName,
password: hash
})
.then(user => {
// send back apirRepr data
return res.status(201).json(user.apiRepr());
})
// error handling
.catch(err => {
if (err.name === 'AuthenticationError') {
return res.status(422).json({message: err.message});
}
return res.status(500).json({message: 'Internal server error'});
});

Using BCrypt with Sequelize Model

I'm trying to use the bcrypt-nodejs package with my sequelize model and was tring to follow a tutorial to incorporate the hashing into my model, but I'm getting an error at generateHash. I can't seem to figure out the issue. Is there a better way to incorporate bcrypt?
Error:
/Users/user/Desktop/Projects/node/app/app/models/user.js:26
User.methods.generateHash = function(password) {
^
TypeError: Cannot set property 'generateHash' of undefined
at module.exports (/Users/user/Desktop/Projects/node/app/app/models/user.js:26:27)
at Sequelize.import (/Users/user/Desktop/Projects/node/app/node_modules/sequelize/lib/sequelize.js:641:30)
model:
var bcrypt = require("bcrypt-nodejs");
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('users', {
annotation_id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
firstName: {
type: DataTypes.DATE,
field: 'first_name'
},
lastName: {
type: DataTypes.DATE,
field: 'last_name'
},
email: DataTypes.STRING,
password: DataTypes.STRING,
}, {
freezeTableName: true
});
User.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
User.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
return User;
}
Methods should be provided in the "options" argument of sequelize.define
const bcrypt = require("bcrypt");
module.exports = function(sequelize, DataTypes) {
const User = sequelize.define('users', {
annotation_id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
firstName: {
type: DataTypes.DATE,
field: 'first_name'
},
lastName: {
type: DataTypes.DATE,
field: 'last_name'
},
email: DataTypes.STRING,
password: DataTypes.STRING
}, {
freezeTableName: true,
instanceMethods: {
generateHash(password) {
return bcrypt.hash(password, bcrypt.genSaltSync(8));
},
validPassword(password) {
return bcrypt.compare(password, this.password);
}
}
});
return User;
}
Other alternative: Use hook and bcrypt async mode
User.beforeCreate((user, options) => {
return bcrypt.hash(user.password, 10)
.then(hash => {
user.password = hash;
})
.catch(err => {
throw new Error();
});
});
There's a tutorial out there on how to get a sequelize/postgreSQL auth system working with hooks and bcrypt.
The guy who wrote the tutorial did not use async hash/salt methods; in the user creation/instance method section he used the following code:
hooks: {
beforeCreate: (user) => {
const salt = bcrypt.genSaltSync();
user.password = bcrypt.hashSync(user.password, salt);
}
},
instanceMethods: {
validPassword: function(password) {
return bcrypt.compareSync(password, this.password);
}
}
Newer versions of Sequelize don't like instance methods being declared this way - and multiple people have explained how to remedy this (including someone who posted on the original tutorial):
The original comment still used the synchronous methods:
User.prototype.validPassword = function (password) {
return bcrypt.compareSync(password, this.password);
};
All you need to do to make these functions asyncronous is this:
Async beforeCreate bcrypt genSalt and genHash functions:
beforeCreate: async function(user) {
const salt = await bcrypt.genSalt(10); //whatever number you want
user.password = await bcrypt.hash(user.password, salt);
}
User.prototype.validPassword = async function(password) {
return await bcrypt.compare(password, this.password);
}
On the node.js app in the login route where you check the password, there's a findOne section:
User.findOne({ where: { username: username } }).then(function (user) {
if (!user) {
res.redirect('/login');
} else if (!user.validPassword(password)) {
res.redirect('/login');
} else {
req.session.user = user.dataValues;
res.redirect('/dashboard');
}
});
All you have to do here is add the words async and await as well:
User.findOne({ where: { username: username } }).then(async function (user) {
if (!user) {
res.redirect('/login');
} else if (!await user.validPassword(password)) {
res.redirect('/login');
} else {
req.session.user = user.dataValues;
res.redirect('/dashboard');
}
});
Bcrypt Is no longer part of node, so I included example with new module of crypto
I am sharing this code from one of working project.
My config file
require('dotenv').config();
const { Sequelize,DataTypes ,Model} = require("sequelize");
module.exports.Model = Model;
module.exports.DataTypes = DataTypes;
module.exports.sequelize = new Sequelize(process.env.DB_NAME,process.env.DB_USER_NAME, process.env.DB_PASSWORD, {
host: process.env.DB_HOST,
dialect: process.env.DB_DISELECT,
pool: {
max: 1,
min: 0,
idle: 10000
},
//logging: true
});
My user model
const { sequelize, DataTypes, Model } = require('../config/db.config');
var crypto = require('crypto');
class USERS extends Model {
validPassword(password) {
var hash = crypto.pbkdf2Sync(password,
this.SALT, 1000, 64, `sha512`).toString(`hex`);
console.log(hash == this.PASSWORD)
return this.PASSWORD === hash;
}
}
USERS.init(
{
ID: {
autoIncrement: true,
type: DataTypes.BIGINT,
allowNull: false,
primaryKey: true
},
MOBILE_NO: {
type: DataTypes.BIGINT,
allowNull: false,
unique: true
},
PASSWORD: {
type: DataTypes.STRING(200),
allowNull: false
},
SALT: {
type: DataTypes.STRING(200),
allowNull: false
}
},
{
sequelize,
tableName: 'USERS',
timestamps: true,
hooks: {
beforeCreate: (user) => {
console.log(user);
user.SALT = crypto.randomBytes(16).toString('hex');
user.PASSWORD = crypto.pbkdf2Sync(user.PASSWORD, user.SALT,
1000, 64, `sha512`).toString(`hex`);
},
}
});
module.exports.USERS = USERS;
And Auth Controller
const { USERS } = require('../../../models/USERS');
module.exports = class authController {
static register(req, res) {
USERS.create({
MOBILE_NO: req.body.mobile,
PASSWORD: req.body.password,
SALT:""
}).then(function (data) {
res.json(data.toJSON());
}).catch((err) => {
res.json({
error: err.errors[0].message
})
})
}
static login(req, res) {
var message = [];
var success = false;
var status = 404;
USERS.findOne({
where:{
MOBILE_NO: req.body.mobile
}
}).then(function (user) {
if (user) {
message.push("user found");
if(user.validPassword(req.body.password)) {
status=200;
success = true
message.push("You are authorised");
}else{
message.push("Check Credentials");
}
}else{
message.push("Check Credentials");
}
res.json({status,success,message});
});
}
}
Old question, but maybe can help someone, you can use sequelize-bcrypt
Example:
const { Sequelize, DataTypes } = require('sequelize');
const useBcrypt = require('sequelize-bcrypt');
const database = new Sequelize({
...sequelizeConnectionOptions,
});
const User = database.define('User', {
email: { type: DataTypes.STRING },
password: { type: DataTypes.STRING },
});
useBcrypt(User);
Usage
User.create({ email: 'john.doe#example.com', password: 'SuperSecret!' });
// { id: 1, email: 'john.doe#example.com', password: '$2a$12$VtyL7j5xx6t/GmmAqy53ZuKJ1nwPox5kHLXDaottN9tIQBsEB3EsW' }
const user = await User.findOne({ where: { email: 'john.doe#example.com' } });
user.authenticate('WrongPassword!'); // false
user.authenticate('SuperSecret!'); // true

Resources