<commit_before>const express = require("express");
const passport = require("passport");
const bodyParser = require("body-parser");
const morgan = require("morgan");
const helmet = require("helmet");
const csurf = require("csurf");
const User = require("../models/user");
const session = require("cookie-session");
const fs = require("fs");
const path = require("path");

function HTTPServer(app) {
    var server = express();
    var httpServer = require("http").createServer(server);
    
    // Setup for parameters and bodies
    server.use(bodyParser.urlencoded({extended: false}));
    server.use(bodyParser.json());
    
    server.use(helmet());

    // Set rendering engine
    server.set("view engine", "pug");

    var setupRoutes = function(directories, modulesWithRoutes) {
        // Use public folder for resources
        server.use(express.static("public"));
        // Register module public directories
        directories.forEach((dir) => server.use(dir.root, dir.middleware));
        
        // Log to console
        if (app.config.debug) {
            // Log requests to console
            server.use(morgan("dev"));

            // Pretty-print JSON
            server.set("json spaces", 4);
        } else {
            var logInfo = {};
            if (fs.existsSync("/var/log/place")) logInfo.stream = require("stream-file-archive")({
                path: "/var/log/place/access-%Y-%m-%d.log",  // Write logs rotated by the day
                symlink: "/var/log/place/current.log",    // Maintain a symlink called current.log
                compress: true                // Gzip old log files
            });
            server.use(morgan("common", logInfo));
        }

        server.set("trust proxy", typeof app.config.trustProxyDepth === "number" ? app.config.trustProxyDepth : 0);

        if (app.logger.raven) server.use(app.logger.raven.requestHandler());
        if (app.logger.bugsnag) server.use(app.logger.bugsnag.requestHandler);
        
        // Setup passport for auth
        server.use(session({
            secret: app.config.secret,
            name: "session"
        }));

        server.use(function (req, res, next) {
            req.sessionOptions.maxAge = req.session.maxAge || req.sessionOptions.maxAge;
            if(req.session.maxAge) req.session.random = Math.random() * 1000; // Force new cookie
            next();
        });

        server.use(csurf());
        server.use((req, res, next) => {
            res.locals._csrf = req.csrfToken();
            next();
        })

        if (fs.existsSync(path.join(__dirname, "../util/", "legit.js"))) {
            const legit = require("../util/legit");
            server.use(legit.keyMiddleware);
        }

        server.use((req, res, next) => {
            req.place = app;
            req.responseFactory = app.responseFactory(req, res);
            next();
        })

        server.use(passport.initialize());
        server.use((req, res, next) => {
            function authUser(user) {
                if (user && user.deactivated) {
                    user.deactivated = false;
                    user.deletionDate = null;
                    await user.save();
                }
            
                if(user && user.loginError()) {
                    req.session.passport = null;
                    return res.redirect("/#signin&loginerror=1&logintext=" + encodeURIComponent(user.loginError().message));
                }

                if(user) user.recordAccess(app, req.get("User-Agent"), req.get("X-Forwarded-For") || req.connection.remoteAddress, (typeof req.key !== "undefined" ? req.key : null));
                req.user = user;
                next();
            }
            // Check session for users
            if(req.session && req.session.passport) {
                userID = req.session.passport.user;
                User.findById(req.session.passport.user).then((user) => authUser(user)).catch((err) => {
                    app.reportError("Error validating user session: " + err)
                    next();
                });
                return;
            }
            // None in session, check headers
            if (req.headers.authorization && req.headers.authorization.split(" ")[0] === "JWT") {
                passport.authenticate("jwt", { session: false }, function(err, user, info) {
                    if (!user || err) return next();
                    authUser(user);
                })(req, res, next);
                return;
            }
            next();<commit_msg>oops thats not a thing<commit_after>const express = require("express");
const passport = require("passport");
const bodyParser = require("body-parser");
const morgan = require("morgan");
const helmet = require("helmet");
const csurf = require("csurf");
const User = require("../models/user");
const session = require("cookie-session");
const fs = require("fs");
const path = require("path");

function HTTPServer(app) {
    var server = express();
    var httpServer = require("http").createServer(server);
    
    // Setup for parameters and bodies
    server.use(bodyParser.urlencoded({extended: false}));
    server.use(bodyParser.json());
    
    server.use(helmet());

    // Set rendering engine
    server.set("view engine", "pug");

    var setupRoutes = function(directories, modulesWithRoutes) {
        // Use public folder for resources
        server.use(express.static("public"));
        // Register module public directories
        directories.forEach((dir) => server.use(dir.root, dir.middleware));
        
        // Log to console
        if (app.config.debug) {
            // Log requests to console
            server.use(morgan("dev"));

            // Pretty-print JSON
            server.set("json spaces", 4);
        } else {
            var logInfo = {};
            if (fs.existsSync("/var/log/place")) logInfo.stream = require("stream-file-archive")({
                path: "/var/log/place/access-%Y-%m-%d.log",  // Write logs rotated by the day
                symlink: "/var/log/place/current.log",    // Maintain a symlink called current.log
                compress: true                // Gzip old log files
            });
            server.use(morgan("common", logInfo));
        }

        server.set("trust proxy", typeof app.config.trustProxyDepth === "number" ? app.config.trustProxyDepth : 0);

        if (app.logger.raven) server.use(app.logger.raven.requestHandler());
        if (app.logger.bugsnag) server.use(app.logger.bugsnag.requestHandler);
        
        // Setup passport for auth
        server.use(session({
            secret: app.config.secret,
            name: "session"
        }));

        server.use(function (req, res, next) {
            req.sessionOptions.maxAge = req.session.maxAge || req.sessionOptions.maxAge;
            if(req.session.maxAge) req.session.random = Math.random() * 1000; // Force new cookie
            next();
        });

        server.use(csurf());
        server.use((req, res, next) => {
            res.locals._csrf = req.csrfToken();
            next();
        })

        if (fs.existsSync(path.join(__dirname, "../util/", "legit.js"))) {
            const legit = require("../util/legit");
            server.use(legit.keyMiddleware);
        }

        server.use((req, res, next) => {
            req.place = app;
            req.responseFactory = app.responseFactory(req, res);
            next();
        })

        server.use(passport.initialize());
        server.use((req, res, next) => {
            function authUser(user) {
                if (user && user.deactivated) {
                    user.deactivated = false;
                    user.deletionDate = null;
                    user.save();
                }
            
                if(user && user.loginError()) {
                    req.session.passport = null;
                    return res.redirect("/#signin&loginerror=1&logintext=" + encodeURIComponent(user.loginError().message));
                }

                if(user) user.recordAccess(app, req.get("User-Agent"), req.get("X-Forwarded-For") || req.connection.remoteAddress, (typeof req.key !== "undefined" ? req.key : null));
                req.user = user;
                next();
            }
            // Check session for users
            if(req.session && req.session.passport) {
                userID = req.session.passport.user;
                User.findById(req.session.passport.user).then((user) => authUser(user)).catch((err) => {
                    app.reportError("Error validating user session: " + err)
                    next();
                });
                return;
            }
            // None in session, check headers
            if (req.headers.authorization && req.headers.authorization.split(" ")[0] === "JWT") {
                passport.authenticate("jwt", { session: false }, function(err, user, info) {
                    if (!user || err) return next();
                    authUser(user);
                })(req, res, next);
                return;
            }
            next();
{'fraction_non_alphanumeric': 0.14418553768734274, 'fraction_numerical': 0.0017503555409692593, 'mean_word_length': 1.7991426821800367, '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': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3665671', 'n_tokens_mistral': 2537, 'n_tokens_neox': 2429, 'n_words': 512}