<commit_before>var request = require("request");
var passport = require('passport');
var githubStrategy = require('passport-github').Strategy;

var GITHUB_CLIENT_ID = process.env.GITHUB_CLIENT_ID;
var GITHUB_CLIENT_SECRET = process.env.GITHUB_CLIENT_SECRET;
var CONTEXT_URI = process.env.CONTEXT_URI;
var mongoDbConnection = require('./lib/connection.js');


module.exports = function (app) {

    var setSession = function (req, user) {
        req.session.username = user.username;
        req.session.encodedUsername = user.encodedUsername;
        req.session.githubUsername = user.githubUser.username;
        req.session.avatarUrl = user.githubUser._json.avatar_url;
    };

    var handleGithubCallback = function (req, res) {
        var githubUser = req.user.profile;
        req.session.githubAccessToken = req.user.accessToken;

        var isNewUser = function (user) {
            return !user;
        };
        var isUserRegisteredWithOneself = function (user) {
            return user && user.username;
        };
        var redirect = function (user, url) {
            res.redirect(CONTEXT_URI + url + "?username=" + user.username);
        };
        var insertGithubProfileInDb = function () {
            var options = {
                url: "https://api.github.com/user/emails?access_token=" + req.user.accessToken,
                headers: {
                    "User-Agent": "Quantified Dev Localhost"
                }
            };
            request(options, function (err, res, body) {
                if (!err) {
                    var userEmails = JSON.parse(body);
                    for (var i in userEmails) {
                        githubUser.emails.push(userEmails[i]);
                    }
                    var githubUserRecord = {
                        githubUser: githubUser,
                        registeredOn: new Date()
                    };
                    mongoDbConnection(function (qdDb) {
                        qdDb.collection('users').insert(githubUserRecord, function (err, insertedRecords) {
                            if (err) {
                                res.status(500).send("Database error");
                            } else {
                                req.session.githubUsername = githubUser.username;
                                req.session.avatarUrl = githubUser._json.avatar_url;
                                redirect(githubUser, "/claimUsername");
                            }
                        });
                    });
                } else {
                    res.status(500).send("Could not fetch email addresses for user.");
                }
            });
        };

        var creditUserSignUpToApp = function(){
            var attributeUserToApp = function(appId){
                var byAppId = {
                    "appId": appId
                },

                updateObject = {
                    "$push": {
                        "users": githubUser.username
                    }
                };

                mongoDbConnection(function (qdDb) {
                    qdDb.collection('registeredApps').update(byAppId, updateObject, function(){
                        console.log("New user " + githubUser.username + " assigned to: " + appId);
                    });
                });
            };

            var mapUserAndAppUsingStream = function(){
                var redirectUrl = req.session.redirectUrl;
                if(redirectUrl.match("/v1/streams")) {
                    var tokenisedUrl = redirectUrl.split("/"),
                    byStreamId = {
                        "streamid": tokenisedUrl[3]
                    };
                    
                    mongoDbConnection(function(qdDb) {
                        qdDb.collection('stream').findOne(byStreamId, function(err, stream){
                            if(!err && stream){
                                attributeUserToApp(stream.appId);
                            }
                        });
                    });
                }
            };
            
            //main
            mapUserAndAppUsingStream();
        }; //end creditUserSignUpToApp


        //main
        var byGitHubUsername = {
            "githubUser.username": githubUser.username
        };
        mongoDbConnection(function (qdDb) {
            qdDb.collection('users').findOne(byGitHubUsername, function (err, user) {
                if (isNewUser(user)) {
                    creditUserSignUpToApp();
                    insertGithubProfileInDb();
                } else if (isUserRegisteredWithOneself(user)) {
                    setSession(req, user);
                    if (req.session.redirectUrl) {
                        var redirectUrl = req.session.redirectUrl;
                        delete req.session.redirectUrl;
                        if(redirectUrl.match("/v1/streams")) {
                            var tokenisedUrl = redirectUrl.split("/");
                            tokenisedUrl[2] = "users";
                            tokenisedUrl[3] = req.session.username;
                            redirectUrl = tokenisedUrl.join("/");
                        }
                        res.cookie('_eun', req.session.encodedUsername);
                        res.redirect(redirectUrl);
                    } else {
                        redirect(user, "/dashboard");
                    }
                } else {
                    req.session.githubUsername = user.githubUser.username;
                    req.session.avatarUrl = user.githubUser._json.avatar_url;
                    redirect(githubUser, "/claimUsername");
                }
            });
        });
    };

    passport.serializeUser(function (user, done) {
        done(null, user);
    });

    passport.deserializeUser(function (obj, done) {
        done(null, obj);
    });

    passport.use(new githubStrategy({
            clientID: GITHUB_CLIENT_ID,
            clientSecret: GITHUB_CLIENT_SECRET,<commit_msg>-- Refactored githuboAuth.js<commit_after>var request = require("request");
var passport = require('passport');
var githubStrategy = require('passport-github').Strategy;
var q = require('q');
var GITHUB_CLIENT_ID = process.env.GITHUB_CLIENT_ID;
var GITHUB_CLIENT_SECRET = process.env.GITHUB_CLIENT_SECRET;
var CONTEXT_URI = process.env.CONTEXT_URI;
var mongoRepository = require('./mongoRepository.js');

module.exports = function (app) {
    var setSession = function (req, user) {
        req.session.username = user.username;
        req.session.encodedUsername = user.encodedUsername;
        req.session.githubUsername = user.githubUser.username;
        req.session.avatarUrl = user.githubUser._json.avatar_url;
    };
    var fetchGithubUserEmails = function (accessToken) {
        var deferred = q.defer();
        var options = {
            url: "https://api.github.com/user/emails?access_token=" + accessToken,
            headers: {
                "User-Agent": "Quantified Dev Localhost"
            }
        };
        request(options, function (err, res, body) {
            if (!err) {
                deferred.resolve(JSON.parse(body));
            }
            else {
                deferred.reject(err);
            }
        });
        return deferred.promise;
    };
    var handleGithubCallback = function (req, res) {
        var githubUser = req.user.profile;
        req.session.githubAccessToken = req.user.accessToken;
        var isNewUser = function (user) {
            return !user;
        };
        var isUserRegisteredWithOneself = function (user) {
            return user && user.username;
        };
        var redirect = function (user, url) {
            res.redirect(CONTEXT_URI + url + "?username=" + user.username);
        };
        var insertGithubProfileInDb = function () {
            fetchGithubUserEmails(req.user.accessToken)
                .then(function (userEmails) {
                    for (var i in userEmails) {
                        githubUser.emails.push(userEmails[i]);
                    }
                    return {
                        githubUser: githubUser,
                        registeredOn: new Date()
                    };
                }, function (err) {
                    res.status(500).send("Could not fetch email addresses for user.");
                }).then(function (githubUserRecord) {
                    return mongoRepository.insert('users', githubUserRecord);
                }).then(function (docs) {
                    req.session.githubUsername = githubUser.username;
                    req.session.avatarUrl = githubUser._json.avatar_url;
                    redirect(githubUser, "/claimUsername");
                }, function (err) {
                    res.status(500).send("Database error");
                });
        };
        var creditUserSignUpToApp = function () {
            var attributeUserToApp = function (appId) {
                var byAppId = {
                        "appId": appId
                    },
                    updateObject = {
                        "$push": {
                            "users": githubUser.username
                        }
                    };
                mongoRepository.update('registeredApps', byAppId, updateObject)
                    .then(function () {
                        console.log("New user " + githubUser.username + " assigned to: " + appId);
                    });
            };

            var mapUserAndAppUsingStream = function () {
                var redirectUrl = req.session.redirectUrl;
                if (redirectUrl.match("/v1/streams")) {
                    var tokenisedUrl = redirectUrl.split("/"),
                        byStreamId = {
                            "streamid": tokenisedUrl[3]
                        };
                    mongoRepository.findOne('stream', byStreamId)
                        .then(function (stream) {
                            attributeUserToApp(stream.appId);
                        }, function (err) {
                        });
                }
            };

            //main
            mapUserAndAppUsingStream();
        }; //end creditUserSignUpToApp
        var byGitHubUsername = {
            "githubUser.username": githubUser.username
        };
        mongoRepository.findOne('users', byGitHubUsername)
            .then(function (user) {
                if (isNewUser(user)) {
                    creditUserSignUpToApp();
                    insertGithubProfileInDb();
                } else if (isUserRegisteredWithOneself(user)) {
                    setSession(req, user);
                    if (req.session.redirectUrl) {
                        var redirectUrl = req.session.redirectUrl;
                        delete req.session.redirectUrl;
                        if (redirectUrl.match("/v1/streams")) {
                            var tokenisedUrl = redirectUrl.split("/");
                            tokenisedUrl[2] = "users";
                            tokenisedUrl[3] = req.session.username;
                            redirectUrl = tokenisedUrl.join("/");
                        }
                        res.cookie('_eun', req.session.encodedUsername);
                        res.redirect(redirectUrl);
                    } else {
                        redirect(user, "/dashboard");
                    }
                } else {
                    req.session.githubUsername = user.githubUser.username;
                    req.session.avatarUrl = user.githubUser._json.avatar_url;
                    redirect(githubUser, "/claimUsername");
                }
            });
    };

    passport.serializeUser(function (user, done) {
        done(null, user);
    });

    passport.deserializeUser(function (obj, done) {
        done(null, obj);
    });

    passport.use(new githubStrategy({
            clientID: GITHUB_CLIENT_ID,
            clientSecret: GITHUB_CLIENT_SECRET,
{'fraction_non_alphanumeric': 0.10206460206460206, 'fraction_numerical': 0.0018315018315018315, 'mean_word_length': 1.3186643505114843, 'pattern_counts': {'":': 12, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7608874', 'n_tokens_mistral': 3042, 'n_tokens_neox': 2869, 'n_words': 505}