创建 Passport.js 配置导出文件并导入到 Index.js

Creating a Passport.js Config Export File and Import into Index.js

虽然我是软件开发的新手,但我对在文件之间导出和导入数据有一定的了解。但是,出于某种原因,在尝试为 Passport.js 创建配置文件并将该文件导入我的 Index.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");
     }
 };

Index.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};

更新: 问题已重新发布,其中包含有关 .

的更多信息

更多信息位于 。我假设因为这个 post 根本没有引起注意,所以我可能缺乏问题的详细信息并解释其他所有内容,或者根本没有详细信息。