使用基本护照身份验证时收到错误请求

时间:2016-08-23 05:52:29

标签: node.js passport.js passport-local bad-request

我已经使用了基本的本地策略,并且我得到了400个错误的请求错误作为响应。我应该怎么做,我使用邮递员来提出请求。我在下面写了护照配置。

当我尝试使用/登录数据时{用户名:nivas@12345.com和密码:nivas12345}

var LocalStrategy = require('passport-local').Strategy;
var common = require('../routes/common');


// load up the user model
var User = require('../model/user');




module.exports = function(passport) {
console.log("passport is working upto here");

    // 
    // passport session setup 
    // required for persistent login sessions
    // passport needs ability to serialize and deserialize users out of session


    // used to serialize the user for the session
    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });


    // used to deserialize the user
    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });

    //
    // LOCAL SIGNUP 
    // 
    // we are using named strategies since we have one for login and one for signup
    // by default, if there was no name, it would just be called 'local'
    // 
    // LOCAL LOGIN 
    // 
    // we are using named strategies since we have one for login and one for signup
    // by default, if there was no name, it would just be called 'local'

    passport.use('local-login', new LocalStrategy({
        // by default, local strategy uses username and password, we will override with email
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true // allows us to pass back the entire request to the callback
    },
    function(req, username, password, done) { // callback with email and password from our form
console.log('getting into callback');
        // find a user whose email is the same as the forms email
        // we are checking to see if the user trying to login already exists
        User.findOne({ 'username' :  username }, function(err, user) {
            // if there are any errors, return the error before anything else
            console.log(user);
            if (err)
                return done(err);

            // if no user is found, return the message
            if (!user)
                return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash

            // if the user is found but the password is wrong
            if (!user.validPassword(password))
                return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata

            // all is well, return successful user
            return done(null, user);
        });

    }));

};

我在app.js文件中直接使用了路由技术,我在这里也添加了app.js ......

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session =require('session');
var passport = require('passport');
var common = require('./routes/common');
require('./config/passport')(passport);



var app = express();



//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//app.use(express.session({ secret: 'medicoshereisaquestionbank' }));
app.use(passport.initialize());
app.use(passport.session());




//Routing

var routes = require('./routes/index');
var users = require('./routes/users');
var registerUser = require('./routes/registeruser');
var postquestion = require('./routes/postquestion');


//Database connection verification
app.db = common.conn;
app.db.on('error', console.error.bind(console, 'mongoose connection error: error '));

app.db.once('open', function () {
    console.log('db connection established to medicoshere database ');


    //and... we have a data store
    //console.log(app.db);
});




//Fixing the modules for a routes.....
app.use('/', routes);
app.use('/users', users);
app.use('/register', registerUser);
app.use('/postquestion', postquestion);
app.post('/login', passport.authenticate('local-login', {
    faliureRedirect: '/login'
}),function(req, res) {
    res.redirect('/');
  });



// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.send('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.send('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;

我的模型文件在这里。

// Node Module dependencies
var express = require('express');

// Local Module dependencies
var common = require('../routes/common.js');
var bcrypt = require('bcrypt-nodejs');

//var request = require('request');
common.mong = global.Promise;




//common.autoIncrement.initialize(common.conn);

//---------------Schema Definitions---------------------//
var userSchema = common.Schema({

    username: String,
    password:String,
    email:String,
    gender: {
        type: String,
        enum: ['male', 'female'],
        default: 'male'
    },
    contact: Number,
    profile_pic: String,
    address: String,
    role: String,
    dob: {
        type: Date,
        default: Date.now
    },
    collage_name: String,
    course: String,
    roll: String,
    specialization: String

});
userSchema.methods.generateHash = function (password) {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};

// checking if password is valid
userSchema.methods.validPassword = function (password) {
    return bcrypt.compareSync(password, this.local.password);
};


var User = common.conn.model('User', userSchema);
module.exports = User;

我在这里错过了什么。

0 个答案:

没有答案