Thursday, 1 June 2017

After creating server side api using express, mongoose, mongodb, morgan and body-parser login route always throw bad request error

Here is my complete application Setup. Here I am using express server, morgan and body-parser as middleware and mongodb as database. My signup route is working fine but my login route always give bad request error.

    //Main starting point of the application
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const morgan = require('morgan');

const app = express();
const router = require('./router');
const mongoose = require('mongoose');

//DB Setup
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:auth/auth');

//App setup
app.use(morgan('combined'));
app.use(bodyParser.json({ type: '*/*' }));
router(app);

//Server setup
const port = process.env.PORT || 3090;
const server = http.createServer(app);
server.listen(port);
console.log('server listening on port:',port);

Here is my model

 const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt-nodejs');

//Define our model
const userSchema = new Schema({
  email: { type: String, unique: true, lowercase: true },
  password: String
});
//On Save Hook, encrypt password
//Before saving a model, run this function
userSchema.pre('save',function(next){
  // get access to the user model
  const user = this;
// Generate a salt then run callback
  bcrypt.genSalt(10, function(err, salt){
    if (err) {
      return next(err);
      }
      // Hash (encrypt) our password using salt
      bcrypt.hash(user.password, salt, null, function(err, hash){
        if (err) {
          return next(err);
        }
        // Overwrite plain text password with encrypted password
        user.password = hash;
        next();
      });
  });
});

userSchema.methods.comparePassword = function(candidatePassword, callback) {
  bcrypt.compare(candidatePassword, this.password, function(err, isMatch){
    if (err) {
      return callback(err);
    }
    callback(null, isMatch);
  })
}

//Create the model class
const ModelClasss = mongoose.model('user',userSchema);

//Export model
module.exports=ModelClasss;

and here is my controller

    const jwt = require('jwt-simple');
const User = require('../models/user');
const config = require('../config');

function tokenForUser(user){
  const timestamp = new Date().getTime();
  return jwt.encode({ sub: user.id, iat: timestamp }, config.secret);
}

exports.signin = function(req,res,next){
  // User has already had their email and password auth'd
  // We just need to give them token
  res.send({ token: tokenForUser(req.user) });
}
exports.signup = function(req, res, next){
  const email = req.body.email;
  const password = req.body.password;

  if (!email || !password) {
    return res.status(422).send({ error: 'You must provide email and password' });
  }
  User.findOne({ email: email }, function(err, existingUser){
    if(err) {
      return next(err);
    }
    //See if a user with the given email exists
    if (existingUser) {
      return res.status(422).send({ error: 'Email is in use' });
    }
    //If a user with email does not exist, create and save user record
    const user = new User({
      email: email,
      password: password
    });

    user.save(function(err){
      if (err) {
        return next(err);
      }
      //Respond to request indicating the use was created
      res.json({ token: tokenForUser(user) });
    });
  });
}

Here is route file

    const Authentication = require('./controllers/authentication');
const passportService = require('./services/passport');
const passport = require('passport');

const requireAuth = passport.authenticate('jwt', { session: false });
const requireSignin = passport.authenticate('local', { session: false });

module.exports = function(app){
  app.get('/', requireAuth, function(req,res){
    res.send({ hi: "there" });
  });
  app.post('/signin', requireSignin, Authentication.signin);
  app.post('/signup', Authentication.signup);
}



via vivek kumar

No comments:

Post a Comment