Skip to content

Instantly share code, notes, and snippets.

@oorjitchowdhary
Last active July 9, 2023 00:57
Show Gist options
  • Save oorjitchowdhary/2644c9eca63978c024958d64274fb5f0 to your computer and use it in GitHub Desktop.
Save oorjitchowdhary/2644c9eca63978c024958d64274fb5f0 to your computer and use it in GitHub Desktop.
Passport.js + Firestore auth config
require('dotenv').config();
const firebaseAdmin = require('firebase-admin');
firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert({
"type": process.env.TYPE,
"project_id": process.env.PROJECT_ID,
"private_key_id": process.env.PRIVATE_KEY_ID,
"private_key": process.env.PRIVATE_KEY.replace(/\\n/g, '\n'),
"client_email": process.env.CLIENT_EMAIL,
"client_id": process.env.CLIENT_ID,
"auth_uri": process.env.AUTH_URI,
"token_uri": process.env.TOKEN_URI,
"auth_provider_x509_cert_url": process.env.AUTH_PROVIDER_CERT_URL,
"client_x509_cert_url": process.env.CLIENT_CERT_URL
}),
});
const db = firebaseAdmin.firestore();
module.exports = db;
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcryptjs');
const db = require('../config/db');
const User = db.collection('users');
module.exports = passport => {
passport.use(
new LocalStrategy({ usernameField: 'username' }, (username, password, done) => {
const user = User.doc(username).get()
.then(user => {
bcrypt.compare(password, user.data()['password'], (err, match) => {
if (err) throw err;
if (!match) { return done(null, false, { message: 'Password does not match.' }); }
else { return done(null, user); }
});
})
.catch(err => {
console.log(err);
return done(null, false, { message: 'No user found.' });
});
})
);
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
const user = User.doc(id).get()
.then(user => done(null, user))
.catch(err => done(err, user));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment