gpt4 book ai didi

javascript - 使用 Passport.js 的登录系统始终执行 “failureRedirect” (nodejs)

转载 作者:太空宇宙 更新时间:2023-11-04 00:22:46 24 4
gpt4 key购买 nike

我正在做教程,但我被困在登录区域。当我使用 Passport.js 登录时,它总是在身份验证中执行“failureRedirect”。

尝试调试替换 router.post('login') 路由后,我收到以下消息:

Error: null User: false Info: {"message":"Missing credentials"}

在阅读一些论坛后,我认为问题可能与 body-parser 有关。我一直在努力解决这个问题,但还没有成功。我非常感谢最有经验的 Node.js 程序员的帮助。

该项目的结构是:应用程序.js 路线: 用户.js 楷模: 用户.js

user.js

var express = require('express');
var router = express.Router();
var multer = require('multer');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');

var User = require('../models/user');

var upload = multer({ dest: './uploads' });

// create application/json parser
var jsonParser = bodyParser.json();

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false });

/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});

router.get('/register', function(req, res, next) {
res.render('register', {
title: 'Register'
});
});

router.get('/login', function(req, res, next) {
res.render('login', {
'title': 'Login'
});
});

router.post('/register', upload.single('profileimage'), function (req, res, next) {
//Get Form Values
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;


// Check for Image Field
if(req.files && req.files.profileimage){
console.log('Uploading File...');

// File Info
var profileImageOriginalName = req.files.profileimage.originalname;
var profileImageName = req.files.profileimage.name;
var profileImageMime = req.files.profileimage.mimetype;
var profileImagePath = req.files.profileimage.path;
var profileImageExt = req.files.profileimage.extension;
var profileImageSize = req.files.profileimage.size;
} else {
// Set a Default Image
var profileImageName = 'noimage.png';
}

// Form Validation
req.checkBody('name', 'Name field is required').notEmpty();
req.checkBody('email', 'Email field is required').notEmpty();
req.checkBody('email', 'Email not valid').isEmail();
req.checkBody('username', 'Username field is required').notEmpty();
req.checkBody('password', 'Password field is required').notEmpty();
req.checkBody('password2', 'Passwords do not match').equals(req.body.password);

// Check for errors
var errors = req.validationErrors();

if(errors){
res.render('register', {
errors: errors,
name: name,
email: email,
username: username,
password: password,
password2: password2
});
} else {
var newUser = new User({
name: name,
email: email,
username: username,
password: password,
profileImage: profileImageName
});

// Create User
User.createUser(newUser, function (err, user) {
if(err) throw err;
console.log(user);
});

//Success Message
req.flash('success', 'You are now registered and may log in');

res.location('/');
res.redirect('/');
}
});

passport.serializeUser(function(user, done) {
done(null, user.id);
});

passport.deserializeUser(function(id, done) {
User.getUserById(id, function(err, user) {
done(err, user);
});
});

passport.use(new LocalStrategy(
function (username, password, done) {
User.getUserByUsername(username, function (err, user) {
if(err) throw err;
if(!user){
console.log('Unknown User');
return done(null, false, {message: 'Unknown User'});
}

User.comparePassword(password, user.password, function (err, isMatch) {
if(err) throw err;
if(isMatch){
return done(null, user);
} else {
console.log('Invalid Password');
return done(null, false, {message:'Invalid Password'});
}
});
});
}
));

router.post('/login', jsonParser, passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/users/login',
failureFlash: true //'Invalid username or password'
}), function (req, res) {
console.log('Authentication Successful');
req.flash('success', 'You are logged in');
res.redirect('/');
});

router.post('/login', passport.authenticate('local', function(err, user, info) {
console.log("authenticate");
console.log(err);
console.log(user);
console.log(info);
}), function (req, res) {
console.log('Authentication Successful');
req.flash('success', 'You are logged in');
res.redirect('/');
});

module.exports = router;

user.js

var mongoose = require('mongoose');
var bcrypt = require('bcrypt');

mongoose.connect('mongodb://localhost/nodeauth');

var db = mongoose.connection;

// User Schema
var UserSchema = mongoose.Schema({
username: {
type: String,
index: true
},
password: {
type: String,
required: true,
bcrypt: true
},
email: {
type: String
},
name:{
type: String
},
profileimage:{
type: String
}

});

var User = module.exports = mongoose.model('User', UserSchema);

module.exports.comparePassword = function(candidatePassowrd, hash, callback) {
bcrypt.compare(candidatePassowrd, hash, function (err, isMatch) {
if(err) return callback(err);
callback(null, isMatch);
});
}

module.exports.getUserById = function (id, callback) {
User.findById(id, callback);
}

module.exports.getUserByUsername = function (username, callback) {
var query = {username: username};
User.findOne(query, callback);
}

module.exports.createUser = function (newUser, callback) {
bcrypt.hash(newUser.password, 10, function (err, hash) {
if(err) throw err;

// Set hashed pw
newUser.password = hash;

// Create User
newUser.save(callback);
});
}

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var multer = require('multer');
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;

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

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// Handle File Uploads
// app.use(multer({dest:'./uploads'}));
var upload = multer({ dest: './uploads' });

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Handle Express Sessions
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));

// Passport
app.use(passport.initialize());
app.use(passport.session());

// Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;

while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
// app.use(expressValidator({
// errorFormatter
// }));

app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(flash());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});

app.use('/', routes);
app.use('/users', users);

// 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 handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

module.exports = app;

Dropbox 上的文件: https://www.dropbox.com/sh/ex26xxo85lfo0my/AADET-j6Ift0q-y-ecWCRUEba?dl=0

感谢您的帮助:)

最佳答案

请查看 https://github.com/rupalipemare/Mongoose-Demo 上的代码,其中有完整的示例演示 Passport 认证。

关于javascript - 使用 Passport.js 的登录系统始终执行 “failureRedirect” (nodejs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43958007/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com