play.api.mvc.Results Scala Examples

The following examples show how to use play.api.mvc.Results. 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: StatusAndRouteCounterFilterSpec.scala    From play-prometheus-filters   with MIT License 5 votes vote down vote up
package com.github.stijndehaes.playprometheusfilters.filters

import com.github.stijndehaes.playprometheusfilters.metrics.DefaultPlayUnmatchedDefaults
import com.github.stijndehaes.playprometheusfilters.mocks.MockController
import io.prometheus.client.CollectorRegistry
import org.mockito.ArgumentMatchers.any
import org.mockito.Mockito.verify
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{MustMatchers, WordSpec}
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.Configuration
import play.api.libs.typedmap.TypedMap
import play.api.mvc.Results
import play.api.routing.{HandlerDef, Router}
import play.api.test.Helpers.stubControllerComponents
import play.api.test.{DefaultAwaitTimeout, FakeRequest, FutureAwaits}

import scala.concurrent.ExecutionContext.Implicits.global

class StatusAndRouteCounterFilterSpec extends WordSpec with MustMatchers with MockitoSugar with Results with DefaultAwaitTimeout with FutureAwaits with GuiceOneAppPerSuite  {

  private implicit val mat = app.materializer
  private val configuration = mock[Configuration]

  "Filter constructor" should {
    "Add a histogram to the prometheus registry" in {
      val collectorRegistry = mock[CollectorRegistry]
      new StatusAndRouteLatencyFilter(collectorRegistry, configuration)
      verify(collectorRegistry).register(any())
    }
  }

  "Apply method" should {
    "Measure the count" in {
      val filter = new StatusAndRouteCounterFilter(mock[CollectorRegistry], configuration)
      val rh = FakeRequest().withAttrs( TypedMap(
        Router.Attrs.HandlerDef -> HandlerDef(null, null, "testController", "test", null, "GET", "/path", null ,null)
      ))
      val action = new MockController(stubControllerComponents()).ok

      await(filter(action)(rh).run())

      val metrics = filter.metrics(0).metric.collect()
      metrics must have size 1
      val samples = metrics.get(0).samples
      //this is the count sample
      val countSample = samples.get(0)
      countSample.value mustBe 1.0
      countSample.labelValues must have size 5
      countSample.labelValues.get(0) mustBe "test"
      countSample.labelValues.get(1) mustBe "200"
      countSample.labelValues.get(2) mustBe "testController"
      countSample.labelValues.get(3) mustBe "/path"
      countSample.labelValues.get(4) mustBe "GET"
    }

    "Measure the count for an unmatched route" in {
      val filter = new StatusAndRouteCounterFilter(mock[CollectorRegistry], configuration)
      val rh = FakeRequest()
      val action = new MockController(stubControllerComponents()).error

      await(filter(action)(rh).run())

      val metrics = filter.metrics(0).metric.collect()
      metrics must have size 1
      val samples = metrics.get(0).samples
      //this is the count sample
      val countSample = samples.get(0)
      countSample.value mustBe 1.0
      countSample.labelValues must have size 5
      countSample.labelValues.get(0) mustBe DefaultPlayUnmatchedDefaults.UnmatchedRouteString
      countSample.labelValues.get(1) mustBe "404"
      countSample.labelValues.get(2) mustBe DefaultPlayUnmatchedDefaults.UnmatchedControllerString
      countSample.labelValues.get(3) mustBe DefaultPlayUnmatchedDefaults.UnmatchedPathString
      countSample.labelValues.get(4) mustBe DefaultPlayUnmatchedDefaults.UnmatchedVerbString
    }
  }

} 
Example 2
Source File: SecurityController.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.controllers

import javax.inject.Inject

import cats.data.{EitherT, OptionT}
import cats.instances.future._
import cats.syntax.either._
import com.mohiva.play.silhouette.api.util.Credentials
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import de.frosner.broccoli.services.{SecurityService, WebSocketService}
import jp.t2v.lab.play2.auth.{BroccoliSimpleAuthorization, LoginLogout}
import play.api.{Environment, Logger}
import play.api.cache.CacheApi
import play.api.data.Forms._
import play.api.data._
import play.api.libs.json.Json
import play.api.mvc.{Action, AnyContent, Controller, Results}

import scala.concurrent.Future

case class SecurityController @Inject()(
    override val securityService: SecurityService,
    override val cacheApi: CacheApi,
    override val playEnv: Environment,
    webSocketService: WebSocketService
) extends Controller
    with LoginLogout
    with BroccoliSimpleAuthorization {

  private val log = Logger(getClass)

  import scala.concurrent.ExecutionContext.Implicits.global

  // https://www.playframework.com/documentation/2.5.x/ScalaForms
  val loginForm = Form {
    mapping(
      SecurityController.UsernameFormKey -> text,
      SecurityController.PasswordFormKey -> text
    )(Credentials.apply)(Credentials.unapply)
  }

  def login: Action[AnyContent] = Action.async { implicit request =>
    getSessionId(request).map(id => (id, webSocketService.closeConnections(id))) match {
      case Some((id, true)) => log.info(s"Removing websocket connection of $id due to another login")
      case _                =>
    }
    (for {
      credentials <- EitherT.fromEither[Future](
        loginForm.bindFromRequest().fold(Function.const(Results.BadRequest.asLeft), _.asRight))
      login <- OptionT(securityService.authenticate(credentials)).toRight(Results.Unauthorized)
      result <- EitherT.right(gotoLoginSucceeded(login.providerKey))
      user <- OptionT(resolveUser(login.providerKey)).toRight(Results.Unauthorized)
    } yield {
      val userResult = Results.Ok(Json.toJson(user))
      result.copy(
        header = result.header.copy(
          headers = userResult.header.headers
            .get("Content-Type")
            .map { contentType =>
              result.header.headers.updated("Content-Type", contentType)
            }
            .getOrElse(result.header.headers)
        ),
        body = userResult.body
      )
    }).merge
  }

  def logout = Action.async(parse.empty) { implicit request =>
    gotoLogoutSucceeded.andThen {
      case tryResult =>
        getSessionId(request).map(id => (id, webSocketService.closeConnections(id))) match {
          case Some((id, true))  => log.info(s"Removing websocket connection of $id due to logout")
          case Some((id, false)) => log.info(s"There was no websocket connection for session $id")
          case None              => log.info(s"No session available to logout from")
        }
    }
  }

  def verify = StackAction(parse.empty) { implicit request =>
    Ok(loggedIn.name)
  }

}

object SecurityController {

  val UsernameFormKey = "username"
  val PasswordFormKey = "password"

} 
Example 3
Source File: ToHTTPResultSpec.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.http

import cats.syntax.either._
import org.scalacheck.Gen
import org.specs2.ScalaCheck
import play.api.mvc.Results
import play.api.test.PlaySpecification

import scala.concurrent.Future

class ToHTTPResultSpec extends PlaySpecification with ScalaCheck {
  import ToHTTPResult.ops._

  "ToHTTPResult.instance" should {
    "convert to a result with the given function" in prop { (body: String, statusCode: Int) =>
      implicit val instance = ToHTTPResult.instance[String](Results.Status(statusCode)(_))

      val result = Future.successful(body.toHTTPResult)
      (status(result) === statusCode) and (contentAsString(result) === body)
    }.setGens(Gen.identifier.label("value"), Gen.choose(200, 500).label("status"))
  }

  "ToHTTPResult Either instance" should {
    "convert to a result of either left or right" in prop { (value: Either[String, String]) =>
      implicit val stringToHTTPResult = ToHTTPResult.instance[String](Results.Ok(_))
      val result = Future.successful(value.toHTTPResult)
      contentAsString(result) === value.merge
    }.setGen(
      Gen.oneOf(Gen.identifier.map(Either.left).label("left"), Gen.identifier.map(Either.right).label("right"))
    )
  }
} 
Example 4
Source File: OnlyHttpsFilter.scala    From get-you-a-license   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package filters

import akka.stream.Materializer
import play.api.{Environment, Mode}
import play.api.http.HeaderNames
import play.api.mvc.{Filter, RequestHeader, Result, Results}

import scala.concurrent.{ExecutionContext, Future}

class OnlyHttpsFilter(environment: Environment)(implicit val mat: Materializer, ec: ExecutionContext) extends Filter {
  def apply(nextFilter: (RequestHeader) => Future[Result])(requestHeader: RequestHeader): Future[Result] = {
    nextFilter(requestHeader).map { result =>
      if (requestHeader.secure || environment.mode == Mode.Dev) {
        result
      }
      else {
        Results.MovedPermanently("https://" + requestHeader.host + requestHeader.uri)
      }
    }
  }
} 
Example 5
Source File: AuthFilter.scala    From CM-Well   with Apache License 2.0 5 votes vote down vote up
package filters

import akka.stream.Materializer
import play.api.libs.json.Json
import play.api.mvc.{Filter, RequestHeader, Result, Results}
import security.PermissionLevel._
import security._
import wsutil._
import javax.inject._
import cmwell.ws.Settings

import scala.concurrent.{ExecutionContext, Future}

class AuthFilter @Inject()(authCache: EagerAuthCache, authUtils: AuthUtils, authorization: Authorization)(
  implicit override val mat: Materializer,
  ec: ExecutionContext
) extends Filter {

  private val useAuthorizationParam = java.lang.Boolean.getBoolean("use.authorization")
  private val irrelevantPaths = Set("/ii/", "/_")

  def apply(nextFilter: RequestHeader => Future[Result])(requestHeader: RequestHeader): Future[Result] = {
    isAuthenticatedAndAuthorized(requestHeader) match {
      case Allowed(username) =>
        nextFilter(requestHeader.addAttr(Attrs.UserName, username))
      case NotAllowed(msg) if PermissionLevel(requestHeader.method) == PermissionLevel.Read =>
        Future(Results.Forbidden(msg))
      case NotAllowed(msg) =>
        Future(Results.Forbidden(Json.obj("success" -> false, "message" -> msg)))
    }
  }

  private def isAuthenticatedAndAuthorized(requestHeader: RequestHeader): AuthResponse = {
    def isRequestWriteToMeta = authUtils.isWriteToMeta(PermissionLevel(requestHeader.method), requestHeader.path)

    val tokenOpt = requestHeader.headers
      .get("X-CM-WELL-TOKEN2")
      . // todo TOKEN2 is only supported for backward compatibility. one day we should stop supporting it
      orElse(requestHeader.headers.get("X-CM-WELL-TOKEN"))
      .orElse(requestHeader.getQueryString("token"))
      .orElse(requestHeader.cookies.get("X-CM-WELL-TOKEN2").map(_.value))
      . // todo TOKEN2 is only supported for backward compatibility. one day we should stop supporting it
      orElse(requestHeader.cookies.get("X-CM-WELL-TOKEN").map(_.value))
      .flatMap(Token(_, authCache))

    val modifier = tokenOpt.fold("anonymous")(_.username) + requestHeader.getQueryString("modifier").fold("")("/".+)

    if ((!useAuthorizationParam && !isRequestWriteToMeta) || irrelevantPaths.exists(requestHeader.path.startsWith))
      Allowed(modifier)
    else {
      val request =
        (normalizePath(requestHeader.path), PermissionLevel(requestHeader.method, requestHeader.getQueryString("op")))

      tokenOpt match {
        case Some(token) if token.isValid => {
          authCache.getUserInfoton(token.username) match {
            case Some(user) =>
              AuthResponse(authorization.isAllowedForUser(request, user, Some(token.username)),
                "Authenticated but not authorized", modifier)
            case None if token.username == "root" || token.username == "pUser" =>
              Allowed(modifier) // special case only required for cases when CRUD is not yet ready
            case None => NotAllowed(s"Username ${token.username} was not found in CM-Well")
          }
        }
        case Some(_) => NotAllowed("given token is not valid (not signed or expired)")
        case None => AuthResponse(authorization.isAllowedForAnonymousUser(request), "Not authorized, please login first", modifier)
      }
    }
  }

  sealed trait AuthResponse
  case class Allowed(modifier: String) extends AuthResponse
  case class NotAllowed(msg: String) extends AuthResponse

  object AuthResponse {
    def apply(allowed: Boolean, msg: String, modifier: String): AuthResponse =
      if(allowed) Allowed(modifier) else NotAllowed(msg)
  }
} 
Example 6
Source File: TrafficShapingFilter.scala    From CM-Well   with Apache License 2.0 5 votes vote down vote up
package filters

import javax.inject._

import akka.stream.Materializer
import play.api.mvc.{Filter, RequestHeader, Result, Results}

import scala.concurrent.{ExecutionContext, Future}
import scala.concurrent.duration._
import scala.util.{Success, Try}
import cmwell.ws.Settings._
import trafficshaping._


class TrafficShapingFilter @Inject()(implicit override val mat: Materializer, ec: ExecutionContext) extends Filter {

  def reqType(req: RequestHeader): String = {
    val opOpt = req.getQueryString("op")
    val segs = req.path.split("/")
    val path = Try(req.path.split("/")(1))

    (opOpt, path) match {
      case (Some(op), _)                           => op
      case (None, Success(p)) if p.startsWith("_") => p
      case _                                       => "get"
    }
  }

  def collectData(resultFuture: Future[Result], ip: String, requestType: String, startTime: Long): Unit = {
    if (ip != "127.0.0.1") {
      resultFuture.foreach { r =>
        val requestDuration = System.currentTimeMillis() - startTime
        TrafficShaper.addRequest(ip, requestType, requestDuration)
      }

    }
  }

  def collectData(ip: String, requestType: String, startTime: Long): Unit = {
    if (ip != "127.0.0.1") {
      val requestDuration = System.currentTimeMillis() - startTime
      TrafficShaper.addRequest(ip, requestType, requestDuration)
    }
  }

  def isNeedTrafficShapping(ip: String, requestType: String): Boolean = {
    val untrackedRequests = Vector("_in", "_ow")
    !untrackedRequests.contains(requestType)
  }

  override def apply(next: (RequestHeader) => Future[Result])(request: RequestHeader): Future[Result] = {
    import Math._

    val ip = request.attrs(Attrs.UserIP)
    lazy val resultFuture = next(request)
    val startTime = request.attrs(Attrs.RequestReceivedTimestamp)
    val maxDurationMillis = maxRequestTimeSec * 1000
    val penalty = TrafficShaper.penalty(ip)
    val requestType = reqType(request)

    if (TrafficShaper.isEnabled && isNeedTrafficShapping(ip, requestType))
      penalty match {
        case NoPenalty =>
          collectData(resultFuture, ip, requestType, startTime)
          resultFuture
        case DelayPenalty =>
          collectData(resultFuture, ip, requestType, startTime)
          resultFuture.flatMap { res =>
            val currentTime = System.currentTimeMillis()
            val reqDurationMillis = currentTime - startTime
            val penalty = min(reqDurationMillis, maxDurationMillis - reqDurationMillis).max(0)
            cmwell.util.concurrent.delayedTask(penalty.millis) { res }
          }
        case FullBlockPenalty =>
          cmwell.util.concurrent.delayedTask(maxDurationMillis.millis) {
            collectData(ip, requestType, startTime)
            Results.ServiceUnavailable("Please reduce the amount of requests")
          }
      } else
      resultFuture
  }
} 
Example 7
Source File: ErrorHandler.scala    From metronome   with Apache License 2.0 5 votes vote down vote up
package dcos.metronome
package api

import org.slf4j.LoggerFactory
import play.api.http.HttpErrorHandler
import play.api.http.Status._
import play.api.libs.json.Json
import play.api.mvc.{RequestHeader, Result, Results}
import play.twirl.api.HtmlFormat

import scala.concurrent.Future

class ErrorHandler extends HttpErrorHandler {

  private[this] val log = LoggerFactory.getLogger(getClass)

  override def onClientError(request: RequestHeader, statusCode: Int, message: String): Future[Result] = {
    log.debug(s"Client Error on path ${request.path}. Message: $message Status: $statusCode")
    val outputMessage = if (statusCode == NOT_FOUND) { ErrorHandler.noRouteHandlerMessage }
    else { message }
    val json = Json.obj("message" -> escape(outputMessage), "requestPath" -> escape(request.path))
    Future.successful(Results.Status(statusCode)(json))
  }

  override def onServerError(request: RequestHeader, exception: Throwable): Future[Result] = {

    
  private def escape(msg: String): String = HtmlFormat.escape(msg).body
}

object ErrorHandler {
  val noRouteHandlerMessage = "Unknown route."
} 
Example 8
Source File: ServerSpec.scala    From metronome   with Apache License 2.0 5 votes vote down vote up
package dcos.metronome
package api

import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.{Millis, Second, Span}
import org.scalatestplus.play._
import play.api.ApplicationLoader.Context
import play.api.libs.ws.ahc.AhcWSComponents
import play.api.mvc.Results
import play.api.test.Helpers._

class ServerSpec
    extends PlaySpec
    with OneServerPerSuiteWithComponents[MockApiComponents with AhcWSComponents]
    with Results
    with ScalaFutures {

  override implicit def patienceConfig: PatienceConfig = PatienceConfig(Span(1, Second), Span(50, Millis))
  override def createComponents(context: Context) = new MockApiComponents(context) with AhcWSComponents

  "Server query" should {
    "work" in {
      implicit val ec = app.materializer.executionContext
      val wsClient = components.wsClient

      whenReady(wsUrl("/ping")(portNumber, wsClient).get) { response =>
        response.status mustBe OK
        response.body mustBe "pong"
      }
    }
  }
} 
Example 9
Source File: PrometheusControllerSpec.scala    From play-prometheus-filters   with MIT License 5 votes vote down vote up
package com.github.stijndehaes.playprometheusfilters.controllers

import java.util.Collections

import io.prometheus.client.Collector.MetricFamilySamples
import io.prometheus.client.{Collector, CollectorRegistry}
import org.mockito.Mockito._
import org.scalatest.mockito.MockitoSugar
import org.scalatestplus.play.PlaySpec
import play.api.mvc.Results
import play.api.test.FakeRequest
import play.api.test.Helpers._


class PrometheusControllerSpec extends PlaySpec with Results with MockitoSugar {

  "Get metrics method" should {
    "Return the prometheus metrics" in {
      val collectorRegistry = mock[CollectorRegistry]
      val metricsFamilySample = new MetricFamilySamples("test", Collector.Type.COUNTER, "help", Collections.emptyList())
      when(collectorRegistry.metricFamilySamples()).thenReturn(new java.util.Vector(Collections.singleton(metricsFamilySample)).elements)

      val client = new PrometheusController(collectorRegistry, stubControllerComponents())

      val request = FakeRequest(GET, "/metrics")

      val result = client.getMetrics.apply(request)
      status(result) mustBe OK
      contentAsString(result) mustBe "# HELP test help\n# TYPE test counter\n"
    }
  }

} 
Example 10
Source File: StatusCounterFilterSpec.scala    From play-prometheus-filters   with MIT License 5 votes vote down vote up
package com.github.stijndehaes.playprometheusfilters.filters

import com.github.stijndehaes.playprometheusfilters.mocks.MockController
import io.prometheus.client.CollectorRegistry
import org.mockito.ArgumentMatchers.any
import org.mockito.Mockito.verify
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{MustMatchers, WordSpec}
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.Configuration
import play.api.mvc.Results
import play.api.test.Helpers.stubControllerComponents
import play.api.test.{DefaultAwaitTimeout, FakeRequest, FutureAwaits}

import scala.concurrent.ExecutionContext.Implicits.global

class StatusCounterFilterSpec extends WordSpec with MustMatchers with MockitoSugar with Results with DefaultAwaitTimeout with FutureAwaits with GuiceOneAppPerSuite {

  private implicit val mat = app.materializer
  private val configuration = mock[Configuration]

  "Filter constructor" should {
    "Add a counter to the prometheus registry" in {
      val collectorRegistry = mock[CollectorRegistry]
      new StatusCounterFilter(collectorRegistry, configuration)
      verify(collectorRegistry).register(any())
    }
  }

  "Apply method" should {
    "Count the requests with status" in {
      val filter = new StatusCounterFilter(mock[CollectorRegistry], configuration)
      val rh = FakeRequest()
      val action = new MockController(stubControllerComponents()).ok

      await(filter(action)(rh).run())

      val metrics = filter.metrics(0).metric.collect()
      metrics must have size 1
      val samples = metrics.get(0).samples
      samples.get(0).value mustBe 1.0
      samples.get(0).labelValues must have size 1
      samples.get(0).labelValues.get(0) mustBe "200"
    }
  }

} 
Example 11
Source File: StatusAndRouteLatencyFilterSpec.scala    From play-prometheus-filters   with MIT License 5 votes vote down vote up
package com.github.stijndehaes.playprometheusfilters.filters

import com.github.stijndehaes.playprometheusfilters.metrics.DefaultPlayUnmatchedDefaults
import com.github.stijndehaes.playprometheusfilters.mocks.MockController
import io.prometheus.client.CollectorRegistry
import org.mockito.ArgumentMatchers.any
import org.mockito.Mockito.verify
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{MustMatchers, WordSpec}
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.Configuration
import play.api.libs.typedmap.TypedMap
import play.api.mvc.Results
import play.api.routing.{HandlerDef, Router}
import play.api.test.Helpers.stubControllerComponents
import play.api.test.{DefaultAwaitTimeout, FakeRequest, FutureAwaits}

import scala.concurrent.ExecutionContext.Implicits.global

class StatusAndRouteLatencyFilterSpec extends WordSpec with MustMatchers with MockitoSugar with Results with DefaultAwaitTimeout with FutureAwaits with GuiceOneAppPerSuite  {

  private implicit val mat = app.materializer
  private val configuration = mock[Configuration]

  "Filter constructor" should {
    "Add a histogram to the prometheus registry" in {
      val collectorRegistry = mock[CollectorRegistry]
      new StatusAndRouteLatencyFilter(collectorRegistry, configuration)
      verify(collectorRegistry).register(any())
    }
  }

  "Apply method" should {
    "Measure the latency" in {
      val filter = new StatusAndRouteLatencyFilter(mock[CollectorRegistry], configuration)
      val rh = FakeRequest().withAttrs( TypedMap(
        Router.Attrs.HandlerDef -> HandlerDef(null, null, "testController", "test", null, "GET", "/path", null ,null)
      ))
      val action = new MockController(stubControllerComponents()).ok

      await(filter(action)(rh).run())

      val metrics = filter.metrics(0).metric.collect()
      metrics must have size 1
      val samples = metrics.get(0).samples
      //this is the count sample
      val countSample = samples.get(samples.size() - 2)
      countSample.value mustBe 1.0
      countSample.labelValues must have size 5
      countSample.labelValues.get(0) mustBe "test"
      countSample.labelValues.get(1) mustBe "200"
      countSample.labelValues.get(2) mustBe "testController"
      countSample.labelValues.get(3) mustBe "/path"
      countSample.labelValues.get(4) mustBe "GET"
    }

    "Measure the latency for an unmatched route" in {
      val filter = new StatusAndRouteLatencyFilter(mock[CollectorRegistry], configuration)
      val rh = FakeRequest()
      val action = new MockController(stubControllerComponents()).error

      await(filter(action)(rh).run())

      val metrics = filter.metrics(0).metric.collect()
      metrics must have size 1
      val samples = metrics.get(0).samples
      //this is the count sample
      val countSample = samples.get(samples.size() - 2)
      countSample.value mustBe 1.0
      countSample.labelValues must have size 5
      countSample.labelValues.get(0) mustBe DefaultPlayUnmatchedDefaults.UnmatchedRouteString
      countSample.labelValues.get(1) mustBe "404"
      countSample.labelValues.get(2) mustBe DefaultPlayUnmatchedDefaults.UnmatchedControllerString
      countSample.labelValues.get(3) mustBe DefaultPlayUnmatchedDefaults.UnmatchedPathString
      countSample.labelValues.get(4) mustBe DefaultPlayUnmatchedDefaults.UnmatchedVerbString
    }
  }
} 
Example 12
Source File: AuthConfigImpl.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.controllers

import com.mohiva.play.silhouette.api.LoginInfo
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import de.frosner.broccoli.auth.{Account, Role}
import de.frosner.broccoli.services.SecurityService
import jp.t2v.lab.play2.auth._
import play.api.{Environment, Mode}
import play.api.cache.CacheApi
import play.api.libs.json.JsString
import play.api.mvc.{RequestHeader, Result, Results}

import scala.concurrent.{ExecutionContext, Future}
import scala.reflect.ClassTag

trait AuthConfigImpl extends AuthConfig {

  val securityService: SecurityService

  val playEnv: Environment

  val cacheApi: CacheApi

  type Id = String

  type User = Account

  type Authority = Role

  val idTag: ClassTag[Id] = scala.reflect.classTag[Id]

  val sessionTimeoutInSeconds = securityService.sessionTimeoutInSeconds

  val cookieSecure = securityService.cookieSecure

  override lazy val idContainer: AsyncIdContainer[Id] = securityService.allowMultiLogin match {
    case true  => AsyncIdContainer(new MultiLoginCacheIdContainer[Id](cacheApi))
    case false => AsyncIdContainer(new CacheIdContainer[Id])
  }

  def resolveUser(id: Id)(implicit ctx: ExecutionContext): Future[Option[User]] =
    securityService.identityService.retrieve(LoginInfo(CredentialsProvider.ID, id))

  def loginSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext): Future[Result] =
    Future.successful(Results.Ok(JsString("Login successful!"))) // the content is not used anyway as the controller replaces it

  def logoutSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext): Future[Result] =
    Future.successful(Results.Ok(JsString("Logout successful!")))

  def authenticationFailed(request: RequestHeader)(implicit ctx: ExecutionContext): Future[Result] =
    Future.successful(Results.Forbidden("Authentication failed."))

  override def authorizationFailed(request: RequestHeader, user: User, authority: Option[Authority])(
      implicit context: ExecutionContext): Future[Result] =
    Future.successful(Results.Forbidden(
      s"Authorization failed: Your privileges (${user.role}) are not matching the required (${authority.getOrElse("None")})."))

  def authorize(user: User, authority: Authority)(implicit ctx: ExecutionContext): Future[Boolean] = Future.successful {
    user.role match {
      case Role.Administrator => true
      case Role.Operator      => authority == Role.Operator || authority == Role.User
      case Role.User          => authority == Role.User
    }
  }

  override lazy val tokenAccessor = new CookieTokenAccessor(
    cookieName = AuthConfigImpl.CookieName,
    cookieSecureOption = playEnv.mode == Mode.Prod && cookieSecure,
    cookieHttpOnlyOption = true,
    cookieDomainOption = None,
    cookiePathOption = "/",
    cookieMaxAge = Some(sessionTimeoutInSeconds)
  )

}

object AuthConfigImpl {

  val CookieName = "BROCCOLI_SESS_ID"

} 
Example 13
Source File: WSPlayListener.scala    From scala-loci   with Apache License 2.0 5 votes vote down vote up
package loci
package communicator
package ws.akka

import java.net.URI
import java.util.concurrent.ConcurrentLinkedQueue

import play.api.mvc.Security.AuthenticatedRequest
import play.api.mvc.{RequestHeader, Results, WebSocket}

import scala.concurrent.Future
import scala.util.{Failure, Success, Try}

private object WSPlayListener {
  locally(WSPlayListener)

  def apply[P <: WS: WSProtocolFactory](properties: WS.Properties) =
    new Listener[P] with WebSocketHandler {
      private def webSocket(authenticated: Either[Option[String], Any]) =
        WebSocket { request =>
          val uri = new URI(s"dummy://${request.host}")
          val host = uri.getHost
          val port = uri.getPort

          val certificates = request.clientCertificateChain.toSeq.flatten
          val isAuthenticated =
            authenticated.isRight ||
            compatibility.either.left(authenticated).nonEmpty ||
            (request.secure && certificates.nonEmpty)
          val isProtected = request.secure
          val isEncrypted = request.secure

          val ws = implicitly[WSProtocolFactory[P]] make (
            request.uri,
            Option(host),
            if (port < 0) None else Some(port),
            this, isAuthenticated, isEncrypted, isProtected,
            Some(Left(request)),
            authenticated.left.toOption.flatten toRight certificates)

          Future successful (ws match {
            case Failure(exception) =>
              connectionEstablished(Failure(exception))
              Left(Results.NotFound)

            case Success(ws) =>
              Right(WSPlayHandler handleWebSocket (
                Future successful ws, properties, connectionEstablished))
          })
        }

      def apply(authenticatedName: String) = webSocket(Left(Some(authenticatedName)))
      def apply(authenticatedName: Option[String]) = webSocket(Left(authenticatedName))
      def apply(request: RequestHeader) = request match {
        case request: AuthenticatedRequest[_, _] =>
          request.user match {
            case user: String =>
              webSocket(Left(Some(user)))(request)
            case user =>
              webSocket(Right(user))(request)
          }
        case _ =>
          webSocket(Left(None))(request)
      }

      private val connected = new ConcurrentLinkedQueue[Connected[P]]

      private def connectionEstablished(connection: Try[Connection[P]]) = {
        val iterator = connected.iterator
        while (iterator.hasNext)
          iterator.next().fire(connection)
      }

      protected def startListening(connectionEstablished: Connected[P]): Try[Listening] = {
        connected.add(connectionEstablished)

        Success(new Listening {
          def stopListening(): Unit = connected.remove(connectionEstablished)
        })
      }
    }
} 
Example 14
Source File: writeableHelper.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package de.zalando.play.controllers

import akka.util.ByteString
import play.api.http.Writeable
import play.api.libs.json._
import play.api.mvc.Results.{ Redirect, Status }
import play.api.mvc.{ AnyContentAsMultipartFormData, RequestHeader, Results }

import scala.language.implicitConversions

case class WriteableWrapper[T](w: Writeable[T], m: Manifest[T])

object WriteableWrapper {
  implicit def writeable2wrapper[T](w: Writeable[T])(implicit m: Manifest[T]): WriteableWrapper[T] =
    WriteableWrapper(w, m)
  implicit val anyContentAsMultipartFormWritable: Writeable[AnyContentAsMultipartFormData] = {
    MultipartFormDataWritable.singleton.map(_.mdf)
  }
}


object ResponseWriters extends ResponseWritersBase

trait ResponseWritersBase {

  type ContentType = String

  def custom: Seq[WriteableWrapper[_]] = Seq.empty

  case class choose[T](mimeType: ContentType) {
    def apply[R <: Any](registry: Seq[WriteableWrapper[_]] = custom)(implicit m: Manifest[R]): Option[Writeable[R]] =
      registry filter {
        _.w.contentType.exists(_ == mimeType)
      } find { p =>
        m.runtimeClass.isAssignableFrom(p.m.runtimeClass)
      } map {
        _.asInstanceOf[WriteableWrapper[R]]
      } map (_.w)
  }

  implicit val jsonTranslatedParsingErrorWrites = Json.writes[TranslatedParsingError]

  implicit val jsonTranslatedParsingErrorsContainerWrites = Json.writes[TranslatedParsingErrorsContainer]
}

object WrappedBodyParsers extends WrappedBodyParsersBase

trait WrappedBodyParsersBase {
  implicit def parser2parserWrapper[T](p: Parser[T])(implicit m: Manifest[T]): ParserWrapper[T] = ParserWrapper(p, m)
  type Parser[T] = ByteString => T
  case class ParserWrapper[T](p: Parser[T], m: Manifest[T])
  val custom: Seq[(String, ParserWrapper[_])] = Seq.empty
  def anyParser[T](implicit manifest: Manifest[T]): Seq[(String, Parser[T])] =
    custom.filter(_._2.m.runtimeClass.isAssignableFrom(manifest.runtimeClass)).map { e =>
      e.copy(_2 = e._2.asInstanceOf[ParserWrapper[T]].p)
    }
  def optionParser[T](implicit manifest: Manifest[T]): Seq[(String, Parser[Option[T]])] = anyParser[Option[T]]
}

trait ResultWrapper[ResultT] {
  val emptyByteString = akka.util.CompactByteString.empty
  def statusCode: Int
  def result: ResultT
  def toResultWithWriter(implicit writer: Writeable[ResultT]): play.api.mvc.Result =
    if (statusCode / 100 == 3)
      Redirect(result.toString, statusCode)
    else
      Status(statusCode)(result)

  def writer: String => Option[Writeable[ResultT]]
  def toResult(mimeType: String): Option[play.api.mvc.Result] =
    if (statusCode / 100 == 3)
      Option(Redirect(result.toString, statusCode))
    else
      writer(mimeType).map(Status(statusCode)(result)(_))

} 
Example 15
Source File: BintrayHttp.scala    From releaser   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.releaser.bintray

import java.net.URL
import java.nio.file.Path
import java.util.concurrent.TimeUnit

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import play.api.libs.ws.ning.{NingAsyncHttpClientConfigBuilder, NingWSClient, NingWSClientConfig}
import play.api.libs.ws.{WSAuthScheme, WSClientConfig, WSResponse}
import play.api.mvc.Results
import uk.gov.hmrc.{Logger, ServiceCredentials}

import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.util.{Failure, Success, Try}
import scala.concurrent.duration._

class BintrayHttp(creds:ServiceCredentials) extends Logger {

  implicit val system = ActorSystem()
  implicit val materializer = ActorMaterializer()

  private def getTimeoutPropertyOptional(key: String) = Option(System.getProperty(key)).map(_.toLong milliseconds)

  def wsClientConfig = NingWSClientConfig(
    wsClientConfig = WSClientConfig(
    connectionTimeout = getTimeoutPropertyOptional("wsclient.timeout.connection").getOrElse(2 seconds),
    idleTimeout = getTimeoutPropertyOptional("wsclient.timeout.idle").getOrElse(2 seconds),
    requestTimeout = getTimeoutPropertyOptional("wsclient.timeout.request").getOrElse(2 seconds)
    )
  )

  val ws = new NingWSClient(new NingAsyncHttpClientConfigBuilder(wsClientConfig).build())

  def apiWs(url:String) = ws.url(url)
    .withAuth(
      creds.user, creds.pass, WSAuthScheme.BASIC)
    .withHeaders("content-type" -> "application/json")

  def emptyPost(url:String): Try[Unit] = {
    log.info(s"posting file to $url")

    val call = apiWs(url).post(Results.EmptyContent())
    val result: WSResponse = Await.result(call, Duration.apply(5, TimeUnit.MINUTES))

    result.status match {
      case s if s >= 200 && s < 300 => Success(new URL(url))
      case _@e => Failure(new scala.Exception(s"Didn't get expected status code when writing to Bintray. Got status ${result.status}: ${result.body}"))
    }
  }

  def get[A](url:String): Try[String] ={
    log.info(s"getting file from $url")

    val call = apiWs(url).get()
    val result: WSResponse = Await.result(call, Duration.apply(5, TimeUnit.MINUTES))

    result.status match {
      case s if s >= 200 && s < 300 => Success(result.body)
      case _@e => Failure(new scala.Exception(s"Didn't get expected status code when writing to Bintray. Got status ${result.status}: ${result.body}"))
    }
  }

  def putFile(version: VersionDescriptor, file: Path, url: String): Try[Unit] = {
    log.info(s"version $version")
    log.info(s"putting file to $url")

    val call = apiWs(url)
      .withHeaders(
        "X-Bintray-Package" -> version.artefactName,
        "X-Bintray-Version" -> version.version)
      .put(file.toFile)

    val result: WSResponse = Await.result(call, Duration.apply(6, TimeUnit.MINUTES))

    result.status match {
      case s if s >= 200 && s < 300 => Success(Unit)
      case _@e => Failure(new scala.Exception(s"Didn't get expected status code when writing to Bintray. Got status ${result.status}: ${result.body}"))
    }
  }
} 
Example 16
Source File: PlayRouter.scala    From caliban   with Apache License 2.0 5 votes vote down vote up
package caliban

import akka.stream.Materializer
import play.api.mvc.{ ActionBuilder, AnyContent, ControllerComponents, PlayBodyParsers, Request, Results }
import play.api.routing.Router.Routes
import play.api.routing.SimpleRouter
import play.api.routing.sird._
import zio.Runtime
import zio.duration.Duration
import scala.concurrent.ExecutionContext

case class PlayRouter[R, E](
  interpreter: GraphQLInterpreter[R, E],
  controllerComponents: ControllerComponents,
  playground: Boolean = true,
  allowGETRequests: Boolean = true,
  subscriptions: Boolean = true,
  skipValidation: Boolean = false,
  enableIntrospection: Boolean = true,
  keepAliveTime: Option[Duration] = None
)(implicit runtime: Runtime[R], materializer: Materializer)
    extends SimpleRouter
    with PlayAdapter {

  override val actionBuilder: ActionBuilder[Request, AnyContent] = controllerComponents.actionBuilder
  override val parse: PlayBodyParsers                            = controllerComponents.parsers
  implicit val ec: ExecutionContext                              = controllerComponents.executionContext

  override def routes: Routes = {
    case POST(p"/api/graphql") => makePostAction(interpreter, skipValidation, enableIntrospection)
    case GET(
        p"/api/graphql" ? q_o"query=$query" & q_o"variables=$variables" & q_o"operationName=$operation" & q_o"extensions=$extensions"
        ) if allowGETRequests =>
      makeGetAction(interpreter, skipValidation, enableIntrospection)(query, variables, operation, extensions)
    case GET(p"/ws/graphql") if subscriptions =>
      makeWebSocket(interpreter, skipValidation, enableIntrospection, keepAliveTime)
    case GET(p"/graphiql") if playground =>
      actionBuilder(
        Results.Ok
          .sendResource("graphiql.html")(controllerComponents.executionContext, controllerComponents.fileMimeTypes)
      )
  }

} 
Example 17
Source File: DeleteOrganizationMetricsApiSpec.scala    From cave   with MIT License 5 votes vote down vote up
import com.cave.metrics.data.Role
import data.UserData
import org.joda.time.DateTime
import org.mockito.Matchers._
import org.mockito.{Matchers, Mockito}
import org.mockito.Mockito._
import play.api.mvc.Results
import play.api.test.{FakeRequest, FakeApplication, PlaySpecification}
import scala.concurrent.{Future, ExecutionContext}
import scala.Some
import scala.util.Success

class DeleteOrganizationMetricsApiSpec extends PlaySpecification with Results with AbstractMetricsApiSpec with UserData {

  val MetricName = "metric"
  val organization = GiltOrg
  val user = SOME_USER

  "DELETE /organizations/:name/metric-names/:metric" should {
    "respond with 204 when deletion succeeds" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true))

      val result = new TestController().deleteOrganizationMetric(organization.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN))
      status(result) must equalTo(NO_CONTENT)
      contentAsString(result) must equalTo("")
    }

    "respond with 404 when metric doesn't exist" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(false))

      val result = new TestController().deleteOrganizationMetric(organization.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN))
      status(result) must equalTo(NOT_FOUND)
    }

    "respond with 403 when it's not an admin user" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Member)))

      val result = new TestController().deleteOrganizationMetric(organization.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN))
      status(result) must equalTo(FORBIDDEN)
    }
  }
} 
Example 18
Source File: DeleteOrganizationMetricsShortcutApiSpec.scala    From cave   with MIT License 5 votes vote down vote up
import com.cave.metrics.data.Role
import data.UserData
import org.joda.time.DateTime
import org.mockito.Matchers._
import org.mockito.{Matchers, Mockito}
import org.mockito.Mockito._
import play.api.mvc.Results
import play.api.test.{FakeRequest, FakeApplication, PlaySpecification}
import scala.concurrent.{Future, ExecutionContext}
import scala.Some
import scala.util.Success

class DeleteOrganizationMetricsShortcutApiSpec extends PlaySpecification with Results with AbstractMetricsApiSpec with UserData {

  val MetricName = "metric"
  val organization = GiltOrg
  val user = SOME_USER

  "DELETE /metric-names/:metric" should {
    "respond with 204 when metric exists" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true))

      val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName").
        withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${organization.name}.$BaseUrl"))
      status(result) must equalTo(NO_CONTENT)
      contentAsString(result) must equalTo("")
    }

    "respond with 404 when metric doesn't exist" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(false))

      val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName").
        withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${organization.name}.$BaseUrl"))
      status(result) must equalTo(NOT_FOUND)
    }

    "respond with 403 when it's not an admin user" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Member)))

      val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName").
        withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${organization.name}.$BaseUrl"))
      status(result) must equalTo(FORBIDDEN)
    }
  }
} 
Example 19
Source File: DeleteTeamMetricsShortcutApiSpec.scala    From cave   with MIT License 5 votes vote down vote up
import com.cave.metrics.data.Role
import data.UserData
import org.joda.time.DateTime
import org.mockito.Matchers._
import org.mockito.{Matchers, Mockito}
import org.mockito.Mockito._
import play.api.mvc.Results
import play.api.test.{FakeRequest, FakeApplication, PlaySpecification}
import scala.concurrent.{Future, ExecutionContext}
import scala.Some
import scala.util.Success

class DeleteTeamMetricsShortcutApiSpec extends PlaySpecification with Results with AbstractMetricsApiSpec with UserData {

  val MetricName = "metric"
  val organization = GiltOrg
  val team = GiltTeam
  val user = SOME_USER

  "DELETE /metric-names/:metric" should {
    "respond with 204 when metric exists" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true))

      val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName").
        withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${team.name}.${organization.name}.$BaseUrl"))
      status(result) must equalTo(NO_CONTENT)
      contentAsString(result) must equalTo("")
    }

    "respond with 404 metric doesn't exist" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(false))

      val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName").
        withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${team.name}.${organization.name}.$BaseUrl"))
      status(result) must equalTo(NOT_FOUND)
    }

    "work for org admins" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true))

      val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName").
        withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${team.name}.${organization.name}.$BaseUrl"))
      status(result) must equalTo(NO_CONTENT)
    }

    "respond with 403 when it's not an admin user" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member)))

      val result = new TestController().deleteMetric(MetricName)(FakeRequest(DELETE, s"/metrics-names/$MetricName").
        withHeaders(AUTHORIZATION -> AUTH_TOKEN, HOST -> s"${team.name}.${organization.name}.$BaseUrl"))
      status(result) must equalTo(FORBIDDEN)
    }
  }
} 
Example 20
Source File: DeleteTeamMetricsApiSpec.scala    From cave   with MIT License 5 votes vote down vote up
import com.cave.metrics.data.Role
import data.UserData
import org.joda.time.DateTime
import org.mockito.Matchers._
import org.mockito.{Matchers, Mockito}
import org.mockito.Mockito._
import play.api.mvc.Results
import play.api.test.{FakeRequest, FakeApplication, PlaySpecification}
import scala.concurrent.{Future, ExecutionContext}
import scala.Some
import scala.util.Success

class DeleteTeamMetricsApiSpec extends PlaySpecification with Results with AbstractMetricsApiSpec with UserData {

  val MetricName = "metric"
  val organization = GiltOrg
  val team = GiltTeam
  val user = SOME_USER

  "DELETE /organizations/:name/teams/:team/metric-names/:metric" should {
    "respond with 204 when deletion succeeds" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true))

      val result = new TestController().deleteTeamMetric(organization.name, team.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/teams/${team.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN))
      status(result) must equalTo(NO_CONTENT)
      contentAsString(result) must equalTo("")
    }

    "respond with 404 when metric doesn't exist" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Admin)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(false))

      val result = new TestController().deleteTeamMetric(organization.name, team.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/teams/${team.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN))
      status(result) must equalTo(NOT_FOUND)
    }

    "work for org admins" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member)))
      when(mockInfluxClientFactory.getClient(None)).thenReturn(mockClient -> mockContext)
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(organization.name -> Role.Admin)))
      when(mockClient.deleteMetric(s"${team.name}.${organization.name}", MetricName)(mockContext)).thenReturn(Future.successful(true))

      val result = new TestController().deleteTeamMetric(organization.name, team.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/teams/${team.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN))
      status(result) must equalTo(NO_CONTENT)
    }

    "respond with 403 when it's not an admin user" in running(FakeApplication(withGlobal = mockGlobal)) {
      Mockito.reset(mockAwsWrapper, mockDataManager, mockInfluxClientFactory)
      when(mockDataManager.findUserByToken(Matchers.eq(SOME_TOKEN), any[DateTime])(any[ExecutionContext])).thenReturn(Future.successful(Some(user)))
      when(mockDataManager.getOrganization(organization.name)).thenReturn(Success(Some(organization)))
      when(mockDataManager.getTeam(organization, team.name)).thenReturn(Success(Some(team)))
      when(mockDataManager.getTeamsForUser(Matchers.eq(organization), Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member)))
      when(mockDataManager.getOrganizationsForUser(Matchers.eq(user))(Matchers.any[ExecutionContext])).thenReturn(Future.successful(List(team.name -> Role.Member)))

      val result = new TestController().deleteTeamMetric(organization.name, team.name, MetricName)(FakeRequest(DELETE, s"/organizations/${organization.name}/teams/${team.name}/metrics-names/$MetricName").withHeaders(AUTHORIZATION -> AUTH_TOKEN))
      status(result) must equalTo(FORBIDDEN)
    }
  }
} 
Example 21
Source File: HttpsFilter.scala    From scala-clippy   with Apache License 2.0 5 votes vote down vote up
package controllers

import play.api.http.Status
import play.api.mvc.{Filter, RequestHeader, Result, Results}

import scala.concurrent.Future

class HttpsFilter extends Filter {
  def apply(nextFilter: (RequestHeader) => Future[Result])(requestHeader: RequestHeader): Future[Result] =
    requestHeader.headers.get("x-forwarded-proto") match {
      case Some(header) =>
        if (header == "https") {
          nextFilter(requestHeader)
        } else {
          Future.successful(
            Results.Redirect("https://" + requestHeader.host + requestHeader.uri, Status.MOVED_PERMANENTLY)
          )
        }
      case None => nextFilter(requestHeader)
    }
} 
Example 22
Source File: ApiErrors.scala    From izanami   with Apache License 2.0 5 votes vote down vote up
package controllers.dto.error

import cats.kernel.Monoid
import play.api.libs.json.{JsValue, Json}
import play.api.mvc.{Result, Results}
import domains.errors.{
  DataShouldExists,
  DataShouldNotExists,
  ErrorMessage,
  IdMustBeTheSame,
  InvalidCopyKey,
  IzanamiError,
  IzanamiErrors,
  Unauthorized,
  ValidationError
}

case class ApiError(message: String, args: List[String])

object ApiError {
  implicit val format = Json.format[ApiError]
}

case class ApiErrors(errors: List[ApiError], fieldErrors: Map[String, List[ApiError]]) {
  def toJson: JsValue = Json.toJson(this)(ApiErrors.format)
}

object ApiErrors {
  implicit val format = Json.format[ApiErrors]

  import cats.implicits._

  implicit val monoid: Monoid[ApiErrors] = new Monoid[ApiErrors] {
    override def empty = ApiErrors(List.empty, Map.empty)
    override def combine(x: ApiErrors, y: ApiErrors): ApiErrors = {
      val errors      = x.errors ++ y.errors
      val fieldErrors = (x.fieldErrors, y.fieldErrors).combineAll
      ApiErrors(errors, fieldErrors)
    }
  }

  def fromErrors(errors: List[IzanamiError]): ApiErrors =
    errors.foldMap {
      case ValidationError(errors, fieldErrors) =>
        ApiErrors(
          errors.toList.map { case e: ErrorMessage => ApiError(e.message, e.args.toList) },
          fieldErrors.view
            .mapValues(_.map { case e: ErrorMessage => ApiError(e.message, e.args.toList) })
            .toMap
        )
      case InvalidCopyKey(id) => error("error.id.copy.invalid", id.key)
      case IdMustBeTheSame(fromObject, inParam) =>
        error("error.id.not.the.same", fromObject.key, inParam.key)
      case DataShouldExists(id)    => error("error.data.missing", id.key)
      case DataShouldNotExists(id) => error("error.data.exists", id.key)
      case Unauthorized(id)        => error("error.data.unauthorized", id.map(_.key).toSeq: _*)
    }

  def toHttpResult(errors: IzanamiErrors): Result = {
    val forbiddens: List[Unauthorized] = errors.toList.collect { case u: Unauthorized => u }
    if (forbiddens.isEmpty) {
      Results.BadRequest(Json.toJson(fromErrors(errors.toList)))
    } else {
      Results.Forbidden(Json.toJson(forbiddens.foldMap {
        case Unauthorized(id) => error("error.data.unauthorized", id.map(_.key).toSeq: _*)
      }))
    }
  }

  def error(message: String, args: String*): ApiErrors =
    ApiErrors(List(ApiError(message, args.toList)), Map.empty)

} 
Example 23
Source File: OrganizationsHelper.scala    From dependency   with MIT License 5 votes vote down vote up
package controllers.helpers

import javax.inject.{Inject, Singleton}

import db.{Authorization, OrganizationsDao}
import io.flow.common.v0.models.UserReference
import io.flow.dependency.v0.models.Organization
import play.api.mvc.{Result, Results}

@Singleton
class OrganizationsHelper @Inject()(
  organizationsDao: OrganizationsDao
) {

  def withOrganization(user: UserReference, id: String)(
    f: Organization => Result
  ) = {
    organizationsDao.findById(Authorization.User(user.id), id) match {
      case None => {
        Results.NotFound
      }
      case Some(organization) => {
        f(organization)
      }
    }
  }

} 
Example 24
Source File: ErrorHandlers.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package daf.web

import java.io.FileNotFoundException
import java.lang.reflect.UndeclaredThrowableException

import daf.error.InvalidRequestException
import it.gov.daf.common.web.ErrorHandler
import org.apache.spark.sql.AnalysisException
import org.ietf.jgss.GSSException
import play.api.mvc.Results

object ErrorHandlers {

  val security: ErrorHandler = {
    case _: GSSException => Results.Unauthorized
  }

  val spark: ErrorHandler = {
    case _: FileNotFoundException => Results.NotFound
    case _: AnalysisException     => Results.NotFound
    case error: UndeclaredThrowableException if error.getUndeclaredThrowable.isInstanceOf[AnalysisException] => Results.NotFound
  }

  val api: ErrorHandler = {
    case error: InvalidRequestException => Results.BadRequest { error.getMessage }
  }

} 
Example 25
Source File: Authentication.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package it.gov.daf.common.authentication

import java.util.Date

import com.nimbusds.jwt.JWTClaimsSet
import org.pac4j.core.profile.{CommonProfile, ProfileManager}
import org.pac4j.jwt.config.signature.SecretSignatureConfiguration
import org.pac4j.jwt.credentials.authenticator.JwtAuthenticator
import org.pac4j.jwt.profile.JwtGenerator
import org.pac4j.play.PlayWebContext
import org.pac4j.play.store.PlaySessionStore
import play.api.Configuration
import play.api.mvc.{RequestHeader, Result, Results}

import scala.collection.convert.decorateAsScala._
import scala.collection.mutable

@SuppressWarnings(
  Array(
    "org.wartremover.warts.Throw",
    "org.wartremover.warts.Var"
  )
)
object Authentication extends Results {

  var configuration: Option[Configuration] = None
  var playSessionStore: Option[PlaySessionStore] = None
  var secret: Option[String] = None

  def apply(configuration: Configuration, playSessionStore: PlaySessionStore): Unit = {
    this.configuration = Some(configuration)
    this.playSessionStore = Some(playSessionStore)
    this.secret = this.configuration.flatMap(_.getString("pac4j.jwt_secret"))
  }

  def getClaims(requestHeader: RequestHeader): Option[mutable.Map[String, AnyRef]] = {

    val header: Option[String] = requestHeader.headers.get("Authorization")
    val token: Option[String] = for {
      h <- header
      t <- h.split("Bearer").lastOption
    } yield t.trim

    getClaimsFromToken(token)
  }

  def getClaimsFromToken(token: Option[String]): Option[mutable.Map[String, AnyRef]] = {
    val jwtAuthenticator = new JwtAuthenticator()
    jwtAuthenticator.addSignatureConfiguration(new SecretSignatureConfiguration(secret.getOrElse(throw new Exception("missing secret"))))
    token.map(jwtAuthenticator.validateTokenAndGetClaims(_).asScala)
  }

  def getProfiles(request: RequestHeader): List[CommonProfile] = {
    val webContext = new PlayWebContext(request, playSessionStore.getOrElse(throw new Exception("missing playSessionStore")))
    val profileManager = new ProfileManager[CommonProfile](webContext)
    profileManager.getAll(true).asScala.toList
  }

  def getStringToken: (RequestHeader,Long) => Option[String] = (request: RequestHeader,minutes:Long)  => {
    val generator = new JwtGenerator[CommonProfile](new SecretSignatureConfiguration(secret.getOrElse(throw new Exception("missing secret"))))
    val profiles = getProfiles(request)
    val token: Option[String] = profiles.headOption.map(profile => {
      val expDate = new Date( (new Date).getTime + 1000L*60L*minutes )//*60L*24L
      val claims = new JWTClaimsSet.Builder().expirationTime(expDate).build()
      profile.addAttributes(claims.getClaims)
      generator.generate(profile)
    })
    token
  }

  def getToken: (RequestHeader,Long) => Result = (request: RequestHeader, minutes:Long) => {
    Ok(getStringToken(request,minutes).getOrElse(""))
  }

} 
Example 26
Source File: ParSeqTraceRenderer.scala    From play-parseq   with Apache License 2.0 5 votes vote down vote up
package com.linkedin.playparseq.trace.s.renderers

import com.linkedin.parseq.trace.{ShallowTrace, Trace, TraceRelationship}
import com.linkedin.playparseq.s.stores.ParSeqTaskStore
import com.linkedin.playparseq.trace.utils.ParSeqTraceBaseVisualizer
import javax.inject.{Inject, Singleton}
import play.api.Environment
import play.api.http.HttpConfiguration
import play.api.mvc.{RequestHeader, Result, Results}
import scala.collection.JavaConverters._
import scala.concurrent.{ExecutionContext, Future}



  override def render(parSeqTaskStore: ParSeqTaskStore)(implicit requestHeader: RequestHeader): Future[Result] =
    Future {
      val traces: Set[Trace] = parSeqTaskStore.get.map(_.getTrace)
      val traceMap: Map[java.lang.Long, ShallowTrace] = traces.foldLeft(Map[java.lang.Long, ShallowTrace]())(_ ++ _.getTraceMap.asScala)
      val relationships: Set[TraceRelationship] = traces.foldLeft(Set[TraceRelationship]())(_ ++ _.getRelationships.asScala)
      // Generate Result of ParSeq Trace
      Option(showTrace(new Trace(traceMap.asJava, relationships.asJava), environment, httpConfiguration)).map(Results.Ok(_).as("text/html"))
        .getOrElse(Results.InternalServerError("Can't show Trace."))
    }

} 
Example 27
Source File: AuthValidator.scala    From maha   with Apache License 2.0 5 votes vote down vote up
package com.yahoo.maha.core.auth

import play.api.Configuration
import play.api.mvc.{RequestHeader, Result, Results}

import scala.collection.immutable.Map

case class ValidationResult(success: Boolean, user: Option[String])

trait AuthValidator {
  def init(configuration: Configuration)
  def validate(requestHeader: RequestHeader) : ValidationResult
  def handleAuthCallback(requestHeader: RequestHeader) : Result
  def handleAuthFailure(requestHeader: RequestHeader) : Result
}

class DefaultAuthValidator extends AuthValidator {
  override def init(configuration: Configuration): Unit = {
  }

  override def validate(requestHeader: RequestHeader): ValidationResult = {
    ValidationResult(success = true, user = None)
  }

  override def handleAuthCallback(requestHeader: RequestHeader): Result = {
    Results.Ok
  }

  override def handleAuthFailure(requestHeader: RequestHeader): Result = {
    Results.Ok
  }
}

trait DruidAuthHeaderProvider {
  def init(configuration: Configuration)
  def getAuthHeaders : Map[String, String]
}

class DefaultDruidAuthHeaderProvider extends DruidAuthHeaderProvider {
  override def init(configuration: Configuration): Unit = {
  }

  override def getAuthHeaders: Map[String, String] = {
    Map.empty
  }
} 
Example 28
Source File: AuthValidatorTest.scala    From maha   with Apache License 2.0 5 votes vote down vote up
package com.yahoo.maha.core.auth

import org.scalatest.{FunSuite, Matchers}
import play.api.mvc.Results

class AuthValidatorTest extends FunSuite with Matchers {

  test("test DefaultAuthValidator") {
    val authValidator: AuthValidator = new DefaultAuthValidator
    authValidator.init(null)
    val validationResult: ValidationResult = authValidator.validate(null)
    assert(validationResult.success)
    assert(validationResult.user.isEmpty)
    assert(authValidator.handleAuthCallback(null) == Results.Ok)
    assert(authValidator.handleAuthFailure(null) == Results.Ok)
  }

  test("test DefaultDruidAuthHeaderProvider") {
    val druidAuthHeaderProvider: DruidAuthHeaderProvider = new DefaultDruidAuthHeaderProvider
    druidAuthHeaderProvider.init(null)
    assert(druidAuthHeaderProvider.getAuthHeaders.isEmpty)
  }
} 
Example 29
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 30
Source File: ErrorHandler.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
import com.google.inject.Inject
import play.api.{Application, Play}
import play.api.http.{DefaultHttpErrorHandler, HttpErrorHandler, Status}
import play.api.mvc.{RequestHeader, Result, Results}
import views.html.index

import scala.concurrent.Future


class ErrorHandler @Inject()(errorHandler: DefaultHttpErrorHandler) extends HttpErrorHandler {
  override def onClientError(request: RequestHeader, statusCode: Int, message: String): Future[Result] = {
    statusCode match {
      case clientError if statusCode > 400 && statusCode < 500 => Future.successful(Results.NotFound(index("Aton")))
      case _ => Future.successful(Results.ServiceUnavailable("Unexpected error happened"))
    }
  }

  override def onServerError(request: RequestHeader, exception: Throwable): Future[Result] = {
    errorHandler.onServerError(request,exception)
  }
} 
Example 31
Source File: FutureResultsSpec.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.playhelper

import org.scalatest.{MustMatchers, WordSpec}
import play.api.mvc.Results

import scala.concurrent.Future

class FutureResultsSpec extends WordSpec with MustMatchers {
  "FutureResults" should {
    "extract data from a play Future[Result]" in {
      val result = Results.Status(202)("{}").withHeaders("some" -> "header", "something" -> "else")
      val futureResult = Future.successful(result)

      FutureResults.responseExtractor.status(futureResult) mustBe 202
      FutureResults.responseExtractor.body(futureResult) mustBe "{}"
      FutureResults.responseExtractor.headers(futureResult) mustBe Map(
        "some" -> "header",
        "something" -> "else")
    }
  }
} 
Example 32
Source File: QueryComplexityFilter.scala    From naptime   with Apache License 2.0 5 votes vote down vote up
package org.coursera.naptime.ari.graphql.controllers.filters

import javax.inject.Inject
import javax.inject.Singleton

import com.typesafe.scalalogging.StrictLogging
import org.coursera.naptime.ari.Response
import org.coursera.naptime.ari.graphql.GraphqlSchemaProvider
import org.coursera.naptime.ari.graphql.SangriaGraphQlContext
import org.coursera.naptime.ari.graphql.controllers.GraphQLController
import org.coursera.naptime.ari.graphql.marshaller.NaptimeMarshaller._
import org.coursera.naptime.ari.graphql.resolvers.NaptimeResolver
import org.coursera.naptime.ari.graphql.resolvers.NoopResolver
import play.api.libs.json.JsObject
import play.api.libs.json.Json
import play.api.mvc.Results
import sangria.ast.Document
import sangria.execution.ErrorWithResolver
import sangria.execution.Executor
import sangria.execution.QueryAnalysisError
import sangria.execution.QueryReducer

import scala.concurrent.ExecutionContext
import scala.concurrent.Future

@Singleton
class QueryComplexityFilter @Inject()(
    graphqlSchemaProvider: GraphqlSchemaProvider,
    configuration: ComplexityFilterConfiguration)(implicit executionContext: ExecutionContext)
    extends Filter
    with Results
    with StrictLogging {

  val MAX_COMPLEXITY = configuration.maxComplexity

  def apply(nextFilter: FilterFn): FilterFn = { incoming =>
    computeComplexity(incoming.document, incoming.variables)
      .flatMap { complexity =>
        if (complexity > MAX_COMPLEXITY) {
          Future.successful(
            OutgoingQuery(
              response = Json.obj("error" -> "Query is too complex.", "complexity" -> complexity),
              ariResponse = None))
        } else {
          nextFilter.apply(incoming)
        }
      }
      .recover {
        case error: QueryAnalysisError =>
          OutgoingQuery(error.resolveError.as[JsObject], None)
        case error: ErrorWithResolver =>
          OutgoingQuery(error.resolveError.as[JsObject], None)
        case error: Exception =>
          OutgoingQuery(Json.obj("errors" -> Json.arr(error.getMessage)), None)
      }
  }

  private[graphql] def computeComplexity(queryAst: Document, variables: JsObject)(
      implicit executionContext: ExecutionContext): Future[Double] = {
    // TODO(bryan): is there a way around this var?
    var complexity = 0D
    val complReducer = QueryReducer.measureComplexity[SangriaGraphQlContext] { (c, ctx) =>
      complexity = c
      ctx
    }
    val executorFut = Executor.execute(
      graphqlSchemaProvider.schema,
      queryAst,
      SangriaGraphQlContext(null, null, executionContext, debugMode = false),
      variables = variables,
      exceptionHandler = GraphQLController.exceptionHandler(logger),
      queryReducers = List(complReducer),
      deferredResolver = new NoopResolver())

    executorFut.map { _ =>
      complexity
    }

  }
}

case class ComplexityFilterConfiguration(maxComplexity: Int)

object ComplexityFilterConfiguration {
  val DEFAULT = ComplexityFilterConfiguration(100000)
} 
Example 33
Source File: response.scala    From naptime   with Apache License 2.0 5 votes vote down vote up
package org.coursera.naptime

import com.linkedin.data.DataList
import org.coursera.common.stringkey.StringKeyFormat
import org.coursera.naptime.model.KeyFormat
import org.coursera.naptime.model.Keyed
import org.coursera.naptime.actions.NaptimeSerializer
import org.coursera.naptime.actions.RestActionCategoryEngine2
import play.api.libs.json.JsValue
import play.api.libs.json.OFormat
import play.api.mvc.Result
import play.api.mvc.Results

sealed abstract class RestResponse[+T] {
  def isOk: Boolean
  def isError: Boolean
  def isRedirect: Boolean

  def map[U](fn: T => U): RestResponse[U]
}

final case class Ok[+T](
    content: T,
    related: Map[ResourceName, Ok.Related[_, _]] = Map.empty,
    pagination: Option[ResponsePagination] = None,
    
  case class Related[K, A](
      resourceName: ResourceName,
      objects: Seq[Keyed[K, A]],
      jsonFormat: OFormat[A],
      keyFormat: KeyFormat[K],
      fields: ResourceFields[A]) {
    def toJson(requestFields: RequestFields): Seq[JsValue] = {
      val finalFields = requestFields
        .forResource(resourceName)
        .getOrElse(RequestFields.empty)
        .mergeWithDefaults(fields.defaultFields)
      JsonUtilities.outputSeq(objects, finalFields)(jsonFormat, keyFormat)
    }

    def toPegasus(requestFields: RequestFields, dataList: DataList): RequestFields = {
      RestActionCategoryEngine2.serializeCollection(
        dataList,
        objects,
        keyFormat,
        NaptimeSerializer.playJsonFormats(jsonFormat),
        requestFields,
        fields)
    }
  }

}

final case class RestError(error: NaptimeActionException) extends RestResponse[Nothing] {
  override val isOk = false
  override val isError = true
  override val isRedirect = false

  override def map[U](fn: Nothing => U): RestResponse[U] = this
}

final case class Redirect(url: String, isTemporary: Boolean) extends RestResponse[Nothing] {
  override val isOk = false
  override val isError = false
  override val isRedirect = true

  override def map[U](fn: Nothing => U): RestResponse[U] = this

  def result: Result = {
    if (isTemporary) {
      Results.TemporaryRedirect(url)
    } else {
      Results.MovedPermanently(url)
    }
  }
} 
Example 34
Source File: AddressJourneyCachingHelper.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.controllershelpers

import com.google.inject.{Inject, Singleton}
import controllers.bindable.AddrType
import controllers.routes
import models.{AddressFinderDtoId, AddressJourneyData, AddressPageVisitedDtoId, CacheIdentifier, SelectedAddressRecordId, SelectedRecordSetId, SubmittedAddressDtoId, SubmittedInternationalAddressChoiceId, SubmittedResidencyChoiceDtoId, SubmittedStartDateId, SubmittedTaxCreditsChoiceId}
import models.addresslookup.{AddressRecord, RecordSet}
import models.dto._
import play.api.libs.json.Writes
import play.api.mvc.{Result, Results}
import services.LocalSessionCache
import uk.gov.hmrc.http.cache.client.CacheMap
import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse}

import scala.concurrent.{ExecutionContext, Future}

@Singleton
class AddressJourneyCachingHelper @Inject()(val sessionCache: LocalSessionCache)(implicit ec: ExecutionContext)
    extends Results {

  val addressLookupServiceDownKey = "addressLookupServiceDown"

  def addToCache[A: Writes](id: CacheIdentifier[A], record: A)(implicit hc: HeaderCarrier): Future[CacheMap] =
    sessionCache.cache(id.id, record)

  def cacheAddressLookupServiceDown()(implicit hc: HeaderCarrier): Future[CacheMap] =
    sessionCache.cache(addressLookupServiceDownKey, true)

  def clearCache()(implicit hc: HeaderCarrier): Future[HttpResponse] =
    sessionCache.remove()

  def gettingCachedAddressPageVisitedDto[T](block: Option[AddressPageVisitedDto] => Future[T])(
    implicit hc: HeaderCarrier): Future[T] =
    sessionCache.fetch() flatMap {
      case Some(cacheMap) =>
        block(cacheMap.getEntry[AddressPageVisitedDto](AddressPageVisitedDtoId.id))
      case None =>
        block(None)
    }

  def gettingCachedAddressLookupServiceDown[T](block: Option[Boolean] => T)(implicit hc: HeaderCarrier): Future[T] =
    sessionCache.fetch() map { cacheMap =>
      {
        block(cacheMap.flatMap(_.getEntry[Boolean](addressLookupServiceDownKey)))
      }
    }

  def gettingCachedTaxCreditsChoiceDto[T](block: Option[TaxCreditsChoiceDto] => T)(
    implicit hc: HeaderCarrier): Future[T] =
    sessionCache.fetch() map { cacheMap =>
      {
        block(cacheMap.flatMap(_.getEntry[TaxCreditsChoiceDto](SubmittedTaxCreditsChoiceId.id)))
      }
    }

  def gettingCachedJourneyData[T](typ: AddrType)(block: AddressJourneyData => Future[T])(
    implicit hc: HeaderCarrier): Future[T] =
    sessionCache.fetch() flatMap {
      case Some(cacheMap) =>
        block(
          AddressJourneyData(
            cacheMap.getEntry[AddressPageVisitedDto](AddressPageVisitedDtoId.id),
            cacheMap.getEntry[ResidencyChoiceDto](SubmittedResidencyChoiceDtoId(typ).id),
            cacheMap.getEntry[RecordSet](SelectedRecordSetId(typ).id),
            cacheMap.getEntry[AddressFinderDto](AddressFinderDtoId(typ).id),
            cacheMap.getEntry[AddressRecord](SelectedAddressRecordId(typ).id),
            cacheMap.getEntry[AddressDto](SubmittedAddressDtoId(typ).id),
            cacheMap.getEntry[InternationalAddressChoiceDto](SubmittedInternationalAddressChoiceId.id),
            cacheMap.getEntry[DateDto](SubmittedStartDateId(typ).id),
            cacheMap.getEntry[Boolean](addressLookupServiceDownKey).getOrElse(false)
          )
        )
      case None =>
        block(AddressJourneyData(None, None, None, None, None, None, None, None, addressLookupServiceDown = false))
    }

  def enforceDisplayAddressPageVisited(addressPageVisitedDto: Option[AddressPageVisitedDto])(block: => Future[Result])(
    implicit hc: HeaderCarrier): Future[Result] =
    addressPageVisitedDto match {
      case Some(_) =>
        block
      case None =>
        Future.successful(Redirect(controllers.address.routes.PersonalDetailsController.onPageLoad()))
    }

  def enforceResidencyChoiceSubmitted(journeyData: AddressJourneyData)(
    block: AddressJourneyData => Future[Result]): Future[Result] =
    journeyData match {
      case AddressJourneyData(_, Some(_), _, _, _, _, _, _, _) =>
        block(journeyData)
      case AddressJourneyData(_, None, _, _, _, _, _, _, _) =>
        Future.successful(Redirect(controllers.address.routes.PersonalDetailsController.onPageLoad()))
    }

} 
Example 35
Source File: BinaryHelper.scala    From dependency   with MIT License 5 votes vote down vote up
package controllers.helpers

import javax.inject.{Inject, Singleton}

import db.BinariesDao
import io.flow.dependency.v0.models.Binary
import play.api.mvc.{Result, Results}

@Singleton
class BinaryHelper @Inject()(
  binariesDao: BinariesDao
) {

  def withBinary(id: String)(
    f: Binary => Result
  ): Result = {
    binariesDao.findById(id) match {
      case None => {
        Results.NotFound
      }
      case Some(binary) => {
        f(binary)
      }
    }
  }


} 
Example 36
Source File: LibrariesHelper.scala    From dependency   with MIT License 5 votes vote down vote up
package controllers.helpers

import javax.inject.{Inject, Singleton}

import db.{Authorization, LibrariesDao}
import io.flow.common.v0.models.UserReference
import io.flow.dependency.v0.models.Library
import play.api.mvc.{Result, Results}

@Singleton
class LibrariesHelper @Inject()(
  librariesDao: LibrariesDao
) {

  def withLibrary(user: UserReference, id: String)(
    f: Library => Result
  ): Result = {
    librariesDao.findById(Authorization.User(user.id), id) match {
      case None => {
        Results.NotFound
      }
      case Some(library) => {
        f(library)
      }
    }
  }


} 
Example 37
Source File: UsersHelper.scala    From dependency   with MIT License 5 votes vote down vote up
package controllers.helpers

import javax.inject.{Inject, Singleton}

import db.UsersDao
import io.flow.common.v0.models.User
import play.api.mvc.{Result, Results}

@Singleton
class UsersHelper @Inject()(
  usersDao: UsersDao
) {

  def withUser(id: String)(
    f: User => Result
  ) = {
    usersDao.findById(id) match {
      case None => {
        Results.NotFound
      }
      case Some(user) => {
        f(user)
      }
    }
  }

} 
Example 38
Source File: ProjectHelper.scala    From dependency   with MIT License 5 votes vote down vote up
package controllers.helpers

import javax.inject.{Inject, Singleton}

import db.{Authorization, ProjectsDao}
import io.flow.common.v0.models.UserReference
import io.flow.dependency.v0.models.Project
import play.api.mvc.{Result, Results}

@Singleton
class ProjectHelper @Inject()(
  projectsDao: ProjectsDao
) {

  def withProject(user: UserReference, id: String)(
    f: Project => Result
  ): Result = {
    projectsDao.findById(Authorization.User(user.id), id) match {
      case None => {
        Results.NotFound
      }
      case Some(project) => {
        f(project)
      }
    }
  }


} 
Example 39
Source File: SecurityRule.scala    From play-zhewbacca   with MIT License 5 votes vote down vote up
package org.zalando.zhewbacca

import org.zalando.zhewbacca.TokenInfoConverter._
import play.api.Logger
import play.api.mvc.{RequestHeader, Result, Results}

import scala.concurrent.{ExecutionContext, Future}

trait SecurityRule {
  def isApplicableTo(requestHeader: RequestHeader): Boolean
  def execute(nextFilter: RequestHeader => Future[Result], requestHeader: RequestHeader)(implicit ec: ExecutionContext): Future[Result]
}

abstract class StrictRule(method: String, pathRegex: String) extends SecurityRule {

  private val RequestMatcherRegex = s"^$method $pathRegex$$".r

  def isApplicableTo(requestHeader: RequestHeader): Boolean =
    RequestMatcherRegex.pattern.matcher(s"${requestHeader.method} ${requestHeader.uri}").matches

}

case class ValidateTokenRule(
    authProvider: AuthProvider,
    method: String,
    pathRegex: String,
    scope: Scope) extends StrictRule(method, pathRegex) {

  private[this] val log = Logger(this.getClass)

  override def execute(nextFilter: RequestHeader => Future[Result], requestHeader: RequestHeader)(implicit ec: ExecutionContext): Future[Result] =
    RequestValidator.validate(scope, requestHeader, authProvider).flatMap[Result] {
      case Right(tokenInfo) =>
        log.info(s"Request #${requestHeader.id} authenticated as: ${tokenInfo.userUid}")
        nextFilter(requestHeader.withTokenInfo(tokenInfo))

      case Left(result) =>
        log.info(s"Request #${requestHeader.id} failed auth")
        Future.successful(result)
    }
}


case object DenyAllRule extends DenySecurityRule {
  override def isApplicableTo(requestHeader: RequestHeader): Boolean = true
}

trait DenySecurityRule extends SecurityRule {
  override def execute(nextFilter: RequestHeader => Future[Result], requestHeader: RequestHeader)(implicit ec: ExecutionContext): Future[Result] =
    Future.successful(Results.Forbidden)
} 
Example 40
Source File: BasicAuthentication.scala    From endpoints4s   with MIT License 5 votes vote down vote up
package endpoints4s.play.server

import java.util.Base64

import endpoints4s.algebra.BasicAuthentication.Credentials
import endpoints4s.algebra.Documentation
import endpoints4s.{Tupler, Valid, algebra}
import play.api.http.HeaderNames
import play.api.http.HeaderNames.AUTHORIZATION
import play.api.libs.streams.Accumulator
import play.api.mvc.{BodyParser, Results}

 )) =>
        _ =>
          Some(
            BodyParser(_ =>
              Accumulator.done(
                Left(
                  Results.Unauthorized.withHeaders(
                    HeaderNames.WWW_AUTHENTICATE -> "Basic realm=Realm"
                  )
                )
              )
            )
          )
      case (u, (h, Some(credentials))) =>
        headers =>
          entity(headers).map(
            _.map(e => tuplerUEHC(tuplerUE(u, e), tuplerHC(h, credentials)))
          )
    } { out =>
      val (ue, hc) = tuplerUEHC.unapply(out)
      val (u, _) = tuplerUE.unapply(ue)
      val (h, c) = tuplerHC.unapply(hc)
      (u, (h, Some(c)))
    }
  }

} 
Example 41
Source File: writeableHelper.scala    From play-swagger   with MIT License 5 votes vote down vote up
package de.zalando.play.controllers

import play.api.http.Writeable
import play.api.mvc.{AnyContentAsMultipartFormData, RequestHeader}
import scala.language.implicitConversions
import play.api.mvc.{RequestHeader, Result, Results}
import play.api.http._
import Results.{Status, Redirect}

case class WriteableWrapper[T](w: Writeable[T], m: Manifest[T])

object WriteableWrapper {
  implicit def writeable2wrapper[T](w: Writeable[T])(implicit m: Manifest[T]) =
    WriteableWrapper(w, m)
  implicit val anyContentAsMultipartFormWritable: Writeable[AnyContentAsMultipartFormData] = {
    MultipartFormDataWritable.singleton.map(_.mdf)
  }
}


object ResponseWriters extends ResponseWritersBase

trait ResponseWritersBase {

  type ContentType = String

  def custom: Seq[WriteableWrapper[_]] = Seq.empty

  case class choose[T](mimeType: ContentType) {
    def apply[R <: Any](registry: Seq[WriteableWrapper[_]] = custom)(implicit m: Manifest[R]): Option[Writeable[R]] =
      registry filter {
        _.w.contentType.exists(_ == mimeType)
      } find { p =>
        m.runtimeClass.isAssignableFrom(p.m.runtimeClass)
      } map  {
        _.asInstanceOf[WriteableWrapper[R]]
      } map(_.w)
  }

}

object WrappedBodyParsers extends WrappedBodyParsersBase

trait WrappedBodyParsersBase {
  implicit def parser2parserWrapper[T](p: Parser[T])(implicit m: Manifest[T]): ParserWrapper[T] = ParserWrapper(p, m)
  type Parser[T] = (RequestHeader, Array[Byte]) => T
  case class ParserWrapper[T](p: Parser[T], m: Manifest[T])
  val custom: Seq[(String, ParserWrapper[_])] = Seq.empty
  def anyParser[T](implicit manifest: Manifest[T]): Seq[(String, Parser[T])] =
    custom.filter(_._2.m.runtimeClass.isAssignableFrom(manifest.runtimeClass)).map { e =>
      e.copy(_2 = e._2.asInstanceOf[ParserWrapper[T]].p) }
  def optionParser[T](implicit manifest: Manifest[T]): Seq[(String, Parser[Option[T]])] = anyParser[Option[T]]
}

trait ResultWrapper[ResultT] {
  def statusCode: Int
  def result: ResultT
  def writer: String => Option[Writeable[ResultT]]
  def toResult(mimeType: String): Option[play.api.mvc.Result] =
    if (statusCode / 100 == 3)
      Option(Redirect(result.toString, statusCode))
    else
      writer(mimeType).map(Status(statusCode)(result)(_))
} 
Example 42
Source File: string_formats_yaml.base.scala    From play-swagger   with MIT License 5 votes vote down vote up
package string_formats.yaml

import scala.language.existentials

import play.api.mvc.{Action, Controller, Results}
import play.api.http._
import Results.Status

import de.zalando.play.controllers.{PlayBodyParsing, ParsingError, ResultWrapper}
import PlayBodyParsing._
import scala.util._
import de.zalando.play.controllers.Base64String
import Base64String._
import de.zalando.play.controllers.BinaryString
import BinaryString._
import org.joda.time.DateTime
import java.util.UUID
import org.joda.time.LocalDate

import de.zalando.play.controllers.PlayPathBindables





trait String_formatsYamlBase extends Controller with PlayBodyParsing {
    sealed trait GetType[T] extends ResultWrapper[T]
    
    case object Get200 extends EmptyReturn(200)
    

    private type getActionRequestType       = (GetDate_time, GetDate, GetBase64, GetUuid, BinaryString)
    private type getActionType[T]            = getActionRequestType => GetType[T] forSome { type T }

        private def getParser(acceptedTypes: Seq[String], maxLength: Int = parse.DefaultMaxTextLength) = {
            def bodyMimeType: Option[MediaType] => String = mediaType => {
                val requestType = mediaType.toSeq.map {
                    case m: MediaRange => m
                    case MediaType(a,b,c) => new MediaRange(a,b,c,None,Nil)
                }
                negotiateContent(requestType, acceptedTypes).orElse(acceptedTypes.headOption).getOrElse("application/json")
            }
            
            import de.zalando.play.controllers.WrappedBodyParsers
            
            val customParsers = WrappedBodyParsers.anyParser[BinaryString]
            anyParser[BinaryString](bodyMimeType, customParsers, "Invalid BinaryString", maxLength)
        }

    val getActionConstructor  = Action
    def getAction[T] = (f: getActionType[T]) => (date_time: GetDate_time, date: GetDate, base64: GetBase64, uuid: GetUuid) => getActionConstructor(getParser(Seq[String]())) { request =>
        val providedTypes = Seq[String]("application/json", "application/yaml")

        negotiateContent(request.acceptedTypes, providedTypes).map { getResponseMimeType =>

            val petId = request.body
            
            

                val result =
                        new GetValidator(date_time, date, base64, uuid, petId).errors match {
                            case e if e.isEmpty => processValidgetRequest(f)((date_time, date, base64, uuid, petId))(getResponseMimeType)
                            case l =>
                                implicit val marshaller: Writeable[Seq[ParsingError]] = parsingErrors2Writable(getResponseMimeType)
                                BadRequest(l)
                        }
                result
            
        }.getOrElse(Status(406)("The server doesn't support any of the requested mime types"))
    }

    private def processValidgetRequest[T](f: getActionType[T])(request: getActionRequestType)(mimeType: String) = {
      f(request).toResult(mimeType).getOrElse {
        Results.NotAcceptable
      }
    }
    abstract class EmptyReturn(override val statusCode: Int = 204) extends ResultWrapper[Results.EmptyContent]  with GetType[Results.EmptyContent] { val result = Results.EmptyContent(); val writer = (x: String) => Some(new DefaultWriteables{}.writeableOf_EmptyContent); override def toResult(mimeType: String): Option[play.api.mvc.Result] = Some(Results.NoContent) }
    case object NotImplementedYet extends ResultWrapper[Results.EmptyContent]  with GetType[Results.EmptyContent] { val statusCode = 501; val result = Results.EmptyContent(); val writer = (x: String) => Some(new DefaultWriteables{}.writeableOf_EmptyContent); override def toResult(mimeType: String): Option[play.api.mvc.Result] = Some(Results.NotImplemented) }
} 
Example 43
Source File: ApiV1Router.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.routes

import javax.inject.Inject

import com.google.inject.Provider
import de.frosner.broccoli.controllers._
import play.api.mvc.{Action, Results}
import play.api.routing.Router.Routes
import play.api.routing.SimpleRouter
import play.api.routing.sird._


class ApiV1Router @Inject()(
    templates: Provider[TemplateController],
    instances: Provider[InstanceController],
    about: Provider[AboutController],
    status: Provider[StatusController],
    security: Provider[SecurityController]
) extends SimpleRouter {
  override def routes: Routes = {
    // Templates
    case GET(p"/templates")     => templates.get.list
    case GET(p"/templates/$id") => templates.get.show(id)
    // Instances
    case GET(p"/instances" ? q_o"templateId=$id") => instances.get.list(id)
    case GET(p"/instances/$id")                   => instances.get.show(id)
    case POST(p"/instances")                      => instances.get.create
    case POST(p"/instances/$id")                  => instances.get.update(id)
    case DELETE(p"/instances/$id")                => instances.get.delete(id)
    case GET(p"/instances/$id/tasks")             => instances.get.tasks(id)
    // About & status
    case GET(p"/about")  => about.get.about
    case GET(p"/status") => status.get.status
    // Authentication
    case POST(p"/auth/login")  => security.get.login
    case POST(p"/auth/logout") => security.get.logout
    case GET(p"/auth/verify")  => security.get.verify
    // Do not fall back to other routes for API requests, but return 404 directly
    case _ => Action(Results.NotFound)
  }
} 
Example 44
Source File: DownloadsRouter.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.routes

import javax.inject.{Inject, Provider}

import de.frosner.broccoli.controllers.InstanceController
import de.frosner.broccoli.routes.Extractors._
import play.api.mvc.{Action, Results}
import play.api.routing.Router.Routes
import play.api.routing.SimpleRouter
import play.api.routing.sird._
import play.api.http.ContentTypes._

class DownloadsRouter @Inject()(instances: Provider[InstanceController]) extends SimpleRouter {

  override def routes: Routes = {
    case GET(
        p"/instances/$instanceId/allocations/$allocationId/tasks/$taskName/logs/${logKind(kind)}" ? q_o"offset=${information(offset)}") =>
      instances.get.logFile(instanceId, allocationId, taskName, kind, offset)
    case GET(
        p"/instances/$instanceId/periodic/$periodicJobPrefix/$periodicJobSuffix/allocations/$allocationId/tasks/$taskName/logs/${logKind(
          kind)}" ? q_o"offset=${information(offset)}") =>
      val periodicJobId = s"$periodicJobPrefix/$periodicJobSuffix"
      instances.get.logFile(instanceId, periodicJobId, allocationId, taskName, kind, offset)
    case _ => Action(Results.NotFound(<h1>Download not found</h1>).as(HTML))
  }
}