导出和导入 Passport.JS 问题
Export and Import Passport.JS Issues
我正在使用 node js 作为后端并作为前端做出反应。在后端,我想创建一个单独的文件来处理每个 passport.js 模块,如下所示,并将 passport.js 导入 user.js 文件,以便可以将用户输入数据传递给护照文件并在需要时归还。我 运行 遇到的问题是找到正确导入和导出 passport.js 文件的方法。任何帮助就足够了,甚至“那不可能”也可以。
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mysql = require('mysql2');
const crypto = require('crypto');
const session = require('express-session');
const SqlDbStore = require('express-mysql-session')(session);
const db = require('./db');
app.use(session({
key: 'session_cookie_name',
secret: 'session_cookie_secret',
store: new SqlDbStore({
host: 'localhost',
port: 3306,
user: 'root',
password: 'xxxxxxxxxx',
database: 'xxxxxxxxxx',
}),
resave: false,
saveUninitialized: false,
cookie:{
maxAge:1000*60*60*24,
}
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(express.static(__dirname + '/views'));
db.connect((err) => {
if (!err) {
console.log("BD Connected");
} else {
console.log("BD Conection Failed");
console.log(err.message);
}
});
const customFields={
firstNameField: 'usersFirstName',
lastNameField: 'usersLastName',
emailField: 'usersEmail',
passwordField:'usersPassword',
confirmPasswordField:'usersConfirmedPassword'
};
/*Passport JS*/
const verifyCallback=(email,password,done)=>{
connection.query('SELECT * FROM USER WHERE usersEmail= ?', [email], function(error, results, fields) {
if (error) {
console.log('query error: ' + error);
return done(error);
}
if(results.length==0) {
return done(null,false, {message: 'Account is not recognized.'});
}
const isValid=validPassword(password, results[0].EncryptHash, results[0].EncryptPassword);
user={id:results[0].ID, email:results[0].usersEmail, hash:results[0].EncryptHash, password:results[0].EncryptPassword};
if(isValid) {
return done(null,user);
} else {
return done(null,false, {message: 'Password is incorrect.'});
}
});
};
const strategy = new LocalStrategy(customFields, verifyCallback);
passport.use(strategy);
passport.serializeUser((user,done)=>{
console.log("Inside serialize");
done(null, user.id);
});
passport.deserializeUser(function(userId, done) {
console.log('deserializeUser');
connection.query('SELECT * FROM User WHERE ID = ? ', [userId], function(error, results) {
done(null, results[0]);
});
});
/*middleware*/
function validPassword(password, hash, salt){
const hashVerify=crypto.pbkdf2Sync(password, salt, 10000, 60, 'sha512').toString("hex");
return hash === hashVerify;
};
function genPassword(password) {
var salt=crypto.randomBytes(32).toString('hex');
var genhash=crypto.pbkdf2Sync(password, salt, 10000, 60, 'sha512').toString('hex');
return {salt:salt, hash:genhash}
};
function checkAuthentication(req,res,next){
if(req.isAuthenticated()){
//req.isAuthenticated() will return true if user is logged in
next();
} else {
res.redirect("/login");
}
};
User.JS
const express = require('express');
const router = express.Router();
const db = require('../config/db');
const passport = require('../config/passport');
const routes = require('')('passport');
router.post('/register', (req, res) => {
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const email = req.body.email;
const password = req.body.password;
const saltHash = genPassword(password);
const salt = passport.saltHash.salt;
const hash = passport.saltHash.hash;
db.query('SELECT * FROM Users WHERE UsersEmail = ? ', [email], (err, results) => {
if (err){
console.log(err)
} else if (results.length > 0) {
res.json({ message: 'Email is already registered!' });
} else {
db.query('INSERT INTO Users (UsersFirstName, UsersLastName, UsersEmail, UsersPasswordHash, UsersPasswordSalt) VALUES (?, ?, ?, ?, ?)', [firstName, lastName, email, hash, salt], (err, results) => {
if (err){
console.log(err);
};
res.send(results);
});
}
})
});
router.post('/login', passport.authenticate('local'));
module.exports = {router, passport};
请注意,我想要转到此根目录的主要原因是为了防止在控制台中访问以下代码。
app.use(session({
key: 'session_cookie_name',
secret: 'session_cookie_secret',
store: new SqlDbStore({
host: 'localhost',
port: 3306,
user: 'root',
password: 'xxxxxxxxxx',
database: 'xxxxxxxxxx',
}),
resave: false,
saveUninitialized: false,
cookie:{
maxAge:1000*60*60*24,
}
}));
更新:
所以我能够进行以下更改以更接近。但是,我收到一条错误消息,指出本地护照“缺少凭据”。
代码更改:
User.JS
const express = require('express');
const app = express();
const router = express.Router();
const db = require('../config/db');
const session = require('express-session');
const SqlDbStore = require('express-mysql-session')(session);
const passport = require('passport');
const bodyParser = require('body-parser');
const mysql = require('mysql2');
const crypto = require('crypto');
const LocalStrategy = require('passport-local').Strategy;
//----------------------------------------- BEGINNING OF PASSPORT MIDDLEWARE AND SETUP ---------------------------------------------------
app.use(session({
key: 'session_cookie_name',
secret: 'session_cookie_secret',
store: new SqlDbStore({
host: 'localhost',
port: 3306,
user: 'root',
password: 'xxxxxxxxxx',
database: 'xxxxxxxxxx',
}),
resave: false,
saveUninitialized: false,
cookie:{
maxAge:1000*60*60*24,
}
}));
app.use(passport.initialize());
app.use(passport.session());
require('../config/ppc.js')(passport);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.use(express.static(__dirname + '/index'));
/*passport middleware*/
function genPassword(password) {
var salt=crypto.randomBytes(32).toString('hex');
var genhash=crypto.pbkdf2Sync(password, salt, 10000, 60, 'sha512').toString('hex');
return {salt:salt, hash:genhash}
};
function checkAuthentication(req,res,next){
if(req.isAuthenticated()){
//req.isAuthenticated() will return true if user is logged in
next();
} else{
res.redirect("/login");
}
};
//----------------------------------------- END OF PASSPORT MIDDLEWARE AND SETUP ---------------------------------------------------
router.post('/register', (req, res) => {
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const email = req.body.email;
const password = req.body.password;
const saltHash = genPassword(password);
const salt = saltHash.salt;
const hash = saltHash.hash;
db.query('SELECT * FROM Users WHERE UsersEmail = ? ', [email], (err, results) => {
if (err){
console.log(err)
} else if (results.length > 0) {
res.json({ message: 'Email is already registered!' });
} else {
db.query('INSERT INTO Users (UsersFirstName, UsersLastName, UsersEmail, UsersPasswordHash, UsersPasswordSalt) VALUES (?, ?, ?, ?, ?)', [firstName, lastName, email, hash, salt], (err, results) => {
if (err){
console.log(err);
};
res.send(results);
});
}
})
});
router.post('/login', function(req, res, next){
console.log(req.body);
passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login'
}, function(err, user, info){
console.log(err, user, info);
if(err) {
res.render ('login ', {Title:' Login ', ErrorMessage: err. Message});
}
if(!user) {
res.render ('login ', {Title:' Login ', ErrorMessage: info. Message});
}
return req.logIn(user, function(err){
if(err) {
res.render ('login ', {Title:' Login ', ErrorMessage: err. Message});
} else {
return res.redirect('/project');
}
});
})(req, res, next);
});
module.exports = router;
ppc.js
const LocalStrategy = require('passport-local').Strategy;
const express = require('express');
const db = require('./db');
module.exports = function (passport) {
db.connect((err) => {
if (!err) {
console.log("BD Connected");
} else {
console.log("BD Conection Failed");
console.log(err.message);
}
});
const customFields={
firstNameField: 'firstName',
lastNameField: 'lastName',
emailField: 'email',
passwordField:'password',
confirmPasswordField:'passwordConfirmation'
};
/*Passport JS*/
const verifyCallback=(email,password,done)=>{
connection.query('SELECT * FROM USER WHERE usersEmail= ?', [email], function(error, results, fields) {
if (error) {
console.log('query error: ' + error);
return done(error);
}
if(results.length==0) {
return done(null,false, {message: 'Account is not recognized.'});
}
const isValid=validPassword(password, results[0].UsersPasswordHash, results[0].UsersPasswordSalt);
user={id:results[0].ID, email:results[0].usersEmail, hash:results[0].UsersPasswordHash, salt:results[0].UsersPasswordSalt};
if(isValid) {
return done(null,user);
} else{
return done(null,false, {message: 'Password is incorrect.'});
}
});
};
const strategy = new LocalStrategy(customFields, verifyCallback);
passport.use(strategy);
passport.serializeUser((user,done)=>{
console.log("Inside serialize");
done(null, user.id);
});
passport.deserializeUser(function(userId, done) {
console.log('deserializeUser');
connection.query('SELECT * FROM User WHERE ID = ? ', [userId], function(error, results) {
done(null, results[0]);
});
});
function validPassword(password, hash, salt){
const hashVerify=crypto.pbkdf2Sync(password, salt, 10000, 60, 'sha512').toString("hex");
return hash === hashVerify;
};
}
返回代码:
BD Connected
{ email: 'jondoetech@outlook.com', password: '1234' } null false { message: 'Missing credentials' }
Error: No default engine was specified
and no extension was provided at new View
所以这是我必须做的来解决我的问题。
为了登录,我不得不将代码更新为下面的代码。
router.post('/login', function(req, res, next){
// console.log(req.body);
passport.authenticate('local', function(err, user, info){
// console.log('Error: ' + err);
// console.log('User ID: ' + user.id + ' User Email: ' + user.email + ' User Salt: ' + user.salt + ' User Hash: ' + user.hash);
// console.log('Info: ' + info);
console.log(err, user, info);
if(err) {
res.json({message: err.message});
}
if(!user) {
res.json({message: info.message});
}
req.logIn(user, function(err){
if(err) {
res.json({message: err.message});
} else {
return res.redirect('/');
}
});
})(req, res, next)});
对于 app.use,我需要以下 app.use...请注意“require”行,因为它对于连接到您尝试导入的单独护照文件非常重要。
app.use(passport.initialize());
app.use(passport.session());
require('../config/ppc.js')(passport);
app.use(app._router);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/../client/src/App'));
现在,我可以点击“serializeUser”,但我不能点击“deserializeUser”。
我正在使用 node js 作为后端并作为前端做出反应。在后端,我想创建一个单独的文件来处理每个 passport.js 模块,如下所示,并将 passport.js 导入 user.js 文件,以便可以将用户输入数据传递给护照文件并在需要时归还。我 运行 遇到的问题是找到正确导入和导出 passport.js 文件的方法。任何帮助就足够了,甚至“那不可能”也可以。
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mysql = require('mysql2');
const crypto = require('crypto');
const session = require('express-session');
const SqlDbStore = require('express-mysql-session')(session);
const db = require('./db');
app.use(session({
key: 'session_cookie_name',
secret: 'session_cookie_secret',
store: new SqlDbStore({
host: 'localhost',
port: 3306,
user: 'root',
password: 'xxxxxxxxxx',
database: 'xxxxxxxxxx',
}),
resave: false,
saveUninitialized: false,
cookie:{
maxAge:1000*60*60*24,
}
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(express.static(__dirname + '/views'));
db.connect((err) => {
if (!err) {
console.log("BD Connected");
} else {
console.log("BD Conection Failed");
console.log(err.message);
}
});
const customFields={
firstNameField: 'usersFirstName',
lastNameField: 'usersLastName',
emailField: 'usersEmail',
passwordField:'usersPassword',
confirmPasswordField:'usersConfirmedPassword'
};
/*Passport JS*/
const verifyCallback=(email,password,done)=>{
connection.query('SELECT * FROM USER WHERE usersEmail= ?', [email], function(error, results, fields) {
if (error) {
console.log('query error: ' + error);
return done(error);
}
if(results.length==0) {
return done(null,false, {message: 'Account is not recognized.'});
}
const isValid=validPassword(password, results[0].EncryptHash, results[0].EncryptPassword);
user={id:results[0].ID, email:results[0].usersEmail, hash:results[0].EncryptHash, password:results[0].EncryptPassword};
if(isValid) {
return done(null,user);
} else {
return done(null,false, {message: 'Password is incorrect.'});
}
});
};
const strategy = new LocalStrategy(customFields, verifyCallback);
passport.use(strategy);
passport.serializeUser((user,done)=>{
console.log("Inside serialize");
done(null, user.id);
});
passport.deserializeUser(function(userId, done) {
console.log('deserializeUser');
connection.query('SELECT * FROM User WHERE ID = ? ', [userId], function(error, results) {
done(null, results[0]);
});
});
/*middleware*/
function validPassword(password, hash, salt){
const hashVerify=crypto.pbkdf2Sync(password, salt, 10000, 60, 'sha512').toString("hex");
return hash === hashVerify;
};
function genPassword(password) {
var salt=crypto.randomBytes(32).toString('hex');
var genhash=crypto.pbkdf2Sync(password, salt, 10000, 60, 'sha512').toString('hex');
return {salt:salt, hash:genhash}
};
function checkAuthentication(req,res,next){
if(req.isAuthenticated()){
//req.isAuthenticated() will return true if user is logged in
next();
} else {
res.redirect("/login");
}
};
User.JS
const express = require('express');
const router = express.Router();
const db = require('../config/db');
const passport = require('../config/passport');
const routes = require('')('passport');
router.post('/register', (req, res) => {
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const email = req.body.email;
const password = req.body.password;
const saltHash = genPassword(password);
const salt = passport.saltHash.salt;
const hash = passport.saltHash.hash;
db.query('SELECT * FROM Users WHERE UsersEmail = ? ', [email], (err, results) => {
if (err){
console.log(err)
} else if (results.length > 0) {
res.json({ message: 'Email is already registered!' });
} else {
db.query('INSERT INTO Users (UsersFirstName, UsersLastName, UsersEmail, UsersPasswordHash, UsersPasswordSalt) VALUES (?, ?, ?, ?, ?)', [firstName, lastName, email, hash, salt], (err, results) => {
if (err){
console.log(err);
};
res.send(results);
});
}
})
});
router.post('/login', passport.authenticate('local'));
module.exports = {router, passport};
请注意,我想要转到此根目录的主要原因是为了防止在控制台中访问以下代码。
app.use(session({
key: 'session_cookie_name',
secret: 'session_cookie_secret',
store: new SqlDbStore({
host: 'localhost',
port: 3306,
user: 'root',
password: 'xxxxxxxxxx',
database: 'xxxxxxxxxx',
}),
resave: false,
saveUninitialized: false,
cookie:{
maxAge:1000*60*60*24,
}
}));
更新: 所以我能够进行以下更改以更接近。但是,我收到一条错误消息,指出本地护照“缺少凭据”。
代码更改: User.JS
const express = require('express');
const app = express();
const router = express.Router();
const db = require('../config/db');
const session = require('express-session');
const SqlDbStore = require('express-mysql-session')(session);
const passport = require('passport');
const bodyParser = require('body-parser');
const mysql = require('mysql2');
const crypto = require('crypto');
const LocalStrategy = require('passport-local').Strategy;
//----------------------------------------- BEGINNING OF PASSPORT MIDDLEWARE AND SETUP ---------------------------------------------------
app.use(session({
key: 'session_cookie_name',
secret: 'session_cookie_secret',
store: new SqlDbStore({
host: 'localhost',
port: 3306,
user: 'root',
password: 'xxxxxxxxxx',
database: 'xxxxxxxxxx',
}),
resave: false,
saveUninitialized: false,
cookie:{
maxAge:1000*60*60*24,
}
}));
app.use(passport.initialize());
app.use(passport.session());
require('../config/ppc.js')(passport);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.use(express.static(__dirname + '/index'));
/*passport middleware*/
function genPassword(password) {
var salt=crypto.randomBytes(32).toString('hex');
var genhash=crypto.pbkdf2Sync(password, salt, 10000, 60, 'sha512').toString('hex');
return {salt:salt, hash:genhash}
};
function checkAuthentication(req,res,next){
if(req.isAuthenticated()){
//req.isAuthenticated() will return true if user is logged in
next();
} else{
res.redirect("/login");
}
};
//----------------------------------------- END OF PASSPORT MIDDLEWARE AND SETUP ---------------------------------------------------
router.post('/register', (req, res) => {
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const email = req.body.email;
const password = req.body.password;
const saltHash = genPassword(password);
const salt = saltHash.salt;
const hash = saltHash.hash;
db.query('SELECT * FROM Users WHERE UsersEmail = ? ', [email], (err, results) => {
if (err){
console.log(err)
} else if (results.length > 0) {
res.json({ message: 'Email is already registered!' });
} else {
db.query('INSERT INTO Users (UsersFirstName, UsersLastName, UsersEmail, UsersPasswordHash, UsersPasswordSalt) VALUES (?, ?, ?, ?, ?)', [firstName, lastName, email, hash, salt], (err, results) => {
if (err){
console.log(err);
};
res.send(results);
});
}
})
});
router.post('/login', function(req, res, next){
console.log(req.body);
passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login'
}, function(err, user, info){
console.log(err, user, info);
if(err) {
res.render ('login ', {Title:' Login ', ErrorMessage: err. Message});
}
if(!user) {
res.render ('login ', {Title:' Login ', ErrorMessage: info. Message});
}
return req.logIn(user, function(err){
if(err) {
res.render ('login ', {Title:' Login ', ErrorMessage: err. Message});
} else {
return res.redirect('/project');
}
});
})(req, res, next);
});
module.exports = router;
ppc.js
const LocalStrategy = require('passport-local').Strategy;
const express = require('express');
const db = require('./db');
module.exports = function (passport) {
db.connect((err) => {
if (!err) {
console.log("BD Connected");
} else {
console.log("BD Conection Failed");
console.log(err.message);
}
});
const customFields={
firstNameField: 'firstName',
lastNameField: 'lastName',
emailField: 'email',
passwordField:'password',
confirmPasswordField:'passwordConfirmation'
};
/*Passport JS*/
const verifyCallback=(email,password,done)=>{
connection.query('SELECT * FROM USER WHERE usersEmail= ?', [email], function(error, results, fields) {
if (error) {
console.log('query error: ' + error);
return done(error);
}
if(results.length==0) {
return done(null,false, {message: 'Account is not recognized.'});
}
const isValid=validPassword(password, results[0].UsersPasswordHash, results[0].UsersPasswordSalt);
user={id:results[0].ID, email:results[0].usersEmail, hash:results[0].UsersPasswordHash, salt:results[0].UsersPasswordSalt};
if(isValid) {
return done(null,user);
} else{
return done(null,false, {message: 'Password is incorrect.'});
}
});
};
const strategy = new LocalStrategy(customFields, verifyCallback);
passport.use(strategy);
passport.serializeUser((user,done)=>{
console.log("Inside serialize");
done(null, user.id);
});
passport.deserializeUser(function(userId, done) {
console.log('deserializeUser');
connection.query('SELECT * FROM User WHERE ID = ? ', [userId], function(error, results) {
done(null, results[0]);
});
});
function validPassword(password, hash, salt){
const hashVerify=crypto.pbkdf2Sync(password, salt, 10000, 60, 'sha512').toString("hex");
return hash === hashVerify;
};
}
返回代码:
BD Connected
{ email: 'jondoetech@outlook.com', password: '1234' } null false { message: 'Missing credentials' }
Error: No default engine was specified
and no extension was provided at new View
所以这是我必须做的来解决我的问题。
为了登录,我不得不将代码更新为下面的代码。
router.post('/login', function(req, res, next){
// console.log(req.body);
passport.authenticate('local', function(err, user, info){
// console.log('Error: ' + err);
// console.log('User ID: ' + user.id + ' User Email: ' + user.email + ' User Salt: ' + user.salt + ' User Hash: ' + user.hash);
// console.log('Info: ' + info);
console.log(err, user, info);
if(err) {
res.json({message: err.message});
}
if(!user) {
res.json({message: info.message});
}
req.logIn(user, function(err){
if(err) {
res.json({message: err.message});
} else {
return res.redirect('/');
}
});
})(req, res, next)});
对于 app.use,我需要以下 app.use...请注意“require”行,因为它对于连接到您尝试导入的单独护照文件非常重要。
app.use(passport.initialize());
app.use(passport.session());
require('../config/ppc.js')(passport);
app.use(app._router);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/../client/src/App'));
现在,我可以点击“serializeUser”,但我不能点击“deserializeUser”。