<commit_before>const _ = require('lodash');
const passport = require('passport');
const request = require('request');
const InstagramStrategy = require('passport-instagram').Strategy;
const LocalStrategy = require('passport-local').Strategy;
const FacebookStrategy = require('passport-facebook').Strategy;
const TwitterStrategy = require('passport-twitter').Strategy;
const GitHubStrategy = require('passport-github').Strategy;
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
const LinkedInStrategy = require('passport-linkedin-oauth2').Strategy;
const OpenIDStrategy = require('passport-openid').Strategy;
const OAuthStrategy = require('passport-oauth').OAuthStrategy;
const OAuth2Strategy = require('passport-oauth').OAuth2Strategy;

const User = require('../models/User');
const Models = require('../models/postgresModels');

passport.serializeUser((user, done) => {
	done(null, user.id);
});

passport.deserializeUser((id, done) => {
	Models.Users.find({where: {id: id}}).then(function(user){
		done(null, user);
	}).error(function(err){
		done(err, null);
	});
});


/**
 * Sign in using Email and Password.
 */

passport.use(new LocalStrategy({
	usernameField: 'email',
	passwordField: 'password',
	passReqToCallback: true
	}, (req, email, password, done) => {
	Models.Users.findOne({ where: {email: email } })
			.then(function (user) {
				if (user !== null) {
					console.log('[AUTH] Success with email: ' + user.email + ' and password (md5-hash): ' + user.password);
					return done(null, user);
				}
				else {
					console.log('[AUTH] Error with email: ' + email + ' and password:' + password);
					return done(null, false);
				}
			})

/*
	User.findOne({ email: email.toLowerCase() }, (err, user) => {
		if (!user) {
			return done(null, false, { msg: `Email ${email} not found.` });
		}
		user.comparePassword(password, (err, isMatch) => {
			if (isMatch) {
				return done(null, user);
			}
			return done(null, false, { msg: 'Invalid email or password.' });
		});
	});
*/
}));


/*
passport.use(new LocalStrategy(
	function (email, password, done) {
		Models.User.find({ where: {email: email, password: crypto.createHash('md5').update(password).digest("hex") } })
			.success(function (user) {
				if (user !== null) {
					console.log('[AUTH] Success with email: ' + user.email + ' and password (md5-hash): ' + user.password);
					return done(null, user);
				}
				else {
					console.log('[AUTH] Error with email: ' + email + ' and password:' + password);
					console.log('[AUTH] md5-hash of passed password: ' + crypto.createHash('md5').update(password).digest("hex"));
					return done(null, false);
				}
			})
	}
));
*/

// Serialized and deserialized methods when got from session
/*
passport.serializeUser(function (user, done) {
	done(null, user);
});
passport.deserializeUser(function (user, done) {
	done(null, user);
});
*/

/**
 * OAuth Strategy Overview
 *
 * - User is already logged in.
 *	 - Check if there is an existing account with a provider id.
 *		 - If there is, return an error message. (Account merging not supported)
 *		 - Else link new OAuth account with currently logged-in user.
 * - User is not logged in.
 *	 - Check if it's a returning user.
 *		 - If returning user, sign in and we are done.
 *		 - Else check if there is an existing account with user's email.
 *			 - If there is, return an error message.
 *			 - Else create a new account.
 */

/**
 * Sign in with Google.
 */
passport.use(new GoogleStrategy({
	clientID: process.env.GOOGLE_ID,
	clientSecret: process.env.GOOGLE_SECRET,
	callbackURL: '/auth/google/callback',
	passReqToCallback: true
}, (req, accessToken, refreshToken, profile, done) => {
	if (req.user) {
		var tokensArray = req.user.tokens || [];
		tokensArray.push({ kind: 'google', accessToken });
		Models.Users.update({
			google: profile.id,
			tokens: tokensArray,
			name: user.name || profile.displayName
		
		},{
			where: {google: profile.id}
		}).then(function(user){
			req.flash('info', { msg: 'Google account has been linked.' });
			res.redirect('/account');
		})
		
		
/*<commit_msg>typos<commit_after>const _ = require('lodash');
const passport = require('passport');
const request = require('request');
const InstagramStrategy = require('passport-instagram').Strategy;
const LocalStrategy = require('passport-local').Strategy;
const FacebookStrategy = require('passport-facebook').Strategy;
const TwitterStrategy = require('passport-twitter').Strategy;
const GitHubStrategy = require('passport-github').Strategy;
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
const LinkedInStrategy = require('passport-linkedin-oauth2').Strategy;
const OpenIDStrategy = require('passport-openid').Strategy;
const OAuthStrategy = require('passport-oauth').OAuthStrategy;
const OAuth2Strategy = require('passport-oauth').OAuth2Strategy;

const User = require('../models/User');
const Models = require('../models/postgresModels');

passport.serializeUser((user, done) => {
	done(null, user.id);
});

passport.deserializeUser((id, done) => {
	Models.Users.find({where: {id: id}}).then(function(user){
		done(null, user);
	}).error(function(err){
		done(err, null);
	});
});


/**
 * Sign in using Email and Password.
 */

passport.use(new LocalStrategy({
	usernameField: 'email',
	passwordField: 'password',
	passReqToCallback: true
	}, (req, email, password, done) => {
	Models.Users.findOne({ where: {email: email } })
			.then(function (user) {
				if (user !== null) {
					console.log('[AUTH] Success with email: ' + user.email + ' and password (md5-hash): ' + user.password);
					return done(null, user);
				}
				else {
					console.log('[AUTH] Error with email: ' + email + ' and password:' + password);
					return done(null, false);
				}
			})

/*
	User.findOne({ email: email.toLowerCase() }, (err, user) => {
		if (!user) {
			return done(null, false, { msg: `Email ${email} not found.` });
		}
		user.comparePassword(password, (err, isMatch) => {
			if (isMatch) {
				return done(null, user);
			}
			return done(null, false, { msg: 'Invalid email or password.' });
		});
	});
*/
}));


/*
passport.use(new LocalStrategy(
	function (email, password, done) {
		Models.User.find({ where: {email: email, password: crypto.createHash('md5').update(password).digest("hex") } })
			.success(function (user) {
				if (user !== null) {
					console.log('[AUTH] Success with email: ' + user.email + ' and password (md5-hash): ' + user.password);
					return done(null, user);
				}
				else {
					console.log('[AUTH] Error with email: ' + email + ' and password:' + password);
					console.log('[AUTH] md5-hash of passed password: ' + crypto.createHash('md5').update(password).digest("hex"));
					return done(null, false);
				}
			})
	}
));
*/

// Serialized and deserialized methods when got from session
/*
passport.serializeUser(function (user, done) {
	done(null, user);
});
passport.deserializeUser(function (user, done) {
	done(null, user);
});
*/

/**
 * OAuth Strategy Overview
 *
 * - User is already logged in.
 *	 - Check if there is an existing account with a provider id.
 *		 - If there is, return an error message. (Account merging not supported)
 *		 - Else link new OAuth account with currently logged-in user.
 * - User is not logged in.
 *	 - Check if it's a returning user.
 *		 - If returning user, sign in and we are done.
 *		 - Else check if there is an existing account with user's email.
 *			 - If there is, return an error message.
 *			 - Else create a new account.
 */

/**
 * Sign in with Google.
 */
passport.use(new GoogleStrategy({
	clientID: process.env.GOOGLE_ID,
	clientSecret: process.env.GOOGLE_SECRET,
	callbackURL: '/auth/google/callback',
	passReqToCallback: true
}, (req, accessToken, refreshToken, profile, done) => {
	if (req.user) {
		var tokensArray = req.user.tokens || [];
		tokensArray.push({ kind: 'google', accessToken });
		Models.Users.update({
			google: profile.id,
			tokens: tokensArray,
			name: req.user.name || profile.displayName
		
		},{
			where: {google: profile.id}
		}).then(function(user){
			req.flash('info', { msg: 'Google account has been linked.' });
			res.redirect('/account');
		})
		
		
/*
{'fraction_non_alphanumeric': 0.16394441735738663, 'fraction_numerical': 0.0021940516821062897, 'mean_word_length': 3.936823104693141, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '762638', 'n_tokens_mistral': 2818, 'n_tokens_neox': 2547, 'n_words': 670}