<commit_before>import * as http from "http";
import {resolve} from "path";

import * as bodyParser from "body-parser";
import * as express from "express";
import * as passport from "passport";
import {Strategy as FbStrategy} from "passport-facebook";
import { Strategy as LocalStrategy } from "passport-local";
import * as sio from "socket.io";
import {MongooseClient} from "./data/MongooseClient";
import {User, IUserDocument, IUser} from "./data/User";

import {GameRoomsRepository} from "./logic/GameRoomsRepository";
import {enableSessions, getSession} from "./session";
import {copy} from "../common/util";
import * as Majavashakki from "../common/GamePieces"

const siteName = process.env.WEBSITE_SITE_NAME; // Azure default
const appRootUrl = siteName ? `https://${siteName}.azurewebsites.net` : "http://localhost:3000";
const app = express();

// Get facebook authentication values from environment variables
const facebookClientId = process.env.MajavashakkiFbClientId
const facebookSecret = process.env.MajavashakkiFbSecret
const isFacebookAuthEnabled = facebookClientId && facebookSecret

MongooseClient.InitMongoConnection();
initPassport(appRootUrl);

const io: SocketIO.Server = sio({transports: ["websocket"]});
enableSessions(app, io);
initSockets();

const logSession = (path, session) => {
  const withoutCookie = copy(session);
  delete withoutCookie.cookie;
  console.log(`[${session.id}] ${path} ${JSON.stringify(withoutCookie)}`);
};

app.use((req, res, next) => {
  logSession(req.path, getSession(req));
  next();
});

app.use(passport.initialize());
app.use(passport.session());

const uiAuth = requireAuth((req, res, next) =>
  res.redirect("/login"))

const apiAuth = requireAuth((req, res, next) =>
  res.status(401).send({error: "Login required"}))

app.get("/", uiAuth, (req, res, next) => {
  const session = getSession(req)
  return User.validProfile(session.passport.user) ? next() : res.redirect("/profile");
});

app.get("/authFacebook",
  passport.authenticate("facebook", {
    successRedirect: "/",
    failureRedirect: "/login",
  })
)

const server = http.createServer(app);
io.attach(server);

app.use(express.static(resolve(__dirname, "../../dist")));
app.use(bodyParser.json())

const roomRepo = GameRoomsRepository.getInstance();

app.get("/api/user", (req, res) => {
  const user = req.user;
  const result = {
    loggedIn: !!user,
    name: user.name
  };
  res.set("Cache-Control", "no-cache");
  res.send(result);
});

app.post("/api/user", apiAuth, (req, res) => {
  const {session, body: {name}} = req
  if (!session) throw new Error("No session found, things are broken")

  const currentUser: IUserDocument = session.passport.user;
  console.log("New user received :" + currentUser.facebookId);
  User.updateName(currentUser._id, name);
  currentUser.name = name;
  res.send("OK")
})

app.post("/api/user/register", async (req, res) => {
  const { body: { username, password, email } } = req<commit_msg>Fixed get(/api/user) throwing error when not logged in<commit_after>import * as http from "http";
import {resolve} from "path";

import * as bodyParser from "body-parser";
import * as express from "express";
import * as passport from "passport";
import {Strategy as FbStrategy} from "passport-facebook";
import { Strategy as LocalStrategy } from "passport-local";
import * as sio from "socket.io";
import {MongooseClient} from "./data/MongooseClient";
import {User, IUserDocument, IUser} from "./data/User";

import {GameRoomsRepository} from "./logic/GameRoomsRepository";
import {enableSessions, getSession} from "./session";
import {copy} from "../common/util";
import * as Majavashakki from "../common/GamePieces"

const siteName = process.env.WEBSITE_SITE_NAME; // Azure default
const appRootUrl = siteName ? `https://${siteName}.azurewebsites.net` : "http://localhost:3000";
const app = express();

// Get facebook authentication values from environment variables
const facebookClientId = process.env.MajavashakkiFbClientId
const facebookSecret = process.env.MajavashakkiFbSecret
const isFacebookAuthEnabled = facebookClientId && facebookSecret

MongooseClient.InitMongoConnection();
initPassport(appRootUrl);

const io: SocketIO.Server = sio({transports: ["websocket"]});
enableSessions(app, io);
initSockets();

const logSession = (path, session) => {
  const withoutCookie = copy(session);
  delete withoutCookie.cookie;
  console.log(`[${session.id}] ${path} ${JSON.stringify(withoutCookie)}`);
};

app.use((req, res, next) => {
  logSession(req.path, getSession(req));
  next();
});

app.use(passport.initialize());
app.use(passport.session());

const uiAuth = requireAuth((req, res, next) =>
  res.redirect("/login"))

const apiAuth = requireAuth((req, res, next) =>
  res.status(401).send({error: "Login required"}))

app.get("/", uiAuth, (req, res, next) => {
  const session = getSession(req)
  return User.validProfile(session.passport.user) ? next() : res.redirect("/profile");
});

app.get("/authFacebook",
  passport.authenticate("facebook", {
    successRedirect: "/",
    failureRedirect: "/login",
  })
)

const server = http.createServer(app);
io.attach(server);

app.use(express.static(resolve(__dirname, "../../dist")));
app.use(bodyParser.json())

const roomRepo = GameRoomsRepository.getInstance();

app.get("/api/user", (req, res) => {
  const user = req.user;
  const result = {
    loggedIn: Boolean(user),
    name: user ? user.name : "Anonymous",
  };
  res.set("Cache-Control", "no-cache");
  res.send(result);
});

app.post("/api/user", apiAuth, (req, res) => {
  const {session, body: {name}} = req
  if (!session) throw new Error("No session found, things are broken")

  const currentUser: IUserDocument = session.passport.user;
  console.log("New user received :" + currentUser.facebookId);
  User.updateName(currentUser._id, name);
  currentUser.name = name;
  res.send("OK")
})

app.post("/api/user/register", async (req, res) => {
  const { body: { username, password, email } } = req
{'fraction_non_alphanumeric': 0.1657190635451505, 'fraction_numerical': 0.0023411371237458192, 'mean_word_length': 5.140657084188912, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 19, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '64914', 'n_tokens_mistral': 1911, 'n_tokens_neox': 1881, 'n_words': 462}