Skip to content

Instantly share code, notes, and snippets.

@stephepush
Created October 8, 2021 02:21
Show Gist options
  • Save stephepush/ae10a37408a0d820d8d8730381e3ca67 to your computer and use it in GitHub Desktop.
Save stephepush/ae10a37408a0d820d8d8730381e3ca67 to your computer and use it in GitHub Desktop.
passport.js using mariadb and mysql2
const mysql = require('mysql2/promise');
const pool = mysql.createPool({
host: 'localhost',
port: 3306,
user: 'admin',
password: 'hello',
database: 'es_starter'
}); //maybe should be const options
const connection = pool;
class User {
constructor(username, hash, salt) {
//this.user_id = user_id;
this.username = username;
this.hash = hash;
this.salt = salt;
}
static findOne(username) {
console.log(username)
return connection.query(
"SELECT hash, salt FROM users WHERE username = ?", [username]
)
};
save() {
/* return connection.execute(
"INSERT INTO users (username, hash, salt) VALUES (?, ?, ?)", [this.username, this.hash, this.salt] //do i need to use 'this'?
) */
try {
return connection.execute(
"INSERT INTO users (username, hash, salt) VALUES (?, ?, ?)", [this.username, this.hash, this.salt] //do i need to use 'this'?,
).catch(e => {
console.log('error', e);
});
} catch (e) {
console.log('error', e);
}
}
}
/* module.exports = {
connection: connection,
User: User,
pool: pool
}; */
module.exports.connection = connection;
module.exports.pool = pool;
/*pool and connection are kinda sorta redundant but why not?*/
module.exports.User = User;
{ username: 'snoopy2' } //from console.log on line 25 of database.js
user: undefined
password: hello,
hash: undefined,
salt: undefined //from console.og that starts on line 27 of passport.js
TypeError [ERR_INVALID_ARG_TYPE]: The "salt" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined
at check (internal/crypto/pbkdf2.js:59:10)
at Object.pbkdf2Sync (internal/crypto/pbkdf2.js:46:5)
at validatesPassword (/home/stephen/Documents/AuthSandbox/express_session_auth_starter/lib/passwordUtils.js:20:31)
at /home/stephen/Documents/AuthSandbox/express_session_auth_starter/config/passport.js:32:29
at processTicksAndRejections (internal/process/task_queues.js:95:5)
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const connection = require('./database');
const { User } = require('./database')
const validatesPassword = require('../lib/passwordUtils').validatesPassword;
const customFields = {
/*Changes what field attributes passport looks for*/
usernameFIeld: 'uname',
passwordField: 'pw'
}
/*the following function is a es6/promisified twist of
whats found in the passport documentation
its promisified and modularized to make the code easier
to read*/
const verifyCallback = (username, password, done) => {
//console.log(username);
/*User.findOne references static class method in
database.js*/
User.findOne({ username: username })
.then((user) => {
//^returns user
if (!user) { return done(null, false) }
//no error, but also no user
console.log(
`user: ${user.username}
password: ${password},
hash: ${user.hash},
salt: ${user.salt}`)
const isValid = validatesPassword(password, user.hash, user.salt)
//^comparing user entered password to hash and salt
if (isValid) {
return done(null, user);
//sucessfully authenticates
} else {
return done(null, false)
//unsuccesfully authenticated, don't allow
}
})
.catch((err) => {
done(err)
});
}
const strategy = new LocalStrategy(customFields, verifyCallback);
passport.use(strategy);
passport.serializeUser((user, done) => {
done(null, user.id);
})
passport.deserializeUser((userId, done) => {
User.findById(userId)
.then((user) => {
done(null, user);
})
.catch(err => done(err))
})
onst crypto = require('crypto');
function genPassword(password) {
let salt = crypto.randomBytes(32).toString('hex'); //seasoning recipe
let genHash = crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha512').toString('hex');
console.log("genHash = " + genHash)
console.log('\n')
console.log("salt = " + salt)
return {
salt: salt,
hash: genHash
}
}
function validatesPassword(password, hash, salt) {
const hashVerify = crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha512').toString('hex');
console.log(hash)
console.log('\n')
console.log(hashVerify)
return hash === hashVerify;
}
module.exports.validatesPassword = validatesPassword;
module.exports.genPassword = genPassword;
//router.post code:
router.post('/login', passport.authenticate('local', { failureRedirect: "/login-failure", successRedirect: 'login-success' }));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment