-
Notifications
You must be signed in to change notification settings - Fork 17
Description
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql2/promise');
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const app = express();
const PORT = 3000;
// Middleware
app.use(bodyParser.json());
// MySQL Connection Pool
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'magento2',
});
// JWT Secret Key
const JWT_SECRET = 'your_secret_key';
// Authenticate User
app.post('/login', async (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ message: 'Email and password are required.' });
}
try {
// Fetch user from Magento customer_entity table
const [rows] = await pool.query(
'SELECT entity_id, email, password_hash FROM customer_entity WHERE email = ?',
[email]
);
if (rows.length === 0) {
return res.status(401).json({ message: 'Invalid credentials.' });
}
const user = rows[0];
// Extract hash and salt
const [storedHash, salt] = user.password_hash.split(':');
// Hash the input password with the salt
const inputHash = crypto.createHash('sha256').update(password + salt).digest('hex');
// Compare the hashes
if (inputHash !== storedHash) {
return res.status(401).json({ message: 'Invalid credentials.' });
}
// Generate JWT
const token = jwt.sign({ id: user.entity_id, email: user.email }, JWT_SECRET, {
expiresIn: '1h',
});
res.json({ token });
} catch (error) {
console.error(error);
res.status(500).json({ message: 'An error occurred while logging in.' });
}
});
// Start the server
app.listen(PORT, () => {
console.log(Server is running on http://localhost:${PORT});
});
Or
const express = require('express');
const bodyParser = require('body-parser');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const mysql = require('mysql2/promise');
const crypto = require('crypto');
const app = express();
const PORT = 3000;
// Middleware
app.use(bodyParser.json());
app.use(passport.initialize());
// MySQL Connection Pool
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'magento2',
});
// Passport Local Strategy
passport.use(
new LocalStrategy(
{ usernameField: 'email', passwordField: 'password' },
async (email, password, done) => {
try {
// Fetch user from Magento database
const [rows] = await pool.query(
'SELECT entity_id, email, password_hash FROM customer_entity WHERE email = ?',
[email]
);
if (rows.length === 0) {
return done(null, false, { message: 'Invalid email or password.' });
}
const user = rows[0];
const [storedHash, salt] = user.password_hash.split(':');
// Hash the provided password with the stored salt
const inputHash = crypto
.createHash('sha256')
.update(password + salt)
.digest('hex');
// Compare hashes
if (inputHash !== storedHash) {
return done(null, false, { message: 'Invalid email or password.' });
}
// Authentication successful
return done(null, { id: user.entity_id, email: user.email });
} catch (error) {
console.error(error);
return done(error);
}
}
)
);
// Serialize User
passport.serializeUser((user, done) => {
done(null, user.id);
});
// Deserialize User
passport.deserializeUser(async (id, done) => {
try {
const [rows] = await pool.query('SELECT entity_id, email FROM customer_entity WHERE entity_id = ?', [id]);
if (rows.length === 0) {
return done(null, false);
}
done(null, rows[0]);
} catch (error) {
done(error);
}
});
// Login Route
app.post('/login', passport.authenticate('local', { session: false }), (req, res) => {
res.json({ message: 'Login successful!', user: req.user });
});
// Start the server
app.listen(PORT, () => {
console.log(Server is running on http://localhost:${PORT});
});