Issue
Although I am pretty new to software development, I have an intermediate understanding of exporting and importing data between files. However, for some reason, when trying to create a config file for Passport.js and trying to import that file into my Index.js file, I hit a brick wall. Something tells me that it could be a rookie mistake, but I’m almost sure that I probably need to move some functions over. Any advice would genuinely do. My code is below for a visual view.
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};
Update:
Question is reposted with more information on Export and Import Passport.JS Issues.
Solution
More information is located on Export and Import Passport.JS Issues. I assumed since this post was getting no attention at all, I may have either been lacking details of my issue and explaining everything else or just had not details at all.
Answered By – JonD
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0