<commit_before>/*jshint node: true*/
/**
 * @author lattmann / https://github.com/lattmann
 */

// based on http://iao.fi/myposts/passport_google_openid_migration


function init(app, logger, config) {
    'use strict';
    var expressSession = require('express-session'),
        passport = require('passport'),

        fs = require('fs'),
        Datastore = require('nedb'),
        users = new Datastore({filename: 'users.nedb', autoload: true}),
        allowedUsers = [],

        updateAllowedUsers = function (filename) {
            try {
                allowedUsers = JSON.parse(fs.readFileSync(filename));
                logger.debug('allowed users list was updated. ' + filename);
            } catch (e) {
                logger.warn(e);
            }
        };

    if (fs.existsSync('users.json')) {
        updateAllowedUsers('users.json');
    } else {
        fs.writeFileSync('users.json', JSON.stringify(allowedUsers));
    }

    fs.watch('.', function (event, fname) {
        if (fname === 'users.json') {
            updateAllowedUsers(fname);
        }
    });

    logger.debug('Auth module is initializing');

    app.use('/', expressSession(config.sessionParameters));
    app.use('/', passport.initialize());
    app.use('/', passport.session());


    app.use(function (req, res, next) {
        if (req.isAuthenticated()) {
            // set user id, if authenticated
            res.set('X-User-Id', req.session.passport.user);
        }

        // if the request start with auth pass it along
        if (req.path.substr(0, 6) === '/auth/') {
            return next();
        }

        if (config.authentication.allowGuests) {
            // if we allow guests then we are done here
            return next();
        }

        if (req.isAuthenticated() && req.user) {
            // iwe have a valid user

            if (allowedUsers.length > 0 &&
                allowedUsers.indexOf(req.user.emails[0].value) === -1) {
                // emails filed is defined in the config
                // we have to filter
                // if current user is not on the list we just redirect him to /auth/failed
                logger.error('Invalid user ' + req.user.displayName + ' ' + req.user.emails[0].value);
                req.session.authRedirect = req.path;
                res.redirect('/auth/failed');
                return;
            } else {
                // if user on the list, pass to the next route the request
                return next();
            }
        }

        // user is not authenticated yet, and requested a path which is not /auth/*
        // save the requested path (redirect him after a successful login - /auth/login/success
        req.session.authRedirect = req.path;
        // redirect him to the main login page
        res.redirect('/auth/login');
    });

    // FIXME: put provider specific strategies to separate file
    // GOOGLE SPECIFIC from here
    var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy,
        googleStrategyConfig = {
            callbackURL: config.server.publicUrl + '/auth/google/oauth2callback'
        },

        google,
        originalAuthorizationParams;
    logger.debug('Google OAuth2 is initializing');
    if (config.authentication.GOOGLE_CLIENT_ID && config.authentication.GOOGLE_CLIENT_SECRET) {
        googleStrategyConfig.clientID = config.authentication.GOOGLE_CLIENT_ID;
        googleStrategyConfig.clientSecret = config.authentication.GOOGLE_CLIENT_SECRET;
    } else {
        throw new Error('GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET have to be defined config.authentication.GOOGLE_*');
    }
<commit_msg>Log successful logins.<commit_after>/*jshint node: true*/
/**
 * @author lattmann / https://github.com/lattmann
 */

// based on http://iao.fi/myposts/passport_google_openid_migration


function init(app, logger, config) {
    'use strict';
    var expressSession = require('express-session'),
        passport = require('passport'),

        fs = require('fs'),
        Datastore = require('nedb'),
        users = new Datastore({filename: 'users.nedb', autoload: true}),
        allowedUsers = [],

        updateAllowedUsers = function (filename) {
            try {
                allowedUsers = JSON.parse(fs.readFileSync(filename));
                logger.debug('allowed users list was updated. ' + filename);
            } catch (e) {
                logger.warn(e);
            }
        };

    if (fs.existsSync('users.json')) {
        updateAllowedUsers('users.json');
    } else {
        fs.writeFileSync('users.json', JSON.stringify(allowedUsers));
    }

    fs.watch('.', function (event, fname) {
        if (fname === 'users.json') {
            updateAllowedUsers(fname);
        }
    });

    logger.debug('Auth module is initializing');

    app.use('/', expressSession(config.sessionParameters));
    app.use('/', passport.initialize());
    app.use('/', passport.session());


    app.use(function (req, res, next) {
        if (req.isAuthenticated()) {
            // set user id, if authenticated
            res.set('X-User-Id', req.session.passport.user);
        }

        // if the request start with auth pass it along
        if (req.path.substr(0, 6) === '/auth/') {
            return next();
        }

        if (config.authentication.allowGuests) {
            // if we allow guests then we are done here
            return next();
        }

        if (req.isAuthenticated() && req.user) {
            // iwe have a valid user

            if (allowedUsers.length > 0 &&
                allowedUsers.indexOf(req.user.emails[0].value) === -1) {
                // emails filed is defined in the config
                // we have to filter
                // if current user is not on the list we just redirect him to /auth/failed
                logger.error('Invalid user ' + req.user.displayName + ' ' + req.user.emails[0].value);
                req.session.authRedirect = req.path;
                res.redirect('/auth/failed');
                return;
            } else {
                // if user on the list, pass to the next route the request
                logger.info('Successful login ' + req.user.displayName + ' ' + req.user.emails[0].value);
                return next();
            }
        }

        // user is not authenticated yet, and requested a path which is not /auth/*
        // save the requested path (redirect him after a successful login - /auth/login/success
        req.session.authRedirect = req.path;
        // redirect him to the main login page
        res.redirect('/auth/login');
    });

    // FIXME: put provider specific strategies to separate file
    // GOOGLE SPECIFIC from here
    var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy,
        googleStrategyConfig = {
            callbackURL: config.server.publicUrl + '/auth/google/oauth2callback'
        },

        google,
        originalAuthorizationParams;
    logger.debug('Google OAuth2 is initializing');
    if (config.authentication.GOOGLE_CLIENT_ID && config.authentication.GOOGLE_CLIENT_SECRET) {
        googleStrategyConfig.clientID = config.authentication.GOOGLE_CLIENT_ID;
        googleStrategyConfig.clientSecret = config.authentication.GOOGLE_CLIENT_SECRET;
    } else {
        throw new Error('GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET have to be defined config.authentication.GOOGLE_*');
    }

{'fraction_non_alphanumeric': 0.12108587555436097, 'fraction_numerical': 0.0025534202392151592, 'mean_word_length': 2.0475020475020473, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, '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': '5166367', 'n_tokens_mistral': 2085, 'n_tokens_neox': 2009, 'n_words': 504}