In the process of creating a custom login page using mongoDb, I am utilizing an unofficial login system. This system involves express, session-express, and passport.
The core functionality is encapsulated in a file called 'passport-config.js'. This file contains validation logic to compare user information from the login form with the database.
import LocalStrategy from 'passport-local'
LocalStrategy.Strategy
import bcrypt from 'bcrypt' // for password encryption
function initialize(passport, getUserByEmail, getUserById) {
const authenticateUser = async (email, password, done) => {
const user = getUserByEmail(email) // retrieves user data based on email from login form
// remaining code...
}
passport.use(new LocalStrategy({ usernameField: 'email' }, authenticateUser)) //calls authenticateUser with form data
}
export default initialize
The function within 'passport-config.js' is exported and then imported into server.js. It requires parameters such as (passport, functions to find users by email and ID)
In server.js:
import initializePassaport from '../passport-config.js' // import the function from passport-config.js
import passport from 'passport'
import users from "../models/User.js"; // retrieve model Schema from users database
initializePassaport(
passport,
email => users.findOne({"email": email}, {}, (err, user) => user) // fetches user based on provided email
id => users.findById(id, (err, user) => {email = user} => user) // fetches user based on ID
)
//more code...
An issue arises when passing parameters in 'server.js', instead of finding the user by email, it returns other values. This might be due to the value sent by the find() function in mongoDb being inaccessible outside the function.
A debug log was added: "email => users.findOne({"email": email}, {}, (err, user) => {console.log(user})". While it displays the correct value in the console, it doesn't pass the right value to the function.
Attempts were made to use return statements without success. Researching yielded no solutions to this problem.
Prior to integrating the database, the code worked flawlessly with a simple array:
const users = [ // example
{
"id": '167252944716',
"username": 'adm',
"email": 'adm@adm',
"password": '$2b$12$G/EwhnXj5P/y1NGTb5Sq4.OTY5m.BMferVHVJ27AtZGn8vt6qDsvi' //encrypted
}
]
initializePassaport(
passport,
email => users.find(user => user.email === email),
id => users.find(user => user.id === id)
)
If unclear, please provide feedback for clarification purposes. Thank you!