here complete code
var express = require('express'), app = express(), mongoose = require('mongoose'), bodyparser = require('body-parser'), morgan = require('morgan'), webtoken = require('jsonwebtoken'), bcrypt = require('bcryptjs'), assert = require('assert'); schema = mongoose.schema, secretkey = "omjdiuwkslxmshsoepdukslsj"; //user schema var userschema = new schema({ username: {type: string, required: true, index: {unique:true}}, password: {type: string, required: true, select: false} }) userschema.pre('save', function(next){ var user = this; if(!user.ismodified('password')) return next(); bcrypt.hash(user.password, null, null, function(err, hash){ if(err) return next(err); user.password = hash; next(); }) }); userschema.methods.comparepassword = function(password){ var user = this; bcrypt.compare(password, user.password, function(err, result){ if(err){ console.log(err); } else { console.log("passwords match!"); return; } }) } var usermodel = mongoose.model('users', userschema); //connecting mongo mongoose.connect("mongodb://localhost/userstories", function(err){ if(err) { console.log(err); } else { console.log("connected database!"); } }); //creating token function createtoken(user){ var token = webtoken.sign({ _id: user.id, username: user.username }, secretkey,{ expiresin: 30 * 60 * 1000 }) return token; } //middlewares app.use(bodyparser.urlencoded({extended: true})); app.use(bodyparser.json()); app.use(morgan('dev')); //api's app.post('/signup', function(req, res){ var user = new usermodel({ username: req.body.username, password: req.body.password }) user.save(function(err){ if(err){ console.log(err); } else{ res.json({message: "user created!"}); } }) }) app.post('/login', function(req, res){ usermodel.findone({username: req.body.username}, function(err, user){ if(err) console.log(err); if(!user){ res.send("user not found!"); } else if(user){ var validpassword = user.comparepassword(req.body.password); if(validpassword){ var tokens = createtoken(user); res.json({ success: true, message: "successfully logged in", token: tokens }); } else { res.send("invalid password"); } } }) }); //running server app.listen(3000, function(err){ if(err) console.log("port not working"); else{ console.log("everything went fine"); } })
i've tried every approaches , saw answers here. no 1 seem come across illegal argument error. please figure 1 out me im sure there bug cant see
i encountered same error when using bcrypt.comparesync("input compared hash", hash)
.
later on discovered supposed pass actual value in first input parameter i.e (the actual value hash generated) , hash in second input parameter, passing hashed values in both input parameters.
after correcting same giving me desired output true or false.
you can run , check code here.
Comments
Post a Comment