<commit_before>package brainflight.security

import models.User
import play.api.mvc._
import play.api.mvc.BodyParsers
import play.api.mvc.Results._
import play.api.mvc.Request
import play.api.Play
import play.api.mvc.WebSocket
import play.api.mvc.WebSocket._
import play.api.Play.current
import play.api.libs.iteratee.Input
import controllers.routes
import play.api.libs.iteratee.Done
import models.{ Role, Permission }
import play.api.libs.iteratee.Enumerator
import play.api.libs.iteratee.Iteratee
import play.api.libs.iteratee.Concurrent

case class AuthenticatedRequest[A](
  val user: User, request: Request[A]
) extends WrappedRequest(request)

object Secured {
  /**
   * Key used to store authentication information in the client cookie
   */
  val SessionInformationKey = "userId"
    
  /**
   * Creates a map which can be added to a cookie to set a session
   */
  def createSession( user: User ): Tuple2[String, String] =
    ( SessionInformationKey -> user.id )
}

/**
 * Provide security features
 */
trait Secured {
  /**
   * Defines the access role which is used if no role is passed to an
   * authenticated action
   */
  def DefaultAccessRole: Option[Role] = None

  /**
   * Defines the default permission used for authenticated actions if not
   * specified otherwise
   */
  def DefaultAccessPermission: Option[Permission] = None
    
  /**
   * Tries to extract the user from a request
   */
  def maybeUser( implicit request: RequestHeader ): Option[models.User] = {
    for {
      userId <- userId( request )
      user <- User.findOneById( userId )
    } yield user
  }
  /**
   * Retrieve the connected users email address.
   */
  private def userId( request: RequestHeader ) = {
    request.session.get( Secured.SessionInformationKey ) match {
      case Some( id ) =>
        Some( id )
      /*case _ if Play.configuration.getBoolean( "application.enableAutoLogin" ).get =>
        // development setting: if the above key is set, one gets logged in 
        // automatically
        Some( User.default.id )  */
      case _ =>
        None
    }
  }

  /**
   * Awesome construct to create an authenticated action. It uses the helper
   * function defined below this one to ensure that a user is logged in. If
   * a user fails this check he is redirected to the result of 'onUnauthorized'
   *
   * Example usage:
   *   def initialize = Authenticated( role=Admin ) { user =>
   *     implicit request =>
   *       Ok("User is logged in!")
   *   }
   *
   */

  def Authenticated[A](
    parser: BodyParser[A],
    role: Option[Role] = DefaultAccessRole,
    permission: Option[Permission] = DefaultAccessPermission )(f: AuthenticatedRequest[A] => Result) = {
      Action(parser) { request =>
        maybeUser(request).map { user =>
           if ( hasAccess( user, role, permission ) ) 
             f(AuthenticatedRequest(user, request))
           else
             Forbidden
        }.getOrElse( onUnauthorized(request) )      
    }
  }

  def Authenticated(f: AuthenticatedRequest[AnyContent] => Result): Action[AnyContent]  = {
    Authenticated(BodyParsers.parse.anyContent)(f)
  }

  def AuthenticatedWebSocket[A](
    role: Option[Role] = DefaultAccessRole,
    permission: Option[Permission] = DefaultAccessPermission )( f: => User => RequestHeader => ( Iteratee[A, _], Enumerator[A] ) )( implicit formatter: FrameFormatter[A] ) =
    WebSocket.using[A] { request =>
      ( for {
        user <- maybeUser( request )
        if ( hasAccess( user, role, permission ) )
      } yield {
        f( user )( request )
      } ).getOrElse {
        val iteratee = Done[A, Unit]( (), Input.EOF )
        // Send an error and close the socket
        val (enumerator, channel) = Concurrent.broadcast[A]
        channel.eofAndEnd

        ( iteratee, enumerator )
      }
    }

  def hasAccess( user: User, role: Option[Role], permission: Option[Permission] ) =
    ( role.isEmpty || user.hasRole( role.get ) ) &&
      ( permission.isEmpty || user.hasPermission( permission.get ) )
  /**
   * Redirect to login if the user in not authorized.
   */
  private def onUnauthorized( request: RequestHeader ) =
    Results.Redirect( routes.Application.login )

  // --

  /**
   * Action for authenticated users.
   */
  def IsAuthenticated( f: => String => Request[AnyContent] => Result ) =
    Security.Authenticated( userId, onUnauthorized ) {
      user =>
        Action( request => f( user )( request ) )
    }

}
<commit_msg>added autologin back<commit_after>package brainflight.security

import models.User
import play.api.mvc._
import play.api.mvc.BodyParsers
import play.api.mvc.Results._
import play.api.mvc.Request
import play.api.Play
import play.api.mvc.WebSocket
import play.api.mvc.WebSocket._
import play.api.Play.current
import play.api.libs.iteratee.Input
import controllers.routes
import play.api.libs.iteratee.Done
import models.{ Role, Permission }
import play.api.libs.iteratee.Enumerator
import play.api.libs.iteratee.Iteratee
import play.api.libs.iteratee.Concurrent

case class AuthenticatedRequest[A](
  val user: User, request: Request[A]
) extends WrappedRequest(request)

object Secured {
  /**
   * Key used to store authentication information in the client cookie
   */
  val SessionInformationKey = "userId"
    
  /**
   * Creates a map which can be added to a cookie to set a session
   */
  def createSession( user: User ): Tuple2[String, String] =
    ( SessionInformationKey -> user.id )
}

/**
 * Provide security features
 */
trait Secured {
  /**
   * Defines the access role which is used if no role is passed to an
   * authenticated action
   */
  def DefaultAccessRole: Option[Role] = None

  /**
   * Defines the default permission used for authenticated actions if not
   * specified otherwise
   */
  def DefaultAccessPermission: Option[Permission] = None
    
  /**
   * Tries to extract the user from a request
   */
  def maybeUser( implicit request: RequestHeader ): Option[models.User] = {
    for {
      userId <- userId( request )
      user <- User.findOneById( userId )
    } yield user
  }
  /**
   * Retrieve the connected users email address.
   */
  private def userId( request: RequestHeader ) = {
    request.session.get( Secured.SessionInformationKey ) match {
      case Some( id ) =>
        Some( id )
      case _ if Play.configuration.getBoolean( "application.enableAutoLogin" ).get =>
        // development setting: if the above key is set, one gets logged in 
        // automatically
        Some( User.default.id )  
      case _ =>
        None
    }
  }

  /**
   * Awesome construct to create an authenticated action. It uses the helper
   * function defined below this one to ensure that a user is logged in. If
   * a user fails this check he is redirected to the result of 'onUnauthorized'
   *
   * Example usage:
   *   def initialize = Authenticated( role=Admin ) { user =>
   *     implicit request =>
   *       Ok("User is logged in!")
   *   }
   *
   */

  def Authenticated[A](
    parser: BodyParser[A],
    role: Option[Role] = DefaultAccessRole,
    permission: Option[Permission] = DefaultAccessPermission )(f: AuthenticatedRequest[A] => Result) = {
      Action(parser) { request =>
        maybeUser(request).map { user =>
           if ( hasAccess( user, role, permission ) ) 
             f(AuthenticatedRequest(user, request))
           else
             Forbidden
        }.getOrElse( onUnauthorized(request) )      
    }
  }

  def Authenticated(f: AuthenticatedRequest[AnyContent] => Result): Action[AnyContent]  = {
    Authenticated(BodyParsers.parse.anyContent)(f)
  }

  def AuthenticatedWebSocket[A](
    role: Option[Role] = DefaultAccessRole,
    permission: Option[Permission] = DefaultAccessPermission )( f: => User => RequestHeader => ( Iteratee[A, _], Enumerator[A] ) )( implicit formatter: FrameFormatter[A] ) =
    WebSocket.using[A] { request =>
      ( for {
        user <- maybeUser( request )
        if ( hasAccess( user, role, permission ) )
      } yield {
        f( user )( request )
      } ).getOrElse {
        val iteratee = Done[A, Unit]( (), Input.EOF )
        // Send an error and close the socket
        val (enumerator, channel) = Concurrent.broadcast[A]
        channel.eofAndEnd

        ( iteratee, enumerator )
      }
    }

  def hasAccess( user: User, role: Option[Role], permission: Option[Permission] ) =
    ( role.isEmpty || user.hasRole( role.get ) ) &&
      ( permission.isEmpty || user.hasPermission( permission.get ) )
  /**
   * Redirect to login if the user in not authorized.
   */
  private def onUnauthorized( request: RequestHeader ) =
    Results.Redirect( routes.Application.login )

  // --

  /**
   * Action for authenticated users.
   */
  def IsAuthenticated( f: => String => Request[AnyContent] => Result ) =
    Security.Authenticated( userId, onUnauthorized ) {
      user =>
        Action( request => f( user )( request ) )
    }

}

{'fraction_non_alphanumeric': 0.10935927541093593, 'fraction_numerical': 0.00022363860002236387, 'mean_word_length': 2.794654221467968, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 41, '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': '2962536', 'n_tokens_mistral': 2667, 'n_tokens_neox': 2610, 'n_words': 748}