Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // config/passport.js
- // load all the things we need
- var LocalStrategy = require('passport-local').Strategy;
- var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
- // load up the user model
- var mysql = require('mysql');
- var bcrypt = require('bcrypt-nodejs');
- var dbconfig = require('./database');
- var connection = mysql.createConnection(dbconfig.connection);
- connection.on('error', function(err){
- console.error("MySQL Error: ", err);
- })
- connection.query('USE ' + dbconfig.database);
- // expose this function to our app using module.exports
- module.exports = function(passport) {
- // =========================================================================
- // passport session setup ==================================================
- // =========================================================================
- // required for persistent login sessions
- // passport needs ability to serialize and unserialize users out of session
- // used to serialize the user for the session
- passport.serializeUser(function(user, done) {
- done(null, user.id);
- });
- // used to deserialize the user
- passport.deserializeUser(function(id, done) {
- connection.query("SELECT * FROM users WHERE id = ? ",[id], function(err, rows){
- if(err) console.error("Deserialization Error: ", err);
- done(err, rows[0]);
- });
- });
- // =========================================================================
- // LOCAL REGISTRATION ======================================================
- // =========================================================================
- // we are using named strategies since we have one for login and one for signup
- // by default, if there was no name, it would just be called 'local'
- passport.use(
- 'local-signup',
- new LocalStrategy({
- // by default, local strategy uses username and password, we will override with email
- usernameField : 'username',
- passwordField : 'password',
- passReqToCallback : true // allows us to pass back the entire request to the callback
- },
- function(req, username, password, done) {
- // find a user whose email is the same as the forms email
- // we are checking to see if the user trying to login already exists
- connection.query("SELECT * FROM users WHERE username = ?",[username], function(err, rows) {
- if (err)
- return done(err);
- if (rows.length) {
- return done(null, false, req.flash('signupMessage', 'That username is already taken.'));
- } else {
- // if there is no user with that username
- // create the user
- var newUserMysql = {
- username: username,
- password: bcrypt.hashSync(password, null, null), // use the generateHash function in our user model
- email: req.body.email,
- first_name: req.body.first_name,
- last_name: req.body.last_name,
- company: req.body.company,
- cryptos_experience: req.body.cryptos_experience
- };
- console.log(newUserMysql);
- var insertQuery = "INSERT INTO users ( username, password, email, first_name, last_name, company, cryptos_experience ) values (?, ?, ?, ?, ?, ?, ?)";
- connection.query(insertQuery,[newUserMysql.username, newUserMysql.password, newUserMysql.email, newUserMysql.first_name, newUserMysql.last_name, newUserMysql.company, newUserMysql.cryptos_experience],
- function(err, rows) {
- newUserMysql.id = rows.insertId;
- req.session.passport.user = newUserMysql.id;
- return done(null, newUserMysql);
- });
- }
- });
- })
- );
- // =========================================================================
- // LOCAL LOGIN =============================================================
- // =========================================================================
- // we are using named strategies since we have one for login and one for signup
- // by default, if there was no name, it would just be called 'local'
- passport.use(
- 'local-login',
- new LocalStrategy({
- // by default, local strategy uses username and password, we will override with email
- usernameField : 'username',
- passwordField : 'password',
- passReqToCallback : true // allows us to pass back the entire request to the callback
- },
- function(req, username, password, done) { // callback with email and password from our form
- if(!password || password.length === 0)
- return done(null, false, req.flash('loginMessage', 'Password cannot be blank.'));
- connection.query("SELECT * FROM users WHERE username = ?",[username], function(err, rows){
- if (err)
- return done(err);
- if (!rows.length) {
- return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
- }
- // if the user is found but the password is wrong
- if (!bcrypt.compareSync(password, rows[0].password))
- return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
- if (rows[0].verified == '0') {
- req.not_verified = true;
- return done(null, false, req.flash('notVerified', rows[0])); // create the loginMessage and save it to session as flashdata
- }
- // all is well, return successful user
- return done(null, rows[0]);
- });
- })
- );
- // =========================================================================
- // GOOGLE LOGIN ============================================================
- // =========================================================================
- // Use the GoogleStrategy within Passport.
- // Strategies in Passport require a `verify` function, which accept
- // credentials (in this case, an accessToken, refreshToken, and Google
- // profile), and invoke a callback with a user object.
- passport.use(new GoogleStrategy({
- clientID: process.env.GOOGLE_CLIENT_ID || '---somekey---.apps.googleusercontent.com',
- clientSecret: process.env.GOOGLE_CLIENT_SECRET || '---sme-other-shit----',
- callbackURL: "/auth/google/callback",
- passReqToCallback : true // allows us to pass back the entire request to the callback
- },
- function(req, accessToken, refreshToken, profile, done) {
- connection.query("SELECT * FROM users WHERE google_id = ?", [profile.id], function(err, rows){
- if(err) {
- console.error("SQL Error: ", err);
- return done(err);
- }
- if (rows.length && rows.length > 0){
- //Return user if found
- req.session.passport.user=rows[0].id;
- return done(null, rows[0]);
- } else {
- var newUserMysql = {
- username: 'G-' + profile.id,
- google_id: profile.id,
- email: profile.emails[0].value,
- first_name: profile.name.givenName,
- last_name: profile.name.familyName
- };
- console.log(newUserMysql);
- var insertQuery = "INSERT INTO users ( username, google_id, email, first_name, last_name, verified) values (?, ?, ?, ?, ?, ?)";
- connection.query(insertQuery,[newUserMysql.username, newUserMysql.google_id, newUserMysql.email, newUserMysql.first_name, newUserMysql.last_name, true],
- function(err, rows) {
- newUserMysql.id = rows.insertId;
- req.session.passport.user = newUserMysql.id;
- return done(null, newUserMysql);
- }
- );
- }
- })
- }
- ));
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement