play.api.http.HttpFilters Scala Examples

The following examples show how to use play.api.http.HttpFilters. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: Filters.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.contacts.filters

import javax.inject._

import play.api._
import play.api.http.HttpFilters


@Singleton
class Filters @Inject() (
  env: Environment,
  exampleFilter: ExampleFilter) extends HttpFilters {

  override val filters = {
    // Use the example filter if we're running development mode. If
    // we're running in production or test mode then don't use any
    // filters at all.
    if (env.mode == Mode.Dev) Seq(exampleFilter) else Seq.empty
  }

} 
Example 2
Source File: VersionRoutingRequestHandler.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package routing

import config.{AppConfig, FeatureSwitch}
import definition.Versions
import javax.inject.{Inject, Singleton}
import play.api.http.{DefaultHttpRequestHandler, HttpConfiguration, HttpErrorHandler, HttpFilters}
import play.api.libs.json.Json
import play.api.mvc.{DefaultActionBuilder, Handler, RequestHeader, Results}
import play.api.routing.Router
import v1.controllers.requestParsers.validators.validations.VrnValidation
import v1.models.errors.{InvalidAcceptHeaderError, UnsupportedVersionError, VrnFormatError}

@Singleton
class VersionRoutingRequestHandler @Inject()(versionRoutingMap: VersionRoutingMap,
                                             errorHandler: HttpErrorHandler,
                                             httpConfiguration: HttpConfiguration,
                                             config: AppConfig,
                                             filters: HttpFilters,
                                             action: DefaultActionBuilder)
  extends DefaultHttpRequestHandler(versionRoutingMap.defaultRouter, errorHandler, httpConfiguration, filters) {

  private val featureSwitch = FeatureSwitch(config.featureSwitch)

  private val unsupportedVersionAction = action(Results.NotFound(Json.toJson(UnsupportedVersionError)))

  private val invalidAcceptHeaderError = action(Results.NotAcceptable(Json.toJson(InvalidAcceptHeaderError)))

  override def routeRequest(request: RequestHeader): Option[Handler] = {

    def documentHandler = routeWith(versionRoutingMap.defaultRouter)(request)

    def apiHandler = Versions.getFromRequest(request) match {
      case Some(version) =>
        versionRoutingMap.versionRouter(version) match {
          case Some(versionRouter) if featureSwitch.isVersionEnabled(version) =>
            routeWith(versionRouter)(request)
          case Some(_) => Some(unsupportedVersionAction)
          case None => Some(unsupportedVersionAction)
        }
      case None => Some(invalidAcceptHeaderError)
    }

    documentHandler orElse apiHandler
  }

  private def routeWith(router: Router)(request: RequestHeader) =
    router
      .handlerFor(request)
      .orElse {
        if (validatePath(request.path)) {
          if (request.path.endsWith("/")) {
            val pathWithoutSlash = request.path.dropRight(1)
            val requestWithModifiedPath = request.withTarget(request.target.withPath(pathWithoutSlash))
            router.handlerFor(requestWithModifiedPath)
          }
          else None
        }
        else {
          Some(action(Results.BadRequest(Json.toJson(VrnFormatError))))
        }
      }

  private def validatePath(path: String) = {
    val vrn = path.split("/")(1)
    if(VrnValidation.validate(vrn) == Nil)
      true
    else false
  }
} 
Example 3
Source File: Filters.scala    From dr-cla   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package utils

import akka.stream.Materializer
import javax.inject.Inject
import play.api.http.{HeaderNames, HttpFilters}
import play.api.mvc._
import play.filters.gzip.GzipFilter

import scala.concurrent.{ExecutionContext, Future}

class OnlyHttpsFilter @Inject() (implicit val mat: Materializer, ec: ExecutionContext) extends Filter {
  def apply(nextFilter: (RequestHeader) => Future[Result])(requestHeader: RequestHeader): Future[Result] = {
    nextFilter(requestHeader).map { result =>
      val isWellKnown = requestHeader.path.startsWith(controllers.routes.Application.wellKnown("").url)
      val isForwardedAndInsecure = requestHeader.headers.get(HeaderNames.X_FORWARDED_PROTO).exists(_ != "https")

      if (isWellKnown || !isForwardedAndInsecure) {
        result
      }
      else {
        Results.MovedPermanently("https://" + requestHeader.host + requestHeader.uri)
      }
    }
  }
}

class Filters @Inject() (gzip: GzipFilter, onlyHttpsFilter: OnlyHttpsFilter) extends HttpFilters {
  val filters = Seq(gzip, onlyHttpsFilter)
} 
Example 4
Source File: Filters.scala    From akka-http-test   with Apache License 2.0 5 votes vote down vote up
import javax.inject._

import akka.stream.Materializer
import play.api._
import play.api.http.HttpFilters
import play.api.mvc._

import scala.concurrent.{ ExecutionContext, Future }


@Singleton
class ExampleFilter @Inject() (implicit override val mat: Materializer, exec: ExecutionContext) extends Filter {
  override def apply(nextFilter: RequestHeader => Future[Result])(requestHeader: RequestHeader): Future[Result] = {
    // Run the next filter in the chain. This will call other filters
    // and eventually call the action. Take the result and modify it
    // by adding a new header.
    nextFilter(requestHeader).map { result =>
      result.withHeaders("X-ExampleFilter" -> "foo")
    }
  }
} 
Example 5
Source File: Filters.scala    From sbt-header   with Apache License 2.0 5 votes vote down vote up
import javax.inject._
import play.api._
import play.api.http.HttpFilters
import play.api.mvc._

import filters.ExampleFilter


@Singleton
class Filters @Inject() (
  env: Environment,
  exampleFilter: ExampleFilter) extends HttpFilters {

  override val filters = {
    // Use the example filter if we're running development mode. If
    // we're running in production or test mode then don't use any
    // filters at all.
    if (env.mode == Mode.Dev) Seq(exampleFilter) else Seq.empty
  }

} 
Example 6
Source File: Filters.scala    From play-swagger   with Apache License 2.0 5 votes vote down vote up
import javax.inject._
import play.api._
import play.api.http.HttpFilters
import play.api.mvc._

import filters.ExampleFilter


@Singleton
class Filters @Inject() (
  env:           Environment,
  exampleFilter: ExampleFilter) extends HttpFilters {

  override val filters = {
    // Use the example filter if we're running development mode. If
    // we're running in production or test mode then don't use any
    // filters at all.
    if (env.mode == Mode.Dev) Seq(exampleFilter) else Seq.empty
  }

} 
Example 7
Source File: Filters.scala    From theGardener   with Apache License 2.0 5 votes vote down vote up
package filters

import akka.stream.Materializer
import javax.inject.Inject
import play.api.http.HttpFilters
import play.api.mvc.{EssentialFilter, RequestHeader, Result}
import play.api.{Environment, Mode}
import play.filters.cors.CORSFilter
import play.filters.gzip.GzipFilter

class Filters @Inject()(environment: Environment, corsFilter: CORSFilter)(implicit mat: Materializer) extends HttpFilters {

  
  private def shouldGzip = (requestHeader: RequestHeader, response: Result) => {
    val responseIsJavascript = response.body.contentType.exists(_.startsWith("application/javascript"))
    val requestPathShouldBeGzipped = requestHeader.path.contains("/api/")
    responseIsJavascript || requestPathShouldBeGzipped
  }

  private val gzipFilter = new GzipFilter(shouldGzip = shouldGzip)

  override val filters: Seq[EssentialFilter] = environment.mode match {
    case Mode.Dev =>
      // CORSFilter only for DEV mode: allow Angular app to call API on different port
      Seq(gzipFilter, corsFilter)
    case _ =>
      Seq(gzipFilter)
  }

}