<commit_before># I'm using coffeescript here so I can write ES queries in YAML-like syntax
esclient = require('./esclient')
config = require('./config')
fs = require('fs')
express = require("express")
bodyParser = require("body-parser")
passport = require("passport")
PersonaStrategy = require("passport-persona").Strategy
methodOverride = require("method-override")
session = require("express-session")
partials = require("express-partials")
uuid = require("node-uuid")
Promise = require('promise')
validate = require('jsonschema').validate
 
# Passport session setup.
#   To support persistent login sessions, Passport needs to be able to
#   serialize users into and deserialize users out of the session.  Typically,
#   this will be as simple as storing the user ID when serializing, and finding
#   the user by ID when deserializing.
passport.serializeUser (user, done) ->
  done null, user.email

passport.deserializeUser (email, done) ->
  esclient.search(
    index: "users"
    body:
      query:
        term:
          email: email
  ).then((result) ->
    return done("No user found")  if result.hits.total is 0
    userInfo = result.hits.hits[0]._source
    userInfo.id = result.hits.hits[0]._id
    done null, userInfo
  )["catch"] done

passport.use new PersonaStrategy(
  audience: config.serverHttpsUrl
, (email, done) ->
  #TODO: TOS
  esclient.search(
    index: "users"
    body:
      query:
        term:
          email: email
  ).then((result) ->
    userInfo = undefined
    userInfo = email: email
    if result.hits.hits.length is 0
      userInfo.key = <KEY>
      esclient.index(
        index: "users"
        type: "user"
        refresh: true
        body: userInfo
      ).then (createUserResult) ->
        userInfo.id = createUserResult._id
        done null, userInfo
    else if result.hits.hits.length is 1
      userInfo = result.hits.hits[0]._source
      userInfo.id = result.hits.hits[0]._id
      done null, userInfo
    else
      done "error"
  ).catch done
)

app = express()
module.exports = app
app.set "views", __dirname + "/views"
app.set "view engine", "ejs"
#logging
app.use require("morgan")("combined")
app.use bodyParser.json()
app.use bodyParser.urlencoded(extended: true)
app.use methodOverride()
app.use session(secret: config.sessionSecret)
app.use passport.initialize()
app.use passport.session()
app.use express.static(__dirname + "/static")
app.use partials()

#### Middleware helpers ####
#TODO Index on users
requireUserKey = (req, res, next) ->
  if not req.body.user?.id
    return res.status(401).send({ error: 'User id and key is required' })
  esclient.get
    index: "users"
    type: "user"
    id: req.body.user.id
  .then (user)->
    if user._source.key == req.body.user.key
      req.user = user
      next()
    else
      res.status(401).send({ error: 'Invalid key' })
  .catch (e)->
    res.status(401).send({ error: 'Invalid user' })  


ensureAuthenticated = (req, res, next) ->
  if req.isAuthenticated()
    next()
  else
    res.redirect('/login?redirect=' + req.originalUrl)

allowXorigin = (req, res, next) ->
  res.header "Access-Control-Allow-Origin", "*"
  res.header "Access-Control-Allow-Headers", "X-Requested-With"
  next()

app.get "/", (req, res) ->
  res.render "index",
    user: req.user
    config:
      url: config.serverUrl
      user: req.user

app.get '/pages/:page', (req, res, next) ->
  res.render 'pages/' + req.params.page,
    user: req.user
    config:
      url: config.serverUrl
      user: req.user

app.get '/contextscripts/:id', (req, res, next) ->
  res.render 'contextscripts',
    id: req.params.id
    user: req.user
    config:
      url: config.serverUrl
      user: req.user

app.get '/myscripts', ensureAuthenticated, (req, res, next) ->
  Promise.all [
    esclient.search
      index: "contextscripts"
      body:
        query:
          term:
            "savedBy": req.user.id
        _source:
          exclude: ["script"]
    esclient.search
      index: "contextscripts"
      body:
        query:
          term:
            "changes.author": req.user.id
        _source:
          exclude: ["script"]
  ]
  .then (result) ->
    res.render 'myscripts',
      user: req.user
      createdScripts: result[0]
      editedScripts: result[1]
      config:
        url: config.serverUrl
        user: req.user
  .catch next

app.get "/login", (req, res) -><commit_msg>increasing myscripts limit<commit_after># I'm using coffeescript here so I can write ES queries in YAML-like syntax
esclient = require('./esclient')
config = require('./config')
fs = require('fs')
express = require("express")
bodyParser = require("body-parser")
passport = require("passport")
PersonaStrategy = require("passport-persona").Strategy
methodOverride = require("method-override")
session = require("express-session")
partials = require("express-partials")
uuid = require("node-uuid")
Promise = require('promise')
validate = require('jsonschema').validate
 
# Passport session setup.
#   To support persistent login sessions, Passport needs to be able to
#   serialize users into and deserialize users out of the session.  Typically,
#   this will be as simple as storing the user ID when serializing, and finding
#   the user by ID when deserializing.
passport.serializeUser (user, done) ->
  done null, user.email

passport.deserializeUser (email, done) ->
  esclient.search(
    index: "users"
    body:
      query:
        term:
          email: email
  ).then((result) ->
    return done("No user found")  if result.hits.total is 0
    userInfo = result.hits.hits[0]._source
    userInfo.id = result.hits.hits[0]._id
    done null, userInfo
  )["catch"] done

passport.use new PersonaStrategy(
  audience: config.serverHttpsUrl
, (email, done) ->
  #TODO: TOS
  esclient.search(
    index: "users"
    body:
      query:
        term:
          email: email
  ).then((result) ->
    userInfo = undefined
    userInfo = email: email
    if result.hits.hits.length is 0
      userInfo.key = <KEY>
      esclient.index(
        index: "users"
        type: "user"
        refresh: true
        body: userInfo
      ).then (createUserResult) ->
        userInfo.id = createUserResult._id
        done null, userInfo
    else if result.hits.hits.length is 1
      userInfo = result.hits.hits[0]._source
      userInfo.id = result.hits.hits[0]._id
      done null, userInfo
    else
      done "error"
  ).catch done
)

app = express()
module.exports = app
app.set "views", __dirname + "/views"
app.set "view engine", "ejs"
#logging
app.use require("morgan")("combined")
app.use bodyParser.json()
app.use bodyParser.urlencoded(extended: true)
app.use methodOverride()
app.use session(secret: config.sessionSecret)
app.use passport.initialize()
app.use passport.session()
app.use express.static(__dirname + "/static")
app.use partials()

#### Middleware helpers ####
#TODO Index on users
requireUserKey = (req, res, next) ->
  if not req.body.user?.id
    return res.status(401).send({ error: 'User id and key is required' })
  esclient.get
    index: "users"
    type: "user"
    id: req.body.user.id
  .then (user)->
    if user._source.key == req.body.user.key
      req.user = user
      next()
    else
      res.status(401).send({ error: 'Invalid key' })
  .catch (e)->
    res.status(401).send({ error: 'Invalid user' })  


ensureAuthenticated = (req, res, next) ->
  if req.isAuthenticated()
    next()
  else
    res.redirect('/login?redirect=' + req.originalUrl)

allowXorigin = (req, res, next) ->
  res.header "Access-Control-Allow-Origin", "*"
  res.header "Access-Control-Allow-Headers", "X-Requested-With"
  next()

app.get "/", (req, res) ->
  res.render "index",
    user: req.user
    config:
      url: config.serverUrl
      user: req.user

app.get '/pages/:page', (req, res, next) ->
  res.render 'pages/' + req.params.page,
    user: req.user
    config:
      url: config.serverUrl
      user: req.user

app.get '/contextscripts/:id', (req, res, next) ->
  res.render 'contextscripts',
    id: req.params.id
    user: req.user
    config:
      url: config.serverUrl
      user: req.user

app.get '/myscripts', ensureAuthenticated, (req, res, next) ->
  Promise.all [
    esclient.search
      index: "contextscripts"
      body:
        # TODO: Pagination
        # It would be better use data end-points that are loaded on the page
        # over AJAX.
        size: 200
        query:
          term:
            "savedBy": req.user.id
        _source:
          exclude: ["script"]
    esclient.search
      index: "contextscripts"
      body:
        size: 200
        query:
          term:
            "changes.author": req.user.id
        _source:
          exclude: ["script"]
  ]
  .then (result) ->
    res.render 'myscripts',
      user: req.user
      createdScripts: result[0]
      editedScripts: result[1]
      config:
        url: config.serverUrl
        user: req.user
  .catch next

app.get "/login", (req, res) ->
{'fraction_non_alphanumeric': 0.13297634984381973, 'fraction_numerical': 0.004685408299866131, 'mean_word_length': 2.74321503131524, 'pattern_counts': {'":': 4, '<': 5, '<?xml version=': 0, '>': 39, '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': '3125969', 'n_tokens_mistral': 2894, 'n_tokens_neox': 2865, 'n_words': 777}