<commit_before>package com.anchortab.snippet

import scala.xml.NodeSeq

import net.liftweb._
  import common._
  import http._
    import js._
      import JsCmds._
    import SHtml._
    import LiftRules._
  import util._
    import Helpers._
  import json._
    import JsonDSL._
  import mongodb.BsonDSL._

import com.mongodb.WriteConcern

import com.anchortab.model._

import me.frmr.wepay._
  import api.Preapproval

object userSession extends SessionVar[Box[UserSession]](Empty)
object statelessUser extends RequestVar[Box[User]](Empty)

object Authentication extends Loggable {
  implicit val authenticationToken : Option[WePayToken] = {
    for {
      anchortabUserId <- Props.getLong("wepay.anchorTabUserId")
      anchortabAccessToken <- Props.get("wepay.anchorTabAccessToken")
    } yield {
      WePayToken(anchortabUserId, anchortabAccessToken, "BEARER", None)
    }
  }

  /**
   * Handle authentication for stateless requests (the API).
  **/
  def earlyInStateless(req:Box[Req]) = {
    req match {
      case Full(req:Req) if req.header("Authorization").isDefined =>
        req.header("Authorization").foreach { authHeader =>
          val authParts = authHeader.split(" ")

          for {
            authType <- tryo(authParts(0)) if authType == "Bearer"
            authKey <- tryo(authParts(1))
            user <- User.find("authorizations.key" -> authKey)
          } {
            statelessUser(Full(user))
          }
        }

      case _ =>
        // Nada
    }
  }

  def dispatch : DispatchPF = {
    case Req("session" :: "logout" :: Nil, _, _) =>
      () => {
        userSession(Empty)
        Full(RedirectResponse("/"))
      }
  }

  def snippetHandlers : SnippetPF = {
    case "login-form" :: Nil => loginForm
    case "registration-form" :: Nil => registrationForm
    case "forgot-password-form" :: Nil => forgotPasswordForm
    case "redirect-to-dashboard-if-logged-in" :: Nil => redirectToDashboardIfLoggedIn
    case "pwn-if-not-logged-in" :: Nil => pwnIfNotLoggedIn
    case "show-if-logged-in" :: Nil => showIfLoggedIn
    case "pwn-if-not-admin" :: Nil => pwnIfNotAdmin
    case "show-if-admin" :: Nil => showIfAdmin
  }

  def redirectToDashboardIfLoggedIn(ns:NodeSeq) = {
    if (userSession.isDefined)
      S.redirectTo("/manager/dashboard")

    ns
  }

  def pwnIfNotLoggedIn(ns:NodeSeq) = {
    if (! userSession.isDefined)
      S.redirectTo("/manager")

    ns
  }

  def pwnIfNotAdmin(ns:NodeSeq) = {
    {
      for {
        session <- userSession
        user <- User.find(session.userId) if user.admin_?
      } yield {
        ns
      }
    } openOr {
      // Let's be clever here and trigger a 404 so that someone doing random
      // probes on our app will believe there simply is no /admin url.
      throw new ResponseShortcutException(NotFoundResponse())
    }
  }

  def showIfAdmin(ns:NodeSeq) = {
    {
      for {
        session <- userSession
        user <- User.find(session.userId) if user.admin_?
      } yield {
        ns
      }
    } openOr {
      NodeSeq.Empty
    }
  }

  def showIfLoggedIn(ns:NodeSeq) = {
    if (userSession.isDefined)
      ns
    else
      NodeSeq.Empty
  }

  def loginForm = {
    var submittedUsername = ""
    var submittedPassword = ""

    val bind =
      ".username" #> text(submittedUsername, submittedUsername = _) &
      ".password" #> password(submittedPassword, submittedPassword = _) &
      ".submit" #> ajaxSubmit("Log In", () => processLogin(submittedUsername, submittedPassword))

    "form" #> { ns:NodeSeq =>
      ajaxForm(bind(ns))
    }
  }

  private def processLogin(username:String, password:String) = {
    User.attemptLogin(username, password) match {
      case Full(user) =>
        val remoteIp = S.containerRequest.map(_.remoteAddress).openOr("localhost")
        val userAgent = S.containerRequest.flatMap(_.userAgent).openOr("unknown")

        val session = UserSession(user._id, remoteIp, userAgent)
        session.save
        userSession(Full(session))

        RedirectTo("/manager/dashboard")

      case _ =>
        Alert("That username or password appears to be invalid.")
    }
  }

  def registrationForm = {
    var emailAddress = ""
    var requestedPassword = ""
    var requestedPasswordConfirmation = ""
    var firstName = ""
    var lastName = ""
    var organization = ""
    var selectedPlan = ""

    val plans = Plan.findAll("visibleOnRegistration" -> true)
    val planSelections = plans.map { plan =>
      (plan._id.toString, plan.registrationTitle)<commit_msg>Set a session cookie on successful login.<commit_after>package com.anchortab.snippet

import scala.xml.NodeSeq

import net.liftweb._
  import common._
  import http._
    import provider._
    import js._
      import JsCmds._
    import SHtml._
    import LiftRules._
  import util._
    import Helpers._
  import json._
    import JsonDSL._
  import mongodb.BsonDSL._

import com.mongodb.WriteConcern

import com.anchortab.model._

import me.frmr.wepay._
  import api.Preapproval

object userSession extends SessionVar[Box[UserSession]](Empty)
object statelessUser extends RequestVar[Box[User]](Empty)

object Authentication extends Loggable {
  implicit val authenticationToken : Option[WePayToken] = {
    for {
      anchortabUserId <- Props.getLong("wepay.anchorTabUserId")
      anchortabAccessToken <- Props.get("wepay.anchorTabAccessToken")
    } yield {
      WePayToken(anchortabUserId, anchortabAccessToken, "BEARER", None)
    }
  }

  /**
   * Handle authentication for stateless requests (the API).
  **/
  def earlyInStateless(req:Box[Req]) = {
    req match {
      case Full(req:Req) if req.header("Authorization").isDefined =>
        req.header("Authorization").foreach { authHeader =>
          val authParts = authHeader.split(" ")

          for {
            authType <- tryo(authParts(0)) if authType == "Bearer"
            authKey <- tryo(authParts(1))
            user <- User.find("authorizations.key" -> authKey)
          } {
            statelessUser(Full(user))
          }
        }

      case _ =>
        // Nada
    }
  }

  def dispatch : DispatchPF = {
    case Req("session" :: "logout" :: Nil, _, _) =>
      () => {
        userSession(Empty)
        Full(RedirectResponse("/"))
      }

    case Req("session" :: "login" :: Nil, _, _) =>
      () => {
        for {
          session <- userSession.is
        } yield {
          RedirectResponse("/manager/dashboard", HTTPCookie("session", session._id.toString).setPath("/"))
        }
      }
  }

  def snippetHandlers : SnippetPF = {
    case "login-form" :: Nil => loginForm
    case "registration-form" :: Nil => registrationForm
    case "forgot-password-form" :: Nil => forgotPasswordForm
    case "redirect-to-dashboard-if-logged-in" :: Nil => redirectToDashboardIfLoggedIn
    case "pwn-if-not-logged-in" :: Nil => pwnIfNotLoggedIn
    case "show-if-logged-in" :: Nil => showIfLoggedIn
    case "pwn-if-not-admin" :: Nil => pwnIfNotAdmin
    case "show-if-admin" :: Nil => showIfAdmin
  }

  def redirectToDashboardIfLoggedIn(ns:NodeSeq) = {
    if (userSession.isDefined)
      S.redirectTo("/manager/dashboard")

    ns
  }

  def pwnIfNotLoggedIn(ns:NodeSeq) = {
    if (! userSession.isDefined)
      S.redirectTo("/manager")

    ns
  }

  def pwnIfNotAdmin(ns:NodeSeq) = {
    {
      for {
        session <- userSession
        user <- User.find(session.userId) if user.admin_?
      } yield {
        ns
      }
    } openOr {
      // Let's be clever here and trigger a 404 so that someone doing random
      // probes on our app will believe there simply is no /admin url.
      throw new ResponseShortcutException(NotFoundResponse())
    }
  }

  def showIfAdmin(ns:NodeSeq) = {
    {
      for {
        session <- userSession
        user <- User.find(session.userId) if user.admin_?
      } yield {
        ns
      }
    } openOr {
      NodeSeq.Empty
    }
  }

  def showIfLoggedIn(ns:NodeSeq) = {
    if (userSession.isDefined)
      ns
    else
      NodeSeq.Empty
  }

  def loginForm = {
    var submittedUsername = ""
    var submittedPassword = ""

    val bind =
      ".username" #> text(submittedUsername, submittedUsername = _) &
      ".password" #> password(submittedPassword, submittedPassword = _) &
      ".submit" #> ajaxSubmit("Log In", () => processLogin(submittedUsername, submittedPassword))

    "form" #> { ns:NodeSeq =>
      ajaxForm(bind(ns))
    }
  }

  private def processLogin(username:String, password:String) = {
    User.attemptLogin(username, password) match {
      case Full(user) =>
        val remoteIp = S.containerRequest.map(_.remoteAddress).openOr("localhost")
        val userAgent = S.containerRequest.flatMap(_.userAgent).openOr("unknown")

        val session = UserSession(user._id, remoteIp, userAgent)
        session.save
        userSession(Full(session))

        RedirectTo("/session/login")

      case _ =>
        Alert("That username or password appears to be invalid.")
    }
  }

  def registrationForm = {
    var emailAddress = ""
    var requestedPassword = ""
    var requestedPasswordConfirmation = ""
    var firstName = ""
    var lastName = ""
    var organization = ""
    var selectedPlan = ""

    val plans = Plan.findAll("visibleOnRegistration" -> true)
    val planSelections = plans.map { plan =>
      (plan._id.toString, plan.registrationTitle)
{'fraction_non_alphanumeric': 0.11933454196438094, 'fraction_numerical': 0.0010664391596459423, 'mean_word_length': 2.56442417331813, 'pattern_counts': {'":': 0, '<': 22, '<?xml version=': 0, '>': 53, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, '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': '3105921', 'n_tokens_mistral': 2963, 'n_tokens_neox': 2869, 'n_words': 602}