play.api.mvc.Result Scala Examples

The following examples show how to use play.api.mvc.Result. 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: SessionAuditor.scala    From pertax-frontend   with Apache License 2.0 6 votes vote down vote up
package controllers.auth

import com.google.inject.Inject
import controllers.auth.SessionAuditor._
import controllers.auth.requests.AuthenticatedRequest
import play.api.Logger
import play.api.libs.json.{Format, Json}
import play.api.mvc.Result
import uk.gov.hmrc.auth.core.retrieve.Credentials
import uk.gov.hmrc.auth.core.{ConfidenceLevel, Enrolment}
import uk.gov.hmrc.domain.{Nino, SaUtr}
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.play.audit.http.connector.AuditConnector
import uk.gov.hmrc.play.audit.http.connector.AuditResult.{Failure, Success}
import uk.gov.hmrc.play.audit.model.ExtendedDataEvent
import util.AuditServiceTools

import scala.concurrent.{ExecutionContext, Future}

private[auth] class SessionAuditor @Inject()(auditConnector: AuditConnector)(implicit ec: ExecutionContext)
    extends AuditTags {

  val logger = Logger(this.getClass)

  def auditOnce[A](request: AuthenticatedRequest[A], result: Result)(implicit hc: HeaderCarrier): Future[Result] =
    request.session.get(sessionKey) match {
      case None =>
        logger.info(request.profile.toString)

        val eventDetail = UserSessionAuditEvent(request)

        val sendAuditEvent = auditConnector
          .sendExtendedEvent(
            ExtendedDataEvent(
              auditSource = AuditServiceTools.auditSource,
              auditType = auditType,
              detail = Json.toJson(eventDetail),
              tags = buildTags(request))
          )
          .recover {
            case e: Exception =>
              Logger.warn(s"Unable to audit: ${e.getMessage}")
              Failure("UserSessionAuditor.auditOncePerSession exception occurred whilst auditing", Some(e))
          }

        sendAuditEvent.map {
          case Success => result.addingToSession(sessionKey -> "true")(request)
          case _       => result
        }

      case _ => Future.successful(result)
    }
}

object SessionAuditor {

  val sessionKey = "sessionAudited"
  val auditType = "user-session-visit"

  case class UserSessionAuditEvent(
    nino: Option[Nino],
    credentials: Credentials,
    confidenceLevel: ConfidenceLevel,
    name: Option[String],
    saUtr: Option[SaUtr],
    allEnrolments: Set[Enrolment])

  object UserSessionAuditEvent {

    def apply[A](request: AuthenticatedRequest[A]): UserSessionAuditEvent = {
      val nino = request.nino
      val credentials = request.credentials
      val confidenceLevel = request.confidenceLevel
      val name = request.name map (_.toString)
      val saUtr = request.saEnrolment map (_.saUtr)
      val enrolments = request.enrolments

      UserSessionAuditEvent(nino, credentials, confidenceLevel, name, saUtr, enrolments)
    }

    implicit val credentialsFormats = Json.format[Credentials]
    implicit val formats: Format[UserSessionAuditEvent] = Json.format[UserSessionAuditEvent]
  }

} 
Example 2
Source File: PersonalDetailsControllerSpec.scala    From pertax-frontend   with Apache License 2.0 6 votes vote down vote up
package controllers.address

import config.ConfigDecorator
import controllers.auth.requests.UserRequest
import controllers.auth.{AuthJourney, WithActiveTabAction}
import controllers.controllershelpers.{AddressJourneyCachingHelper, PersonalDetailsCardGenerator}
import models.AddressJourneyTTLModel
import models.dto.AddressPageVisitedDto
import org.mockito.ArgumentCaptor
import org.mockito.Mockito.{times, verify, when}
import org.mockito.Matchers.{eq => meq, _}
import org.scalatestplus.mockito.MockitoSugar
import play.api.http.Status.OK
import play.api.libs.json.Json
import play.api.mvc.{MessagesControllerComponents, Request, Result}
import play.api.test.FakeRequest
import repositories.EditAddressLockRepository
import services.{LocalSessionCache, NinoDisplayService}
import uk.gov.hmrc.http.cache.client.CacheMap
import uk.gov.hmrc.play.audit.http.connector.{AuditConnector, AuditResult}
import uk.gov.hmrc.play.audit.model.DataEvent
import uk.gov.hmrc.renderer.TemplateRenderer
import util.UserRequestFixture.buildUserRequest
import util.{ActionBuilderFixture, BaseSpec, Fixtures, LocalPartialRetriever}
import views.html.interstitial.DisplayAddressInterstitialView
import views.html.personaldetails.{AddressAlreadyUpdatedView, CannotUseServiceView, PersonalDetailsView}

import scala.concurrent.{ExecutionContext, Future}

class PersonalDetailsControllerSpec extends AddressBaseSpec {

  val ninoDisplayService = mock[NinoDisplayService]

  trait LocalSetup extends AddressControllerSetup {

    when(ninoDisplayService.getNino(any(), any())).thenReturn {
      Future.successful(Some(Fixtures.fakeNino))
    }

    def currentRequest[A]: Request[A] = FakeRequest().asInstanceOf[Request[A]]

    def controller =
      new PersonalDetailsController(
        injected[PersonalDetailsCardGenerator],
        mockEditAddressLockRepository,
        ninoDisplayService,
        mockAuthJourney,
        addressJourneyCachingHelper,
        withActiveTabAction,
        mockAuditConnector,
        cc,
        displayAddressInterstitialView,
        injected[PersonalDetailsView]
      ) {}

    "Calling AddressController.onPageLoad" should {

      "call citizenDetailsService.fakePersonDetails and return 200" in new LocalSetup {
        override def sessionCacheResponse: Option[CacheMap] =
          Some(CacheMap("id", Map("addressPageVisitedDto" -> Json.toJson(AddressPageVisitedDto(true)))))

        val result = controller.onPageLoad()(FakeRequest())

        status(result) shouldBe OK
        verify(mockLocalSessionCache, times(1))
          .cache(meq("addressPageVisitedDto"), meq(AddressPageVisitedDto(true)))(any(), any(), any())
        verify(mockEditAddressLockRepository, times(1)).get(any())
      }

      "send an audit event when user arrives on personal details page" in new LocalSetup {
        override def sessionCacheResponse: Option[CacheMap] =
          Some(CacheMap("id", Map("addressPageVisitedDto" -> Json.toJson(AddressPageVisitedDto(true)))))

        val result = controller.onPageLoad()(FakeRequest())
        val eventCaptor = ArgumentCaptor.forClass(classOf[DataEvent])

        status(result) shouldBe OK
        verify(mockAuditConnector, times(1)).sendEvent(eventCaptor.capture())(any(), any())
      }
    }
  }
} 
Example 3
Source File: AddFormatParameterIfOnlyAcceptHeaderProvidedFilter.scala    From CM-Well   with Apache License 2.0 5 votes vote down vote up
package filters

import akka.stream.Materializer
import com.typesafe.scalalogging.LazyLogging
import javax.inject._
import play.api.http.MediaType
import play.api.mvc.{Filter, RequestHeader, Result}

import scala.concurrent.Future

class AddFormatParameterIfOnlyAcceptHeaderProvidedFilter @Inject()(implicit val mat: Materializer) extends Filter {
  //MediaType2Format
  private[this] val mt2f: PartialFunction[String, PartialFunction[String, String]] = (mt: String) =>
    mt match {
      case "text" => {
        case "yaml"       => "yaml"
        case "json"       => "json"
        case "rdf+n3"     => "n3"
        case "n3"         => "n3"
        case "plain"      => "ntriples"
        case "ntriples"   => "ntriples"
        case "turtle"     => "ttl"
        case "ttl"        => "ttl"
        case "rdf+turtle" => "ttl"
        case "rdf+ttl"    => "ttl"
        case "n-quads"    => "nquads"
      }
      case "application" => {
        case "json"     => "jsonl"
        case "ld+json"  => "jsonld"
        case "rdf+xml"  => "rdfxml"
        case "x-nquads" => "nquads"
      }
      //    case "xml" => {
      //      case "rdf" => "rdfxml"
      //    }
  }

  private def formatToValidType(mt: MediaType): String = mt2f(mt.mediaType)(mt.mediaSubType)

  private def isCMWellAccepted(mt: MediaType): Boolean =
    mt2f.isDefinedAt(mt.mediaType) && mt2f(mt.mediaType).isDefinedAt(mt.mediaSubType)

  override def apply(next: (RequestHeader) => Future[Result])(request: RequestHeader): Future[Result] = {
    val withFormat =
      if ((request.getQueryString("format").isDefined || request.acceptedTypes.isEmpty) && Set("post", "get")(
            request.method.toLowerCase
          )) request
      else
        request.acceptedTypes.find(isCMWellAccepted(_)) match {
          case Some(mt) =>
            val newTarget = request.target.withQueryString(request.target.queryMap + ("format" -> Seq(formatToValidType(mt))))
            request.withTarget(newTarget)
          case None     => request
        }
    next(withFormat)
  }
} 
Example 4
Source File: VinylDnsAction.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package actions

import cats.effect.IO
import controllers.{OidcAuthenticator, VinylDNS}
import org.slf4j.Logger
import play.api.mvc.{ActionFunction, Request, Result, Session}
import vinyldns.core.domain.membership.{LockStatus, User}

import scala.concurrent.{ExecutionContext, Future}

trait VinylDnsAction extends ActionFunction[Request, UserRequest] {

  val userLookup: String => IO[Option[User]]
  val oidcAuthenticator: OidcAuthenticator
  val oidcEnabled: Boolean = oidcAuthenticator.oidcEnabled

  val logger: Logger

  implicit val executionContext: ExecutionContext

  def notLoggedInResult: Future[Result]

  def cantFindAccountResult(un: String): Future[Result]

  def lockedUserResult(un: String): Future[Result]

  def getValidUsernameLdap(session: Session): Option[String] =
    session.get("username")

  def getValidUsernameOidc(session: Session): Option[String] =
    session.get(VinylDNS.ID_TOKEN).flatMap {
      oidcAuthenticator.getValidUsernameFromToken
    }

  def invokeBlock[A](
      request: Request[A],
      block: UserRequest[A] => Future[Result]
  ): Future[Result] = {
    // if the user name is not in session, or token is invalid reject
    val userName = if (oidcEnabled) {
      getValidUsernameOidc(request.session)
    } else {
      getValidUsernameLdap(request.session)
    }

    userName match {
      case None =>
        logger.info("User is not logged in or token expired; redirecting to login screen")
        notLoggedInResult

      case Some(un) =>
        // user name in session, let's get it from the repo
        userLookup(un).unsafeToFuture().flatMap {
          // Odd case, but let's handle with a different error message
          case None =>
            logger.error(s"Cant find account for user with username $un")
            cantFindAccountResult(un)

          case Some(user) if user.lockStatus == LockStatus.Locked =>
            logger.info(s"User ${user.userName}'s account is locked; redirecting to lock screen")
            lockedUserResult(un)

          case Some(user) =>
            logger.debug(s"User ${user.userName}'s is logged in")
            block(new UserRequest(un, user, request))
        }
    }
  }
} 
Example 5
Source File: FrontendAction.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package actions

import cats.effect.IO
import controllers.{CacheHeader, OidcAuthenticator, VinylDNS}
import org.slf4j.LoggerFactory
import play.api.mvc.Results.Redirect
import play.api.mvc.{AnyContent, BodyParser, Result}
import vinyldns.core.domain.membership.User

import scala.concurrent.{ExecutionContext, Future}


class LegacyFrontendAction(
    val userLookup: String => IO[Option[User]],
    val oidcAuthenticator: OidcAuthenticator,
    val parser: BodyParser[AnyContent]
) extends VinylDnsAction
    with FrontendActionBuilder
    with CacheHeader {

  override val logger = LoggerFactory.getLogger(classOf[LegacyFrontendAction])
  implicit val executionContext: ExecutionContext = scala.concurrent.ExecutionContext.global

  def notLoggedInResult: Future[Result] =
    Future.successful(
      Redirect("/login")
        .flashing(VinylDNS.Alerts.error("You are not logged in. Please login to continue."))
        .withNewSession
        .withHeaders(cacheHeaders: _*)
    )

  def cantFindAccountResult(un: String): Future[Result] =
    Future.successful(
      Redirect("/login")
        .flashing(VinylDNS.Alerts.error(s"Unable to find user account for user name '$un'"))
        .withNewSession
        .withHeaders(cacheHeaders: _*)
    )

  def lockedUserResult(un: String): Future[Result] =
    Future.successful(
      Redirect("/noaccess").withNewSession
        .withHeaders(cacheHeaders: _*)
    )
} 
Example 6
Source File: ErrorHandler.scala    From DataQuality   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package org.openapitools

import play.api.http.DefaultHttpErrorHandler
import play.api.libs.json.JsResultException
import play.api.mvc.Results._
import play.api.mvc.{RequestHeader, Result}

import scala.concurrent.Future

class ErrorHandler extends DefaultHttpErrorHandler {
  override def onServerError(request: RequestHeader, e: Throwable): Future[Result] = e match {
    case _: OpenApiExceptions.MissingRequiredParameterException =>
      Future.successful(BadRequest(e.getMessage))
    case _: JsResultException =>
      Future.successful(BadRequest(e.getMessage))
    case _ =>
      // Handles dev mode properly, or otherwise returns internal server error in production mode
      super.onServerError(request, e)
  }
} 
Example 7
Source File: ExtendedController.scala    From bay-scalajs.g8   with Apache License 2.0 5 votes vote down vote up
package controllers

import cats.data.EitherT
import play.api.data.Form
import play.api.mvc.Controller
import play.api.mvc.Request
import play.api.mvc.Result
import shared.utils.Codecs
import shared.utils.Implicits
import cats.syntax.either._
import play.api.i18n.MessagesApi
import services.Services

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


trait ExtendedController extends Controller with Implicits with Codecs {
  val services: Services
  implicit val ec: ExecutionContext

  type HttpResult[A] = EitherT[Future, Result, A]

  // Constructors for our result type
  object HttpResult {

    def point[A](a: A): HttpResult[A] =
      EitherT[Future, Result, A](Future.successful(Right(a)))

    def fromFuture[A](fa: Future[A]): HttpResult[A] =
      EitherT[Future, Result, A](fa.map(Right(_)))

    def fromEither[A](va: Either[Result, A]): HttpResult[A] =
      EitherT[Future, Result, A](Future.successful(va))

    def fromEither[A, B](failure: B => Result)(va: Either[B, A]): HttpResult[A] =
      EitherT[Future, Result, A](Future.successful(va.leftMap(failure)))

    def fromOption[A](failure: Result)(oa: Option[A]): HttpResult[A] =
      EitherT[Future, Result, A](Future.successful(oa.toRight(failure)))

    def fromFOption[A](failure: Result)(foa: Future[Option[A]]): HttpResult[A] =
      EitherT[Future, Result, A](foa.map(_.toRight(failure)))

    def fromFEither[A, B](failure: B => Result)(fva: Future[Either[B, A]]): HttpResult[A] =
      EitherT[Future, Result, A](fva.map(_.leftMap(failure)))

    def fromForm[FormType](failure: Form[FormType] => Result)(form: Form[FormType])(
        implicit request: Request[_]): HttpResult[FormType] =
      EitherT[Future, Result, FormType](
        form.bindFromRequest.fold(errorForm => Left(failure(errorForm)).asFuture,
                                  formEntity => Right(formEntity).asFuture))
  }

  def constructResult(result: HttpResult[Result]): Future[Result] = result.value.map(_.merge)

  implicit class ExtResult(e: Result) {

    def pureResult: HttpResult[Result] =
      EitherT[Future, Result, Result](Future.successful(Right(e)))
  }

  implicit class EnrichedOps[T](t: T) {
    def |>[R](f: T => R): R = f(t)
  }

  def messagesApi: MessagesApi = services.messagesApi
} 
Example 8
Source File: AuthConfigImpl.scala    From bay-scalajs.g8   with Apache License 2.0 5 votes vote down vote up
package controllers

import jp.t2v.lab.play2.auth._
import play.api.mvc.RequestHeader
import play.api.mvc.Result
import services.Services
import services.dao.UserDao

import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import scala.reflect._

trait AuthConfigImpl extends AuthConfig with ExtendedController {

  val services: Services

  type Id        = Int
  type User      = shared.models.slick.default.User
  type Authority = User => Future[Boolean]
  val idTag: ClassTag[Id]          = classTag[Id]
  val sessionTimeoutInSeconds: Int = 3600

  def resolveUser(id: Id)(implicit ctx: ExecutionContext): Future[Option[User]] =
    services.userDao.resolveUser(id)(ctx)

  def loginSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext): Future[Result] =
    Redirect(routes.Application.index("")).asFuture

  def logoutSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext): Future[Result] =
    Redirect(routes.Application.index("")).asFuture

  def authenticationFailed(request: RequestHeader)(
      implicit ctx: ExecutionContext): Future[Result] = Unauthorized.asFuture

  override def authorizationFailed(
      request: RequestHeader,
      user: User,
      authority: Option[Authority])(implicit context: ExecutionContext): Future[Result] =
    Unauthorized.asFuture

  def authorize(user: User, authority: Authority)(
      implicit ctx: ExecutionContext): Future[Boolean] = authority(user)

  // Define reusable authorities

  def isLoggedIn(user: User): Future[Boolean] = true.asFuture

  def isInGroup(groupName: String)(user: User): Future[Boolean] =
    services.userDao.isInGroup(user.id, groupName)
} 
Example 9
Source File: User.scala    From auth0-scala-samples   with MIT License 5 votes vote down vote up
package controllers

import javax.inject.Inject
import play.api.mvc.{Action, AnyContent, Controller, Request, Result}
import play.api.libs.json._
import play.api.cache._


class User @Inject() (cache: CacheApi) extends Controller {
  def AuthenticatedAction(f: Request[AnyContent] => Result): Action[AnyContent] = {
    Action { request =>
      (request.session.get("id").flatMap { id =>
        cache.get[JsValue](id + "profile")
      } map { profile =>
        f(request)
      }).orElse {
        Some(Redirect(routes.Application.index()))
      }.get
    }
  }
  
  def index: Action[AnyContent] = AuthenticatedAction { request =>
    val id = request.session.get("id").get
    val profile = cache.get[JsValue](id + "profile").get
    Ok(views.html.user(profile))
  }
} 
Example 10
Source File: BaseController.scala    From play-silhouette-postgres-async-seed   with Apache License 2.0 5 votes vote down vote up
package controllers

import java.util.UUID

import org.joda.time.LocalDateTime
import play.api.i18n.I18nSupport
import services.user.AuthenticationEnvironment
import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.impl.authenticators.CookieAuthenticator
import models.user.{ Role, User }
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.mvc.{ AnyContent, Result }

import scala.concurrent.Future

abstract class BaseController() extends Silhouette[User, CookieAuthenticator] with I18nSupport {
  def env: AuthenticationEnvironment

  def withAdminSession(block: (SecuredRequest[AnyContent]) => Future[Result]) = SecuredAction.async { implicit request =>
    if (request.identity.roles.contains(Role.Admin)) {
      block(request)
    } else {
      Future.successful(NotFound("404 Not Found"))
    }
  }

  def withSession(block: (SecuredRequest[AnyContent]) => Future[Result]) = UserAwareAction.async { implicit request =>
    val response = request.identity match {
      case Some(user) =>
        val secured = SecuredRequest(user, request.authenticator.getOrElse(throw new IllegalStateException()), request)
        block(secured).map { r =>
          r
        }
      case None =>
        val user = User(
          id = UUID.randomUUID(),
          username = None,
          profiles = Nil,
          created = new LocalDateTime()
        )

        for {
          user <- env.userService.save(user)
          authenticator <- env.authenticatorService.create(LoginInfo("anonymous", user.id.toString))
          value <- env.authenticatorService.init(authenticator)
          result <- block(SecuredRequest(user, authenticator, request))
          authedResponse <- env.authenticatorService.embed(value, result)
        } yield {
          env.eventBus.publish(SignUpEvent(user, request, request2Messages))
          env.eventBus.publish(LoginEvent(user, request, request2Messages))
          authedResponse
        }
    }
    response
  }
} 
Example 11
Source File: AddCharsetIfNotExistFilter.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 controllers.XCmWellType
import play.api.http.HeaderNames
import play.api.mvc.{Filter, Headers, RequestHeader, Result}
import scala.concurrent.Future

class AddCharsetIfNotExistFilter @Inject()(implicit override val mat: Materializer) extends Filter {
  def apply(next: (RequestHeader) => Future[Result])(request: RequestHeader): Future[Result] = request match {
    case XCmWellType.File()             => next(request)
    case _ if request.charset.isDefined => next(request)
    case _ => {
      val charset = request.charset.getOrElse("UTF-8")
      val contentType = request.contentType.getOrElse("text/plain")

      val headers = request.headers.headers.filterNot(_._1 == HeaderNames.CONTENT_TYPE) ++ Seq(
        HeaderNames.CONTENT_TYPE -> s"$contentType;charset=$charset"
      )
      val modifiedRequestHeader = request.withHeaders(Headers(headers: _*))

      next(modifiedRequestHeader)
    }
  }
} 
Example 12
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 13
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 14
Source File: AccessLoggingFilter.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package filters

import akka.stream.Materializer
import javax.inject.Inject
import org.slf4j.LoggerFactory
import play.api.mvc.{Filter, RequestHeader, Result}
import play.mvc.Http

import scala.concurrent.{ExecutionContext, Future}

class AccessLoggingFilter @Inject() (
    implicit val mat: Materializer,
    executionContext: ExecutionContext
) extends Filter {

  private val logger = LoggerFactory.getLogger(classOf[AccessLoggingFilter])

  def apply(next: RequestHeader => Future[Result])(request: RequestHeader): Future[Result] = {
    val resultFuture = next(request)

    resultFuture.foreach(result => {
      if (!request.uri.contains("/public") && !request.uri.contains("/assets")) {
        val msg = s"Request: method=${request.method}, path=${request.uri}, " +
          s"remote_address=${request.remoteAddress}, " +
          s"user_agent=${request.headers.get(Http.HeaderNames.USER_AGENT).getOrElse("unknown")} " +
          s"| Response: status_code=${result.header.status} "
        logger.info(msg)
      }
    })

    resultFuture
  }
} 
Example 15
Source File: LoggingFilter.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.utils

import javax.inject.{ Inject, Singleton }
import akka.stream.Materializer
import com.nimbusds.jose.JWSObject
import com.nimbusds.jwt.JWTClaimsSet
import play.api.http.HttpErrorHandler
import play.api.mvc.{ Filter, RequestHeader, Result }
import play.api.{ Configuration, Logger }

import scala.concurrent.{ ExecutionContext, Future }
import scala.util.Try

@Singleton
class ActiveHatCounter() {
  // Careful! Mutable state
  private var count: Long = 0

  def get(): Long = count
  def increase(): Unit = this.synchronized(count += 1)
  def decrease(): Unit = this.synchronized(count -= 1)
}

class LoggingFilter @Inject() (
    errorHandler: HttpErrorHandler,
    configuration: Configuration,
    hatCounter: ActiveHatCounter)(
    implicit
    ec: ExecutionContext,
    val mat: Materializer) extends Filter {
  private val logger = Logger("api")

  def apply(nextFilter: RequestHeader => Future[Result])(requestHeader: RequestHeader): Future[Result] = {

    val startTime = System.currentTimeMillis

    nextFilter(requestHeader)
      .recoverWith({
        case e ⇒ errorHandler.onServerError(requestHeader, e)
      })
      .map { result =>
        val active = hatCounter.get()
        val requestTime = System.currentTimeMillis - startTime
        logger.info(s"[${requestHeader.remoteAddress}] [${requestHeader.method}:${requestHeader.host}:${requestHeader.uri}] " +
          s"[${result.header.status}] [$requestTime:ms] [hats:$active] ${tokenInfo(requestHeader)}")

        result.withHeaders("Request-Time" -> requestTime.toString)
      }
  }

  private val authTokenFieldName: String = configuration.get[String]("silhouette.authenticator.fieldName")
  private def tokenInfo(requestHeader: RequestHeader): String = {
    requestHeader.queryString.get(authTokenFieldName).flatMap(_.headOption)
      .orElse(requestHeader.headers.get(authTokenFieldName))
      .flatMap(t ⇒ if (t.isEmpty) { None } else { Some(t) })
      .flatMap(t ⇒ Try(JWSObject.parse(t)).toOption)
      .map(o ⇒ JWTClaimsSet.parse(o.getPayload.toJSONObject))
      .map { claimSet =>
        s"[${Option(claimSet.getStringClaim("application")).getOrElse("api")}@" +
          s"${Option(claimSet.getStringClaim("applicationVersion")).getOrElse("_")}]"
      }
      .getOrElse("[unauthenticated@_]")
  }
} 
Example 16
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 17
Source File: AuthUtils.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.controllers

import de.frosner.broccoli.auth.{Account, Role}
import de.frosner.broccoli.services.SecurityService
import jp.t2v.lab.play2.auth.test.Helpers._
import org.mockito.Mockito._
import org.specs2.matcher.MatchResult
import org.specs2.matcher.MatchersImplicits._
import play.api.cache.CacheApi
import play.api.mvc.{Action, AnyContentAsEmpty, Result}
import play.api.test.Helpers._
import play.api.test._
import play.api.{Application, Environment}

import scala.concurrent.Future

trait AuthUtils extends ServiceMocks {

  def playEnv(implicit app: Application): Environment = app.injector.instanceOf[Environment]

  def cacheApi(implicit app: Application): CacheApi = app.injector.instanceOf[CacheApi]

  def testWithAllAuths[T <: AuthConfigImpl, B](account: Account)(controller: SecurityService => T)(
      action: T => Action[B])(requestModifier: FakeRequest[AnyContentAsEmpty.type] => FakeRequest[B])(
      matcher: (T, Future[Result]) => MatchResult[_]): MatchResult[_] = {
    val confAuthController = controller(withAuthConf(mock[SecurityService], List(account)))
    val confAuthRequest = requestModifier(FakeRequest().withLoggedIn(confAuthController)(account.name))
    val confAuthResult = action(confAuthController).apply(confAuthRequest)
    val confAuthMatcher = matcher(confAuthController, confAuthResult)

    val noAuthController = controller(withAuthNone(mock[SecurityService]))
    val noAuthRequest = requestModifier(FakeRequest())
    val confAuthNoLoginResult = action(confAuthController).apply(noAuthRequest)
    val confAuthNoLoginMatcher = status(confAuthNoLoginResult) === 403

    confAuthMatcher and confAuthNoLoginMatcher
  }

  def testWithAllAuths[T <: AuthConfigImpl, B](controller: SecurityService => T)(action: T => Action[B])(
      requestModifier: FakeRequest[AnyContentAsEmpty.type] => FakeRequest[B])(
      matcher: (T, Future[Result]) => MatchResult[_]): MatchResult[_] = {
    val account = Account("user", ".*", Role.Administrator)
    val noAuthController = controller(withAuthNone(mock[SecurityService]))
    val noAuthRequest = requestModifier(FakeRequest())
    val noAuthResult = action(noAuthController).apply(noAuthRequest)
    val noAuthMatcher = matcher(noAuthController, noAuthResult)

    val authMatchers = testWithAllAuths(account)(controller)(action)(requestModifier)(matcher)

    noAuthMatcher and authMatchers
  }

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

import java.util.concurrent.TimeUnit

import de.frosner.broccoli.services.WebSocketService.Msg
import play.api.libs.iteratee.{Enumerator, Input, Iteratee}
import play.api.mvc.Result
import play.api.test.WithApplication

import scala.concurrent.{Await, Future}
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.ExecutionContext.Implicits.global

object WsTestUtil {

  private val waitTime = FiniteDuration(1, TimeUnit.SECONDS)

  case class Incoming(iteratee: Iteratee[Msg, _]) {

    def feed(message: Msg): Incoming =
      Incoming(Await.result(iteratee.feed(Input.El(message)), waitTime))

    def end: Incoming =
      Incoming(Await.result(iteratee.feed(Input.EOF), waitTime))

  }

  case class Outgoing(enum: Enumerator[Msg]) {
    private val messages = enum(Iteratee.fold(List[Msg]()) { (l, jsValue) =>
      jsValue :: l
    }).flatMap(_.run)

    def get: List[Msg] =
      Await.result(messages, waitTime)
  }

  def wrapConnection(connection: => Future[Either[Result, (Iteratee[Msg, _], Enumerator[Msg])]])
    : Either[Result, (Incoming, Outgoing)] = {
    val future = connection.map {
      _.right.map {
        case (iteratee, enumerator) => (Incoming(iteratee), Outgoing(enumerator))
      }
    }
    Await.result(future, waitTime)
  }

} 
Example 19
Source File: BroccoliSimpleAuthorization.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package jp.t2v.lab.play2.auth

import de.frosner.broccoli.auth.{Account, AuthMode}
import de.frosner.broccoli.conf
import de.frosner.broccoli.controllers.AuthConfigImpl
import de.frosner.broccoli.services.SecurityService
import jp.t2v.lab.play2.stackc.{RequestAttributeKey, RequestWithAttributes, StackableController}
import play.api.mvc.{Controller, RequestHeader, Result}

import scala.concurrent.Future

trait BroccoliSimpleAuthorization extends StackableController with AsyncAuth with AuthConfigImpl {

  self: Controller with AuthConfig =>

  val securityService: SecurityService

  private[auth] case object AuthKey extends RequestAttributeKey[User]

  override def proceed[A](req: RequestWithAttributes[A])(
      f: RequestWithAttributes[A] => Future[Result]): Future[Result] = {
    implicit val (r, ctx) = (req, StackActionExecutionContext(req))
    securityService.authMode match {
      case AuthMode.Conf => {
        restoreUser recover {
          case _ => None -> identity[Result] _
        } flatMap {
          case (Some(u), cookieUpdater) => super.proceed(req.set(AuthKey, u))(f).map(cookieUpdater)
          case (None, _)                => authenticationFailed(req)
        }
      }
      case AuthMode.None => {
        super.proceed(req)(f)
      }
    }
  }

  implicit def loggedIn(implicit req: RequestWithAttributes[_]): User = securityService.authMode match {
    case AuthMode.Conf => req.get(AuthKey).get
    case AuthMode.None => Account.anonymous
  }

  def getSessionId(request: RequestHeader): Option[AuthenticityToken] = extractToken(request)

} 
Example 20
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 21
Source File: GraphQlController.scala    From tap   with Apache License 2.0 5 votes vote down vote up
package controllers

import javax.inject.Inject
import models.GraphqlSchema
import models.graphql.GraphqlActions
import play.api.Logger
import play.api.libs.json.{JsObject, JsValue, Json}
import play.api.mvc.{Action, AnyContent, InjectedController, Result}
import sangria.ast.Document
import sangria.execution.{ErrorWithResolver, Executor, QueryAnalysisError}
import sangria.marshalling.playJson.{PlayJsonInputUnmarshallerJObject, PlayJsonResultMarshaller}
import sangria.parser.{QueryParser, SyntaxError}
import sangria.schema.Schema
import views.GraphiqlPage

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.{Failure, Success}


class GraphQlController @Inject() (assets: AssetsFinder, gqlSchema: GraphqlSchema, actions: GraphqlActions) extends InjectedController {

  val schema:Schema[GraphqlActions,Unit] = gqlSchema.create

  def graphiql:Action[AnyContent] = Action {
    request => Logger.info("Got Any content request from:" + request.remoteAddress)
    //Ok(views.html.graphiql(assets))
    Ok(GraphiqlPage.render("Explore TAP with GraphiQL"))
  }

  def graphql:Action[JsValue] = Action.async(parse.json) { request =>
    val query = (request.body \ "query").as[String]
    val operation = (request.body \ "operationName").asOpt[String]
    val variables = (request.body \ "variables").asOpt[JsObject].getOrElse(Json.obj())
    Logger.info(s"Query received from ${request.remoteAddress} >>> ${operation.getOrElse("No query")}")
    Logger.info(s"Variables: $variables")
    process(query,operation,variables)
  }

  def process(query:String,name:Option[String],variables:JsObject):Future[Result] = QueryParser.parse(query) match {
    case Success(queryAst) => executeGraphQLQuery(queryAst, name, variables)
    case Failure(error: SyntaxError) => Future.successful(BadRequest(error.getMessage))
    case _ => Future.successful(BadRequest("There was a problem with the request to TAP graphql."))
  }

  def executeGraphQLQuery(query: Document, name: Option[String], vars: JsObject):Future[Result] = {
     Executor.execute(schema, query, actions, operationName = name, variables = vars)
      .map(Ok(_))
      .recover {
        case error: QueryAnalysisError => BadRequest(error.resolveError)
        case error: ErrorWithResolver => InternalServerError(error.resolveError)
      }

  }
} 
Example 22
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 23
package commons.controllers

import commons.exceptions.ValidationException
import commons.models.ValidationResultWrapper
import play.api.libs.json.{JsError, Json, Reads}
import play.api.mvc.{AbstractController, BodyParser, ControllerComponents, Result}

import scala.concurrent.ExecutionContext

abstract class RealWorldAbstractController(controllerComponents: ControllerComponents)
  extends AbstractController(controllerComponents) {

  implicit protected val executionContext: ExecutionContext = defaultExecutionContext

  protected def validateJson[A: Reads]: BodyParser[A] = parse.json.validate(
    _.validate[A].asEither.left.map(e => BadRequest(JsError.toJson(e)))
  )

  protected def handleFailedValidation: PartialFunction[Throwable, Result] = {
    case e: ValidationException =>
      val errors = e.violations
        .groupBy(_.property)
        .view
        .mapValues(_.map(propertyViolation => propertyViolation.violation.message))
        .toMap

      val wrapper: ValidationResultWrapper = ValidationResultWrapper(errors)
      UnprocessableEntity(Json.toJson(wrapper))
  }

} 
Example 24
Source File: PropertyEopsObligationsResourceSpec.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package router.resources

import mocks.services.MockTaxCalcService
import play.api.mvc.Result
import play.api.test.FakeRequest
import router.errors.{ErrorCode, IncorrectAPIVersion, UnsupportedAPIVersion}
import support.ResourceSpec
import uk.gov.hmrc.http.HttpResponse

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class PropertyEopsObligationsResourceSpec extends ResourceSpec
  with MockTaxCalcService {

  class Setup {
    val resource = new TaxCalcResource(
      service = mockTaxCalcService,
      authConnector = mockAuthConnector,
      cc = controllerComponents
    )
    mockAuthAction
  }

  "get" should {
    "return a 200 with the response headers" when {
      "the service returns a HttpResponse containing a 200 with no json response body" in new Setup {
        MockTaxCalcService.get()
          .returns(Future.successful(Right(HttpResponse(OK, None, testHeaderResponse))))

        val result: Future[Result] = resource.get("","")(FakeRequest())
        status(result) shouldBe OK
        headers(result) shouldBe testHeader
        contentType(result) shouldBe None
      }
    }

    "return a 200 with a json response body and response headers" when {
      "the service returns a HttpResponse containing a 200 with a json response body" in new Setup {
        MockTaxCalcService.get()
          .returns(Future.successful(Right(HttpResponse(OK, Some(responseJson), testHeaderResponse))))

        val result: Future[Result] = resource.get("","")(FakeRequest())
        status(result) shouldBe OK
        headers(result) shouldBe testHeader
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe responseJson
      }
    }

    "return a 406 with a json response body representing the error" when {
      "the service returns an IncorrectAPIVersion response" in new Setup {
        MockTaxCalcService.get()
          .returns(Future.successful(Left(IncorrectAPIVersion)))

        val result: Future[Result] = resource.get("","")(FakeRequest())
        status(result) shouldBe NOT_ACCEPTABLE
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe ErrorCode.invalidAcceptHeader.asJson
      }
    }

    "return a 404 with a json response body representing the error" when {
      "the service returns an UnsupportedAPIVersion response" in new Setup {
        MockTaxCalcService.get()
          .returns(Future.successful(Left(UnsupportedAPIVersion)))

        val result: Future[Result] = resource.get("","")(FakeRequest())
        status(result) shouldBe NOT_FOUND
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe ErrorCode.notFound.asJson
      }
    }
  }

} 
Example 25
Source File: MetricsFilter.scala    From play-prometheus-filters   with MIT License 5 votes vote down vote up
package com.github.stijndehaes.playprometheusfilters.filters
import akka.stream.Materializer
import com.github.stijndehaes.playprometheusfilters.metrics.RequestMetric
import io.prometheus.client.Collector
import play.api.Configuration
import play.api.mvc.{Filter, RequestHeader, Result}

import scala.concurrent.{ExecutionContext, Future}


abstract class MetricsFilter(configuration: Configuration)(implicit val mat: Materializer, ec: ExecutionContext) extends Filter {

  val metrics: List[RequestMetric[_, RequestHeader, Result]]

  val excludePaths = {
    import collection.JavaConverters._
    Option(configuration.underlying)
      .map(_.getStringList("play-prometheus-filters.exclude.paths"))
      .map(_.asScala.toSet)
      .map(_.map(_.r))
      .getOrElse(Set.empty)
  }

  def apply(nextFilter: RequestHeader => Future[Result])
           (requestHeader: RequestHeader): Future[Result] = {

    // check if current uri is excluded from metrics
    def urlIsExcluded = excludePaths.exists(_.findFirstMatchIn(requestHeader.uri).isDefined)

    val startTime = System.nanoTime

    nextFilter(requestHeader).map { implicit result =>
      implicit val rh = requestHeader

      if (!urlIsExcluded) {
        val endTime = System.nanoTime
        val requestTime = (endTime - startTime) / Collector.NANOSECONDS_PER_SECOND

        metrics.foreach(_.mark(requestTime))
      }

      result
    }
  }
} 
Example 26
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 27
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 28
Source File: Tokens.scala    From cave   with MIT License 5 votes vote down vote up
package controllers

import controllers.helpers.CaveForms._
import controllers.helpers.{DeleteToken, CreateToken}
import play.api.Logger
import play.api.i18n.Messages
import play.api.mvc.{AnyContent, Request, Result}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class Tokens extends AbstractCaveController {
  def create = caveAsyncAction { implicit request =>
    createTokenForm.bindFromRequest().fold(handleFormError, handleCreateToken)
  }

  def delete = caveAsyncAction { implicit request =>
    deleteTokenForm.bindFromRequest().fold(handleFormError, handleDeleteToken)
  }

  private def handleDeleteToken(token: DeleteToken)(implicit request: Request[AnyContent]): Future[Result] = {
    token.teamName match {
      case Some(team) => deleteTeamToken(token, team)
      case _ => deleteOrganizationToken(token)
    }
  }

  private def handleCreateToken(token: CreateToken)(implicit request: Request[AnyContent]): Future[Result] = {
    token.teamName match {
      case Some(team) => createTeamToken(token, team)
      case _ => createOrganizationToken(token)
    }
  }

  private def deleteOrganizationToken(token: DeleteToken)
                                     (implicit request: Request[AnyContent]): Future[Result] = withCaveClient { client =>
    client.Tokens.deleteOrganizationsByOrganizationAndId(token.orgName, token.tokenId) map { result =>
      Logger.debug(s"Deleted organization token $token")
      Redirect(routes.Organizations.organization(token.orgName)).flashing("success" -> Messages("cave.tokens.delete.success"))
    }
  }

  private def createOrganizationToken(token: CreateToken)
                                     (implicit request: Request[AnyContent]): Future[Result] = withCaveClient { client =>
    client.Tokens.postOrganizationsByOrganization(token.orgName, token.description) map { result =>
      Logger.debug(s"Created new organization token $token")
      Redirect(routes.Organizations.organization(token.orgName)).flashing("success" -> Messages("cave.tokens.created.success"))
    }
  }

  private def deleteTeamToken(token: DeleteToken, team: String)
                             (implicit request: Request[AnyContent]): Future[Result] = withCaveClient { client =>
    client.Tokens.deleteOrganizationsAndTeamsByOrganizationAndTeamAndId(token.orgName, team, token.tokenId) map { result =>
      Logger.debug(s"Deleted team token $token")
      Redirect(routes.Teams.team(token.orgName, token.teamName.getOrElse(""))).flashing("success" -> Messages("cave.tokens.delete.success"))
    }
  }

  private def createTeamToken(token: CreateToken, team: String)
                             (implicit request: Request[AnyContent]): Future[Result] = withCaveClient { client =>
    client.Tokens.postOrganizationsAndTeamsByOrganizationAndTeam(token.orgName, team, token.description) map { result =>
      Logger.debug(s"Created new team token $token")
      Redirect(routes.Teams.team(token.orgName, token.teamName.getOrElse(""))).flashing("success" -> Messages("cave.tokens.created.success"))
    }
  }
} 
Example 29
Source File: RegisterProjectSteps.scala    From theGardener   with Apache License 2.0 5 votes vote down vote up
package steps

import java.nio.file._
import java.util

import cucumber.api.DataTable
import cucumber.api.scala._
import models._
import org.scalatestplus.mockito._
import play.api.libs.json.Json
import play.api.mvc.Result
import play.api.test.Helpers._
import play.api.test._
import resource._
import utils._

import scala.collection.JavaConverters._


class RegisterProjectSteps extends ScalaDsl with EN with MockitoSugar {

  import CommonSteps._

  def registerProject(project: Project): Result = {
    response = route(app, FakeRequest("POST", "/api/projects").withJsonBody(Json.toJson(project))).get
    await(response)
  }

  private def checkProjectsInDb(expectedProjects: Seq[Project]) = {
    val actualProjects = projectRepository.findAll().map(_.copy(hierarchy = None, branches = None))
    actualProjects mustBe expectedProjects
  }

  Given("""^the server "([^"]*)" host under the project "([^"]*)" on the branch "([^"]*)" the file "([^"]*)"$""") { (remoteRepository: String, project: String, branch: String, file: String, content: String) =>
    val projectRepositoryPath = s"$remoteRepository/$project".fixPathSeparator

    managed(initRemoteRepositoryIfNeeded(branch, projectRepositoryPath)).acquireAndGet { git =>

      addFile(git, projectRepositoryPath, file.fixPathSeparator, content)
    }
  }

  Given("""^the server "([^"]*)" host under the project "([^"]*)" on the branch "([^"]*)" the files$""") { (remoteRepository: String, project: String, branch: String, files: DataTable) =>
    val projectRepositoryPath = s"$remoteRepository/$project".fixPathSeparator

    managed(initRemoteRepositoryIfNeeded(branch, projectRepositoryPath)).acquireAndGet { git =>

      files.asScala.foreach { line =>
        val file = line("file").fixPathSeparator
        val content = line("content")

        addFile(git, projectRepositoryPath, file, content)
      }

    }
  }

  Given("""^no project settings are setup in theGardener$""") { () =>
    projectRepository.deleteAll()
  }

  Given("""^the root data path is "([^"]*)"$""") { path: String =>
    val fullPath = Paths.get(s"target/$path".fixPathSeparator)
    Files.createDirectories(fullPath.getParent)
  }

  When("""^a user register a new project with$""") { projects: util.List[ProjectTableRow] =>
    registerProject(projects.get(0).toProject().copy(hierarchy = None, branches = None))
  }

  When("""^a user register a new project in theGardener$""") { () =>
    val project = Project("suggestionsWS", "Suggestions WebServices", "[email protected]:library/suggestionsWS.git ", None, "master", None, Some("test/features"))
    registerProject(project)
  }

  Then("""^those projects settings are setup in theGardener$""") { () =>
    val expectedProjects = Seq(Project("suggestionsWS", "Suggestions WebServices", "[email protected]:library/suggestionsWS.git ", None, "master", None, Some("test/features")))
    checkProjectsInDb(expectedProjects)
  }

  Then("""^the projects settings are now$""") { projects: util.List[ProjectTableRow] =>
    checkProjectsInDb(projects.asScala.map(_.toProject().copy(hierarchy = None, branches = None)))
  }
} 
Example 30
Source File: Filters.scala    From theGardener   with Apache License 2.0 5 votes vote down vote up
package filters

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

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

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

  private val gzipFilter = new GzipFilter(shouldGzip = shouldGzip)

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

} 
Example 31
Source File: StatsController.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.document.stats

import com.mohiva.play.silhouette.api.Silhouette
import controllers.{BaseOptAuthController, Security, HasVisitLogging, HasPrettyPrintJSON}
import java.io.{ByteArrayOutputStream, PrintWriter}
import javax.inject.{Inject, Singleton}
import kantan.csv._
import kantan.csv.ops._
import kantan.csv.CsvConfiguration.{Header, QuotePolicy}
import kantan.csv.engine.commons._
import services.annotation.AnnotationService
import services.document.DocumentService
import services.user.UserService
import services.user.Roles._
import services.visit.VisitService
import org.webjars.play.WebJarsUtil
import play.api.Configuration
import play.api.mvc.{AnyContent, Request, Result, ControllerComponents}
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.i18n.I18nSupport
import plugins.PluginRegistry
import scala.concurrent.{ExecutionContext, Future}

@Singleton
class StatsController @Inject() (
  val components: ControllerComponents,
  val config: Configuration,
  val documents: DocumentService,
  val annotations: AnnotationService,
  val users: UserService,
  val silhouette: Silhouette[Security.Env],
  implicit val visitService: VisitService,
  implicit val webjars: WebJarsUtil,
  implicit val ctx: ExecutionContext
) extends BaseOptAuthController(components, config, documents, users) 
    with HasVisitLogging 
    with HasPrettyPrintJSON 
    with I18nSupport {
  
  private val CSV_CONFIG = CsvConfiguration(',', '"', QuotePolicy.WhenNeeded, Header.None)
    
  implicit val tuple2Writes: Writes[Tuple2[String, Long]] = (
    (JsPath \ "value").write[String] and
    (JsPath \ "count").write[Long]
  )(t => (t._1, t._2))
  
  private def toCSV(stats: Seq[(String, Long)]): String = {
    val out = new ByteArrayOutputStream()
    val writer = out.asCsvWriter[(String, Long)](CSV_CONFIG)
    stats.foreach(writer.write(_))
    writer.close()
    new String(out.toByteArray, "UTF-8")
  }
  
  def showDocumentStats(documentId: String, tab: Option[String]) = silhouette.UserAwareAction.async { implicit request =>
    documentReadResponse(documentId, request.identity,  { case (doc, accesslevel) =>
      logDocumentView(doc.document, None, accesslevel)      
      tab.map(_.toLowerCase) match {
        case Some(t) if t == "activity" =>  
          val plugins = PluginRegistry.listConfigs("document.stats.activity")
          Future.successful(Ok(views.html.document.stats.activity(doc, request.identity, accesslevel, plugins)))
          
        case Some(t) if t == "entities" =>
          val plugins = PluginRegistry.listConfigs("document.stats.entities")
          Future.successful(Ok(views.html.document.stats.entities(doc, request.identity, accesslevel, plugins)))
          
        case Some(t) if t == "tags" =>
          val plugins = PluginRegistry.listConfigs("document.stats.tags")
          Future.successful(Ok(views.html.document.stats.tags(doc, request.identity, accesslevel, plugins)))
          
        case _ =>
          val plugins = PluginRegistry.listConfigs("document.stats.activity")
          Future.successful(Ok(views.html.document.stats.activity(doc, request.identity, accesslevel, plugins)))
      }
    })
  }
  
  private def getTags(documentId: String)(action: (Seq[(String, Long)], Request[AnyContent]) => Result) =
    silhouette.UserAwareAction.async { implicit request =>
      documentReadResponse(documentId, request.identity,  { case (doc, accesslevel) =>
          annotations.getTagStats(documentId).map { buckets =>
            action(buckets, request.request)
          }
        }
      )
    }
  
  def getTagsAsJSON(documentId: String) = getTags(documentId) { case (buckets, request) =>
    jsonOk(Json.toJson(buckets))(request)
  }
  
  def getTagsAsCSV(documentId: String) = getTags(documentId) { case(buckets, request) =>
    Ok(toCSV(buckets)).withHeaders(CONTENT_DISPOSITION -> { s"attachment; filename=${documentId}_tags.csv" })
  }

} 
Example 32
Source File: BaseOptAuthController.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers

import services.RuntimeAccessLevel
import services.document.{ExtendedDocumentMetadata, DocumentService}
import services.generated.tables.records.{DocumentFilepartRecord, DocumentRecord}
import services.user.{User, UserService}
import play.api.Configuration
import play.api.mvc.{AnyContent, ControllerComponents, Request, Result}
import scala.concurrent.{ExecutionContext, Future}

abstract class BaseOptAuthController(
    components: ControllerComponents,
    config: Configuration,
    documents: DocumentService,
    users: UserService
  ) extends BaseController(components, config, users) {
 
  
  protected def documentPartResponse(
      documentId: String,
      partNo: Int,
      maybeUser: Option[User],
      response: (ExtendedDocumentMetadata, DocumentFilepartRecord, RuntimeAccessLevel) => Future[Result]
    )(implicit ctx: ExecutionContext, request: Request[AnyContent]) = {
    
    documentReadResponse(documentId, maybeUser, { case (doc, accesslevel) =>
      doc.fileparts.find(_.getSequenceNo == partNo) match {
        case None => Future.successful(NotFoundPage)
        case Some(part) => response(doc, part, accesslevel)
      }
    })
  }
  
} 
Example 33
Source File: BackupAdminController.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.admin.backup

import akka.actor.ActorSystem
import akka.stream.scaladsl.FileIO
import com.mohiva.play.silhouette.api.Silhouette
import controllers.{BaseAuthController, Security}
import controllers.document.BackupReader
import javax.inject.{Inject, Singleton}
import services.ContentType
import services.annotation.AnnotationService
import services.document.DocumentService
import services.generated.tables.records.DocumentFilepartRecord
import services.user.UserService
import services.user.Roles._
import services.visit.VisitService
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import org.webjars.play.WebJarsUtil
import play.api.Configuration
import play.api.mvc.{ControllerComponents, ResponseHeader, Result}
import play.api.libs.Files.TemporaryFileCreator
import play.api.http.HttpEntity
import scala.concurrent.{ExecutionContext, Future}
import storage.db.DB
import storage.es.migration.AnnotationMigrationUtil
import transform.tiling.TilingService

@Singleton
class BackupAdminController @Inject() (
    val components: ControllerComponents,
    val config: Configuration,
    val migrationUtil: AnnotationMigrationUtil,
    val users: UserService,
    val visits: VisitService,
    val silhouette: Silhouette[Security.Env],
    implicit val db: DB,
    implicit val tilingService: TilingService,
    implicit val annotations: AnnotationService,
    implicit val documents: DocumentService,
    implicit val ctx: ExecutionContext,
    implicit val system: ActorSystem,
    implicit val tmpFileCreator: TemporaryFileCreator,
    implicit val webJarsUtil: WebJarsUtil
  ) extends BaseAuthController(components, config, documents, users) with BackupReader {

  

  def restore = silhouette.SecuredAction(Security.WithRole(Admin)).async { implicit request =>
    request.body.asMultipartFormData.flatMap(_.file("backup")) match {
      case Some(formData) =>
        restoreBackup(formData.ref.path.toFile, runAsAdmin = true, forcedOwner = None).map { case (doc, fileparts) =>
          Ok
        }.recover { case t: Throwable =>
          t.printStackTrace()
          InternalServerError
        }

      case None =>
        Future.successful(BadRequest)
    }
  }

  def exportVisits = silhouette.SecuredAction(Security.WithRole(Admin)).async { implicit request =>
    visits.scrollExport().map { path =>
      val fmt = DateTimeFormat.forPattern("yyyy-MM-dd")
      val source = FileIO.fromPath(path)
      val filename = s"visits-exported-${fmt.print(DateTime.now)}.csv"
      Result(
        header = ResponseHeader(200, Map("Content-Disposition" -> s"""attachment; filename="${filename}"""")),
        body = HttpEntity.Streamed(source, None, Some("text/csv"))
      )
    }
  }

  def deleteVisitsOlderThan(date: Option[String]) = silhouette.SecuredAction(Security.WithRole(Admin)).async { implicit request =>
    date match {
      case Some(_) =>
        Future.successful(BadRequest("User-provided dates not supported yet."))

      case _ =>
        val cutoffDate = DateTime.now minusMonths 6
        visits.deleteOlderThan(cutoffDate).map { success =>
          if (success) Ok("Done.")
          else InternalServerError("Something went wrong.")
        }
    }
  }

} 
Example 34
Source File: BaseAuthController.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers

import services.RuntimeAccessLevel
import services.document.{ExtendedDocumentMetadata, DocumentService}
import services.generated.tables.records.{DocumentFilepartRecord, DocumentRecord}
import services.user.{User, UserService}
import play.api.Configuration
import play.api.mvc.{ControllerComponents, Result}
import scala.concurrent.ExecutionContext

abstract class BaseAuthController(
    components: ControllerComponents,
    config: Configuration,
    documents: DocumentService,
    users: UserService
  ) extends BaseController(components, config, users) {
  
  
  protected def documentPartResponse(
    docId: String,
    partNo: Int,
    user: User,
    response: (ExtendedDocumentMetadata, DocumentFilepartRecord, RuntimeAccessLevel) => Result
  )(implicit ctx: ExecutionContext) = {
    documentResponse(docId, user, { case (doc, accesslevel) =>
      doc.fileparts.find(_.getSequenceNo == partNo) match {
        case None => NotFoundPage
        case Some(part) => response(doc, part, accesslevel)
      }
    })
  }
  
} 
Example 35
Source File: ZipkinTraceFilter.scala    From play-zipkin-tracing   with Apache License 2.0 5 votes vote down vote up
package brave.play.filter

import javax.inject.Inject

import akka.stream.Materializer
import brave.play.ZipkinTraceServiceLike
import play.api.mvc.{Filter, Headers, RequestHeader, Result}
import play.api.routing.Router

import scala.concurrent.Future
import scala.util.Failure


class ZipkinTraceFilter @Inject() (tracer: ZipkinTraceServiceLike)(implicit val mat: Materializer) extends Filter {

  import tracer.executionContext
  private val reqHeaderToSpanName: RequestHeader => String = ZipkinTraceFilter.ParamAwareRequestNamer

  def apply(nextFilter: RequestHeader => Future[Result])(req: RequestHeader): Future[Result] = {
    val serverSpan = tracer.serverReceived(
      spanName = reqHeaderToSpanName(req),
      span = tracer.newSpan(req.headers)((headers, key) => headers.get(key))
    )
    val result = nextFilter(req.withHeaders(new Headers(
      (req.headers.toMap.mapValues(_.headOption getOrElse "") ++ tracer.toMap(serverSpan)).toSeq
    )))
    result.onComplete {
      case Failure(t) => tracer.serverSend(serverSpan, "failed" -> s"Finished with exception: ${t.getMessage}")
      case _ => tracer.serverSend(serverSpan)
    }
    result
  }
}

object ZipkinTraceFilter {
  val ParamAwareRequestNamer: RequestHeader => String = { reqHeader =>
    import org.apache.commons.lang3.StringUtils
    val pathPattern = StringUtils.replace(
      reqHeader.attrs.get(Router.Attrs.HandlerDef).map(_.path).getOrElse(reqHeader.path),
      "<[^/]+>", ""
    )
    s"${reqHeader.method} - $pathPattern"
  }
} 
Example 36
Source File: ApiAction.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package actions

import cats.effect.IO
import controllers.{CacheHeader, OidcAuthenticator}
import javax.inject.Inject
import org.slf4j.LoggerFactory
import play.api.mvc.Results.{Forbidden, NotFound, Unauthorized}
import play.api.mvc.{AnyContent, BodyParser, Result}
import vinyldns.core.domain.membership.User

import scala.concurrent.{ExecutionContext, Future}


class LegacyApiAction @Inject() (
    val userLookup: String => IO[Option[User]],
    val oidcAuthenticator: OidcAuthenticator,
    val parser: BodyParser[AnyContent]
) extends VinylDnsAction
    with ApiActionBuilder
    with CacheHeader {

  override val logger = LoggerFactory.getLogger(classOf[LegacyApiAction])
  implicit val executionContext: ExecutionContext = scala.concurrent.ExecutionContext.global

  def notLoggedInResult: Future[Result] =
    Future.successful(
      Unauthorized("You are not logged in. Please login to continue.").withHeaders(cacheHeaders: _*)
    )

  def cantFindAccountResult(un: String): Future[Result] =
    Future.successful(
      NotFound(s"Unable to find user account for user name '$un'")
        .withHeaders(cacheHeaders: _*)
    )

  def lockedUserResult(un: String): Future[Result] =
    Future.successful(Forbidden(s"User account for `$un` is locked.").withHeaders(cacheHeaders: _*))
} 
Example 37
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 38
Source File: GroupApi.scala    From asura   with MIT License 5 votes vote down vote up
package asura.app.api

import akka.actor.ActorSystem
import asura.app.AppErrorMessages
import asura.app.api.auth.Reserved
import asura.common.model.ApiResError
import asura.common.util.StringUtils
import asura.core.es.actor.ActivitySaveActor
import asura.core.es.model.{Activity, Group}
import asura.core.es.service.GroupService
import asura.core.model.QueryGroup
import asura.play.api.BaseApi.OkApiRes
import javax.inject.{Inject, Singleton}
import org.pac4j.play.scala.SecurityComponents
import play.api.Configuration
import play.api.mvc.{RequestHeader, Result}

import scala.concurrent.{ExecutionContext, Future}

@Singleton
class GroupApi @Inject()(
                          implicit val system: ActorSystem,
                          val exec: ExecutionContext,
                          val configuration: Configuration,
                          val controllerComponents: SecurityComponents,
                        ) extends BaseApi {

  val administrators = configuration.getOptional[Seq[String]]("asura.admin").getOrElse(Nil).toSet
  val activityActor = system.actorOf(ActivitySaveActor.props())

  def getById(id: String) = Action.async { implicit req =>
    GroupService.getById(id).toOkResultByEsOneDoc(id)
  }

  def delete(id: String) = Action.async { implicit req =>
    checkPrivilege { user =>
      activityActor ! Activity(id, StringUtils.EMPTY, user, Activity.TYPE_DELETE_GROUP, id)
      GroupService.deleteGroup(id).toOkResult
    }
  }

  def put() = Action(parse.byteString).async { implicit req =>
    val group = req.bodyAs(classOf[Group])
    val user = getProfileId()
    group.fillCommonFields(user)
    if (Reserved.isReservedGroup(group.id)) {
      Future.successful(OkApiRes(ApiResError(getI18nMessage(AppErrorMessages.error_CanNotUseReservedGroup))))
    } else {
      GroupService.index(group).map(res => {
        activityActor ! Activity(group.id, StringUtils.EMPTY, user, Activity.TYPE_NEW_GROUP, group.id)
        toActionResultFromAny(res)
      })
    }
  }

  def query() = Action(parse.byteString).async { implicit req =>
    val queryGroup = req.bodyAs(classOf[QueryGroup])
    GroupService.queryGroup(queryGroup).toOkResultByEsList(false)
  }

  def update() = Action(parse.byteString).async { implicit req =>
    val group = req.bodyAs(classOf[Group])
    GroupService.updateGroup(group).toOkResult
  }

  private def checkPrivilege(func: String => Future[Result])(implicit request: RequestHeader): Future[Result] = {
    val user = getProfileId()
    val isAllowed = if (administrators.nonEmpty) administrators.contains(user) else true
    if (isAllowed) {
      func(user)
    } else {
      Future.successful(OkApiRes(ApiResError(getI18nMessage(AppErrorMessages.error_NotAllowedContactAdministrator, administrators.mkString(",")))))
    }
  }
} 
Example 39
Source File: ClusterApi.scala    From asura   with MIT License 5 votes vote down vote up
package asura.app.api

import akka.actor.ActorSystem
import akka.pattern.ask
import akka.util.Timeout
import asura.app.AppErrorMessages
import asura.cluster.ClusterManager
import asura.cluster.actor.MemberListenerActor.GetAllMembers
import asura.common.model.ApiResError
import asura.core.CoreConfig
import asura.play.api.BaseApi.OkApiRes
import javax.inject.{Inject, Singleton}
import org.pac4j.play.scala.SecurityComponents
import play.api.Configuration
import play.api.mvc.{RequestHeader, Result}

import scala.concurrent.{ExecutionContext, Future}

@Singleton
class ClusterApi @Inject()(
                            implicit val system: ActorSystem,
                            val exec: ExecutionContext,
                            val configuration: Configuration,
                            val controllerComponents: SecurityComponents
                          ) extends BaseApi {

  implicit val timeout: Timeout = CoreConfig.DEFAULT_ACTOR_ASK_TIMEOUT

  def getMembers() = Action(parse.byteString).async { implicit req =>
    checkClusterEnabled {
      (ClusterManager.clusterManagerActor ? GetAllMembers).toOkResult
    }
  }

  private def checkClusterEnabled(func: => Future[Result])(implicit request: RequestHeader): Future[Result] = {
    if (ClusterManager.enabled) {
      func
    } else {
      Future.successful(OkApiRes(ApiResError(getI18nMessage(AppErrorMessages.error_ClusterNotEnabled))))
    }
  }
} 
Example 40
Source File: ErrorHandler.scala    From asura   with MIT License 5 votes vote down vote up
package asura.play.hook

import asura.common.exceptions.ErrorMessages
import asura.common.exceptions.ErrorMessages.ErrorMessageException
import asura.common.model.{ApiCode, ApiRes, ApiResError}
import asura.common.util.{LogUtils, StringUtils}
import asura.play.api.BaseApi.OkApiRes
import javax.inject.{Inject, Singleton}
import org.slf4j.LoggerFactory
import play.api.http.HttpErrorHandler
import play.api.i18n.{Langs, MessagesApi}
import play.api.mvc.{RequestHeader, Result}

import scala.concurrent.Future

@Singleton
class ErrorHandler @Inject()(messagesApi: MessagesApi, langs: Langs) extends HttpErrorHandler with ErrorMessages {

  lazy val logger = LoggerFactory.getLogger(classOf[ErrorHandler])

  override def onClientError(request: RequestHeader, statusCode: Int, message: String): Future[Result] = {
    val msg = s""""${request.method} ${request.uri}" ${statusCode} ${if (StringUtils.isNotEmpty(message)) message else ""}"""
    Future.successful(OkApiRes(ApiResError(msg)))
  }

  override def onServerError(request: RequestHeader, exception: Throwable): Future[Result] = {
    val logStack = LogUtils.stackTraceToString(exception)
    logger.warn(logStack)
    val requestLocal = request.headers.get("Local")
    implicit val lang = if (requestLocal.nonEmpty) {
      langs.availables.find(_.code == requestLocal.get).getOrElse(langs.availables.head)
    } else {
      langs.availables.head
    }
    exception match {
      case errMsgException: ErrorMessageException =>
        val errMsg = messagesApi(errMsgException.error.name, errMsgException.error.errMsg)
        Future.successful(OkApiRes(ApiRes(code = ApiCode.ERROR, msg = errMsg, data = logStack)))
      case _ =>
        val message = if (StringUtils.isNotEmpty(exception.getMessage)) {
          exception.getMessage
        } else {
          messagesApi(error_ServerError.name)
        }
        Future.successful(OkApiRes(ApiRes(code = ApiCode.ERROR, msg = message, data = logStack)))
    }
  }
} 
Example 41
Source File: AuthCtrlSpec.scala    From gospeak   with Apache License 2.0 5 votes vote down vote up
package gospeak.web.auth

import gospeak.core.domain.User
import gospeak.core.testingutils.Generators._
import gospeak.libs.scala.domain.{EmailAddress, Secret}
import gospeak.web.testingutils.CtrlSpec
import gospeak.web.utils.GsForms.SignupData
import org.scalatest.BeforeAndAfterEach
import play.api.http.Status
import play.api.mvc.{AnyContentAsFormUrlEncoded, RequestHeader, Result}
import play.api.test.Helpers._

import scala.concurrent.Future

class AuthCtrlSpec extends CtrlSpec with BeforeAndAfterEach {
  private val _ = aEmailAddress // to keep the `gospeak.core.testingutils.Generators._` import
  private val ctrl = new AuthCtrl(cc, silhouette, conf, db.user, db.userRequest, db.group, authSrv, emailSrv)
  private val redirect: Option[String] = None
  // private val signupData = random[SignupData] // TODO add generators constraints: firstName&lastName should not be empty, password should have 8 char at least
  private val signupData = SignupData(User.Slug.from("slug").right.get, "first", "last", EmailAddress.from("[email protected]").right.get, Secret("passpass"), rememberMe = true)

  override def beforeEach(): Unit = {
    db.migrate().unsafeRunSync()
    emailSrv.sentEmails.clear()
  }

  override def afterEach(): Unit = db.dropTables().unsafeRunSync()

  describe("AuthCtrl") {
    describe("signup") {
      it("should return form when not authenticated") {
        val res = ctrl.signup(redirect).apply(unsecuredReq)
        status(res) shouldBe Status.OK
      }
      it("should redirect to user home when authenticated") {
        val res = ctrl.signup(redirect).apply(securedReq)
        status(res) shouldBe Status.SEE_OTHER
      }
      it("should create a user and credentials then login") {
        val res = AuthCtrlSpec.doSignup(signupData)(unsecuredReq)(ctrl)
        contentAsString(res) shouldBe ""
        headers(res) should contain key "Location"
        status(res) shouldBe Status.SEE_OTHER
        emailSrv.sentEmails should have length 1
      }
      it("should find the user, create credentials then login") {

      }
      it("should fail if credentials already exist") {

      }
    }
    describe("login") {
      it("should return form when not authenticated") {
        val res = ctrl.login(redirect).apply(unsecuredReq)
        status(res) shouldBe Status.OK
      }
      it("should redirect to user home when authenticated") {
        val res = ctrl.login(redirect).apply(securedReq)
        status(res) shouldBe Status.SEE_OTHER
      }
    }
    describe("forgotPassword") {
      it("should return form when not authenticated") {
        val res = ctrl.forgotPassword(redirect).apply(unsecuredReq)
        status(res) shouldBe Status.OK
      }
      it("should redirect to user home when authenticated") {
        val res = ctrl.forgotPassword(redirect).apply(securedReq)
        status(res) shouldBe Status.SEE_OTHER
      }
    }
  }
}

object AuthCtrlSpec {
  def doSignup(data: SignupData, redirect: Option[String] = None)(req: RequestHeader)(ctrl: AuthCtrl): Future[Result] = {
    ctrl.doSignup(redirect).apply(req.withBody(AnyContentAsFormUrlEncoded(Map(
      "slug" -> Seq(data.slug.value),
      "first-name" -> Seq(data.firstName),
      "last-name" -> Seq(data.lastName),
      "email" -> Seq(data.email.value),
      "password" -> Seq(data.password.decode),
      "rememberMe" -> Seq(data.rememberMe.toString)
    ))))
  }
} 
Example 42
Source File: CustomSecuredErrorHandler.scala    From gospeak   with Apache License 2.0 5 votes vote down vote up
package gospeak.web.auth.services

import com.mohiva.play.silhouette.api.actions.SecuredErrorHandler
import gospeak.web.api.domain.utils.ErrorResult
import gospeak.web.auth.routes.AuthCtrl
import gospeak.web.pages.user.routes.UserCtrl
import gospeak.web.utils.HttpUtils
import play.api.http.Status
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.libs.json.Json
import play.api.mvc.Results._
import play.api.mvc.{RequestHeader, Result}

import scala.concurrent.Future

class CustomSecuredErrorHandler(val messagesApi: MessagesApi) extends SecuredErrorHandler with I18nSupport {
  override def onNotAuthenticated(implicit req: RequestHeader): Future[Result] = {
    val message = "Unauthorized: please login"
    if (req.uri.startsWith("/api")) {
      Future.successful(Unauthorized(Json.toJson(ErrorResult(Status.UNAUTHORIZED, message, execMs = 0))))
    } else {
      Future.successful(Redirect(AuthCtrl.login(Some(req.uri))).flashing("warning" -> message))
    }
  }

  override def onNotAuthorized(implicit req: RequestHeader): Future[Result] = {
    val message = "Forbidden: it seems you lack some rights here"
    if (req.uri.startsWith("/api")) {
      Future.successful(Unauthorized(Json.toJson(ErrorResult(Status.FORBIDDEN, message, execMs = 0))))
    } else {
      val next = Redirect(HttpUtils.getReferer(req.headers).getOrElse(UserCtrl.index().path()))
      Future.successful(next.flashing("error" -> message))
    }
  }
} 
Example 43
Source File: CfpCtrl.scala    From gospeak   with Apache License 2.0 5 votes vote down vote up
package gospeak.web.pages.orga.cfps

import cats.data.OptionT
import cats.effect.IO
import com.mohiva.play.silhouette.api.Silhouette
import gospeak.core.domain.utils.OrgaCtx
import gospeak.core.domain.{Cfp, Event, Group}
import gospeak.core.services.storage._
import gospeak.web.AppConf
import gospeak.web.auth.domain.CookieEnv
import gospeak.web.domain.Breadcrumb
import gospeak.web.pages.orga.GroupCtrl
import gospeak.web.pages.orga.cfps.CfpCtrl._
import gospeak.web.pages.orga.events.routes.{EventCtrl => EventRoutes}
import gospeak.web.utils.{GsForms, OrgaReq, UICtrl}
import gospeak.libs.scala.domain.Page
import play.api.data.Form
import play.api.mvc.{Action, AnyContent, ControllerComponents, Result}

class CfpCtrl(cc: ControllerComponents,
              silhouette: Silhouette[CookieEnv],
              conf: AppConf,
              userRepo: OrgaUserRepo,
              val groupRepo: OrgaGroupRepo,
              cfpRepo: OrgaCfpRepo,
              eventRepo: OrgaEventRepo,
              proposalRepo: OrgaProposalRepo) extends UICtrl(cc, silhouette, conf) with UICtrl.OrgaAction {
  def list(group: Group.Slug, params: Page.Params): Action[AnyContent] = OrgaAction(group) { implicit req =>
    val customParams = params.withNullsFirst
    cfpRepo.list(customParams).map(cfps => Ok(html.list(cfps)(listBreadcrumb))) // TODO listWithProposalCount
  }

  def create(group: Group.Slug, event: Option[Event.Slug]): Action[AnyContent] = OrgaAction(group) { implicit req =>
    createView(group, GsForms.cfp, event)
  }

  def doCreate(group: Group.Slug, event: Option[Event.Slug]): Action[AnyContent] = OrgaAction(group) { implicit req =>
    GsForms.cfp.bindFromRequest.fold(
      formWithErrors => createView(group, formWithErrors, event),
      data => (for {
        // TODO check if slug not already exist
        cfpElt <- OptionT.liftF(cfpRepo.create(data))
        redirect <- OptionT.liftF(event.map { e =>
          eventRepo.attachCfp(e, cfpElt.id)
            .map(_ => Redirect(EventRoutes.detail(group, e)))
          // TODO recover and redirect to cfp detail
        }.getOrElse {
          IO.pure(Redirect(routes.CfpCtrl.detail(group, data.slug)))
        })
      } yield redirect).value.map(_.getOrElse(groupNotFound(group)))
    )
  }

  private def createView(group: Group.Slug, form: Form[Cfp.Data], event: Option[Event.Slug])(implicit req: OrgaReq[AnyContent]): IO[Result] = {
    val b = listBreadcrumb.add("New" -> routes.CfpCtrl.create(group))
    IO.pure(Ok(html.create(form, event)(b)))
  }

  def detail(group: Group.Slug, cfp: Cfp.Slug, params: Page.Params): Action[AnyContent] = OrgaAction(group) { implicit req =>
    (for {
      cfpElt <- OptionT(cfpRepo.find(cfp))
      proposals <- OptionT.liftF(proposalRepo.listFull(cfp, params))
      speakers <- OptionT.liftF(userRepo.list(proposals.items.flatMap(_.users).distinct))
      userRatings <- OptionT.liftF(proposalRepo.listRatings(cfp))
      b = breadcrumb(cfpElt)
    } yield Ok(html.detail(cfpElt, proposals, speakers, userRatings)(b))).value.map(_.getOrElse(cfpNotFound(group, cfp)))
  }

  def edit(group: Group.Slug, cfp: Cfp.Slug, redirect: Option[String]): Action[AnyContent] = OrgaAction(group) { implicit req =>
    editView(group, cfp, GsForms.cfp, redirect)
  }

  def doEdit(group: Group.Slug, cfp: Cfp.Slug, redirect: Option[String]): Action[AnyContent] = OrgaAction(group) { implicit req =>
    GsForms.cfp.bindFromRequest.fold(
      formWithErrors => editView(group, cfp, formWithErrors, redirect),
      data => (for {
        cfpOpt <- OptionT.liftF(cfpRepo.find(data.slug))
        res <- OptionT.liftF(cfpOpt match {
          case Some(duplicate) if data.slug != cfp => editView(group, cfp, GsForms.cfp.fillAndValidate(data).withError("slug", s"Slug already taken by cfp: ${duplicate.name.value}"), redirect)
          case _ => cfpRepo.edit(cfp, data).map { _ => redirectOr(redirect, routes.CfpCtrl.detail(group, data.slug)) }
        })
      } yield res).value.map(_.getOrElse(groupNotFound(group)))
    )
  }

  private def editView(group: Group.Slug, cfp: Cfp.Slug, form: Form[Cfp.Data], redirect: Option[String])(implicit req: OrgaReq[AnyContent], ctx: OrgaCtx): IO[Result] = {
    (for {
      cfpElt <- OptionT(cfpRepo.find(cfp))
      filledForm = if (form.hasErrors) form else form.fill(cfpElt.data)
      b = breadcrumb(cfpElt).add("Edit" -> routes.CfpCtrl.edit(group, cfp))
    } yield Ok(html.edit(cfpElt, filledForm, redirect)(b))).value.map(_.getOrElse(cfpNotFound(group, cfp)))
  }
}

object CfpCtrl {
  def listBreadcrumb(implicit req: OrgaReq[AnyContent]): Breadcrumb =
    GroupCtrl.breadcrumb.add("CFPs" -> routes.CfpCtrl.list(req.group.slug))

  def breadcrumb(cfp: Cfp)(implicit req: OrgaReq[AnyContent]): Breadcrumb =
    listBreadcrumb.add(cfp.name.value -> routes.CfpCtrl.detail(req.group.slug, cfp.slug))
} 
Example 44
Source File: ProfileCtrl.scala    From gospeak   with Apache License 2.0 5 votes vote down vote up
package gospeak.web.pages.user.profile

import cats.effect.IO
import com.mohiva.play.silhouette.api.Silhouette
import gospeak.core.domain.User
import gospeak.core.services.storage.{UserGroupRepo, UserProposalRepo, UserTalkRepo, UserUserRepo}
import gospeak.web.AppConf
import gospeak.web.auth.domain.CookieEnv
import gospeak.web.domain.Breadcrumb
import gospeak.web.pages.published.speakers.routes.{SpeakerCtrl => PublishedSpeakerRoutes}
import gospeak.web.pages.user.UserCtrl
import gospeak.web.pages.user.profile.ProfileCtrl._
import gospeak.web.utils.{GsForms, UICtrl, UserReq}
import play.api.data.Form
import play.api.mvc.{Action, AnyContent, ControllerComponents, Result}

class ProfileCtrl(cc: ControllerComponents,
                  silhouette: Silhouette[CookieEnv],
                  conf: AppConf,
                  groupRepo: UserGroupRepo,
                  proposalRepo: UserProposalRepo,
                  talkRepo: UserTalkRepo,
                  userRepo: UserUserRepo) extends UICtrl(cc, silhouette, conf) {
  def edit(): Action[AnyContent] = UserAction { implicit req =>
    editView(GsForms.user)
  }

  def doEdit(): Action[AnyContent] = UserAction { implicit req =>
    GsForms.user.bindFromRequest.fold(
      formWithErrors => editView(formWithErrors),
      data => userRepo.edit(data)
        .map(_ => Redirect(PublishedSpeakerRoutes.detail(req.user.slug)).flashing("success" -> "Profile updated"))
    )
  }

  private def editView(form: Form[User.Data])(implicit req: UserReq[AnyContent]): IO[Result] = {
    val filledForm = if (form.hasErrors) form else form.fill(req.user.data)
    IO(Ok(html.edit(filledForm)(editBreadcrumb)))
  }
}

object ProfileCtrl {
  def breadcrumb(implicit req: UserReq[AnyContent]): Breadcrumb =
    UserCtrl.breadcrumb.add("Profile" -> PublishedSpeakerRoutes.detail(req.user.slug))

  def editBreadcrumb(implicit req: UserReq[AnyContent]): Breadcrumb =
    breadcrumb.add("Edit" -> routes.ProfileCtrl.edit())
} 
Example 45
Source File: PropertyEopsDeclarationResourceSpec.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package router.resources

import mocks.services.MockPropertyEopsDeclarationService
import play.api.mvc.Result
import play.api.test.FakeRequest
import router.errors.{ErrorCode, IncorrectAPIVersion, UnsupportedAPIVersion}
import support.ResourceSpec
import uk.gov.hmrc.http.HttpResponse

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class PropertyEopsDeclarationResourceSpec extends ResourceSpec
  with MockPropertyEopsDeclarationService {

  class Setup {
    val resource = new PropertyEopsDeclarationResource(
      service = mockPropertyEopsDeclarationService,
      authConnector = mockAuthConnector,
      cc = controllerComponents
    )
    mockAuthAction
  }

  val request = FakeRequest()

  "post" should {
    "return a 204 with the response headers" when {
      "the service returns a HttpResponse containing a 204 with no json response body" in new Setup {
        MockPropertyEopsDeclarationService.post()
          .returns(Future.successful(Right(HttpResponse(NO_CONTENT, None, testHeaderResponse))))

        val result: Future[Result] = resource.post("","","")(FakeRequest().withBody(requestJson))
        status(result) shouldBe NO_CONTENT
        headers(result) shouldBe testHeader
        contentType(result) shouldBe None
      }
    }

    "return a 200 with a json response body and response headers" when {
      "the service returns a HttpResponse containing a 200 with a json response body" in new Setup {
        MockPropertyEopsDeclarationService.post()
          .returns(Future.successful(Right(HttpResponse(OK, Some(responseJson), testHeaderResponse))))

        val result: Future[Result] = resource.post("","","")(FakeRequest().withBody(requestJson))
        status(result) shouldBe OK
        headers(result) shouldBe testHeader
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe responseJson
      }
    }

    "return a 406 with a json response body representing the error" when {
      "the service returns an IncorrectAPIVersion response" in new Setup {
        MockPropertyEopsDeclarationService.post()
          .returns(Future.successful(Left(IncorrectAPIVersion)))

        val result: Future[Result] = resource.post("","","")(FakeRequest().withBody(requestJson))
        status(result) shouldBe NOT_ACCEPTABLE
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe ErrorCode.invalidAcceptHeader.asJson
      }
    }

    "return a 404 with a json response body representing the error" when {
      "the service returns an UnsupportedAPIVersion response" in new Setup {
        MockPropertyEopsDeclarationService.post()
          .returns(Future.successful(Left(UnsupportedAPIVersion)))

        val result: Future[Result] = resource.post("","","")(FakeRequest().withBody(requestJson))
        status(result) shouldBe NOT_FOUND
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe ErrorCode.notFound.asJson
      }
    }
  }

} 
Example 46
Source File: PaymentsControllerSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers

import config.ConfigDecorator
import connectors._
import controllers.auth.requests.UserRequest
import controllers.auth.{AuthJourney, WithBreadcrumbAction}
import models.CreatePayment
import org.joda.time.DateTime
import org.mockito.Matchers.any
import org.mockito.Mockito.when
import org.scalatestplus.mockito.MockitoSugar
import play.api.Application
import play.api.i18n.MessagesApi
import play.api.inject.bind
import play.api.mvc.{ActionBuilder, MessagesControllerComponents, Request, Result}
import play.api.test.FakeRequest
import play.api.test.Helpers.{redirectLocation, _}
import uk.gov.hmrc.renderer.TemplateRenderer
import uk.gov.hmrc.time.CurrentTaxYear
import util.UserRequestFixture.buildUserRequest
import util.{ActionBuilderFixture, BaseSpec}

import scala.concurrent.{ExecutionContext, Future}

class PaymentsControllerSpec extends BaseSpec with CurrentTaxYear with MockitoSugar {

  override def now: () => DateTime = DateTime.now

  lazy val fakeRequest = FakeRequest("", "")

  val mockPayConnector = mock[PayApiConnector]
  val mockAuthJourney = mock[AuthJourney]

  override implicit lazy val app: Application = localGuiceApplicationBuilder()
    .overrides(
      bind[PayApiConnector].toInstance(mockPayConnector),
      bind[AuthJourney].toInstance(mockAuthJourney)
    )
    .build()

  def controller =
    new PaymentsController(
      mockPayConnector,
      mockAuthJourney,
      injected[WithBreadcrumbAction],
      injected[MessagesControllerComponents]
    )(mockLocalPartialRetriever, injected[ConfigDecorator], mock[TemplateRenderer], injected[ExecutionContext])

  when(mockAuthJourney.authWithPersonalDetails).thenReturn(new ActionBuilderFixture {
    override def invokeBlock[A](request: Request[A], block: UserRequest[A] => Future[Result]): Future[Result] =
      block(
        buildUserRequest(
          request = request
        ))
  })

  "makePayment" should {
    "redirect to the response's nextUrl" in {

      val expectedNextUrl = "someNextUrl"
      val createPaymentResponse = CreatePayment("someJourneyId", expectedNextUrl)

      when(mockPayConnector.createPayment(any())(any(), any()))
        .thenReturn(Future.successful(Some(createPaymentResponse)))

      val result = controller.makePayment()(FakeRequest())
      status(result) shouldBe SEE_OTHER
      redirectLocation(result) shouldBe Some("someNextUrl")
    }

    "redirect to a BAD_REQUEST page if createPayment failed" in {

      when(mockPayConnector.createPayment(any())(any(), any()))
        .thenReturn(Future.successful(None))

      val result = controller.makePayment()(FakeRequest())
      status(result) shouldBe BAD_REQUEST
    }
  }
} 
Example 47
Source File: HealthControllerSpec.scala    From smui   with Apache License 2.0 5 votes vote down vote up
package controllers

import org.scalatest.mockito.MockitoSugar
import org.scalatestplus.play._
import play.api.http.ContentTypes
import play.api.mvc.Result
import play.api.test.Helpers._
import play.api.test.{FakeRequest, Helpers}

import scala.concurrent.Future


class HealthControllerSpec extends PlaySpec with MockitoSugar {

  "The HealthController" must {
    "provide an health status json" in {
      val stubControllerComponents = Helpers.stubControllerComponents()
      val controller = new HealthController(stubControllerComponents)
      val result: Future[Result] = controller.health.apply(FakeRequest())
      val bodyText: String = contentAsString(result)
      contentType(result) mustBe Some(ContentTypes.JSON)
      (contentAsJson(result) \ "name").asOpt[String] mustBe Some("search-management-ui")
    }
  }
} 
Example 48
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 49
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 50
Source File: NispFrontendControllerSpec.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.controllers

import org.slf4j.{Logger => Slf4JLogger}
import org.mockito.Mockito.{verify, when}
import org.mockito.ArgumentMatchers._
import org.scalatest.mock.MockitoSugar
import org.scalatestplus.play.OneAppPerSuite
import play.api.Logger
import play.api.http.Status
import play.api.mvc.Result
import play.api.test.FakeRequest
import uk.gov.hmrc.nisp.config.{ApplicationGlobal, ApplicationGlobalTrait}
import uk.gov.hmrc.nisp.helpers.{MockApplicationGlobal, MockCachedStaticHtmlPartialRetriever}
import uk.gov.hmrc.nisp.utils.MockTemplateRenderer
import uk.gov.hmrc.play.test.UnitSpec
import uk.gov.hmrc.renderer.TemplateRenderer

class NispFrontendControllerSpec extends UnitSpec with MockitoSugar with OneAppPerSuite {

  val mockLogger: Slf4JLogger = mock[Slf4JLogger]
  when(mockLogger.isErrorEnabled).thenReturn(true)

  def controller = new NispFrontendController {
    override val logger = new Logger(mockLogger)
    val cachedStaticHtmlPartialRetriever = MockCachedStaticHtmlPartialRetriever
    override implicit val templateRenderer: TemplateRenderer = MockTemplateRenderer
    override  val applicationGlobal:ApplicationGlobalTrait = MockApplicationGlobal
  }

  implicit val request = FakeRequest()

  "onError" should {
    "should log error details" in {
      val result: Result =  controller.onError(new Exception())
      verify(mockLogger).error(anyString(), any[Exception])
    }

    "should return an Internal Server Error (500)" in {
      val result: Result =  controller.onError(new Exception())
      status(result) shouldBe Status.INTERNAL_SERVER_ERROR
    }
  }

} 
Example 51
Source File: ExcludedAuthActionImpl.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.controllers.auth

import java.net.{URI, URLEncoder}

import com.google.inject.{ImplementedBy, Inject}
import play.api.mvc.Results.Redirect
import play.api.mvc.{ActionBuilder, ActionFunction, Request, Result}
import uk.gov.hmrc.auth.core._
import uk.gov.hmrc.auth.core.retrieve.v2.Retrievals
import uk.gov.hmrc.auth.core.retrieve.~
import uk.gov.hmrc.domain.Nino
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.nisp.config.ApplicationConfig
import uk.gov.hmrc.play.HeaderCarrierConverter

import scala.concurrent.{ExecutionContext, Future}

class ExcludedAuthActionImpl @Inject()(override val authConnector: PlayAuthConnector)
                                      (implicit ec: ExecutionContext) extends ExcludedAuthAction with AuthorisedFunctions {

  override def invokeBlock[A](request: Request[A], block: ExcludedAuthenticatedRequest[A] => Future[Result]): Future[Result] = {

    implicit val hc: HeaderCarrier = HeaderCarrierConverter.fromHeadersAndSession(request.headers, Some(request.session))

    authorised(ConfidenceLevel.L200)
      .retrieve(Retrievals.nino and Retrievals.confidenceLevel and Retrievals.credentials and Retrievals.loginTimes) {
        case Some(nino) ~ confidenceLevel ~ credentials ~ loginTimes =>
          block(ExcludedAuthenticatedRequest(request,
            Nino(nino),
            AuthDetails(confidenceLevel, credentials.map(creds => creds.providerType), loginTimes))
          )
        case _ => throw new RuntimeException("Can't find credentials for user")
      } recover {
      case _: NoActiveSession => Redirect(ApplicationConfig.ggSignInUrl, Map("continue" -> Seq(ApplicationConfig.postSignInRedirectUrl),
        "origin" -> Seq("nisp-frontend"), "accountType" -> Seq("individual")))
      case _: InsufficientConfidenceLevel => Redirect(ivUpliftURI.toURL.toString)
    }
  }

  private val ivUpliftURI: URI =
  new URI(s"${ApplicationConfig.ivUpliftUrl}?origin=NISP&" +
    s"completionURL=${URLEncoder.encode(ApplicationConfig.postSignInRedirectUrl, "UTF-8")}&" +
    s"failureURL=${URLEncoder.encode(ApplicationConfig.notAuthorisedRedirectUrl, "UTF-8")}" +
    s"&confidenceLevel=200")

}

@ImplementedBy(classOf[ExcludedAuthActionImpl])
trait ExcludedAuthAction extends ActionBuilder[ExcludedAuthenticatedRequest] with ActionFunction[Request, ExcludedAuthenticatedRequest] 
Example 52
Source File: NispFrontendController.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.controllers

import play.api.mvc.{Request, Result}
import play.api.{Logger, PlayException}
import uk.gov.hmrc.nisp.config.wiring.NispFormPartialRetriever
import uk.gov.hmrc.nisp.config.{ApplicationGlobal, ApplicationGlobalTrait, LocalTemplateRenderer}
import uk.gov.hmrc.play.frontend.controller.FrontendController
import uk.gov.hmrc.play.partials.CachedStaticHtmlPartialRetriever
import uk.gov.hmrc.renderer.TemplateRenderer

trait NispFrontendController extends FrontendController {
  val logger: Logger = Logger(this.getClass)

  implicit val cachedStaticHtmlPartialRetriever: CachedStaticHtmlPartialRetriever
  implicit val formPartialRetriever: uk.gov.hmrc.play.partials.FormPartialRetriever = NispFormPartialRetriever
  implicit val templateRenderer: TemplateRenderer = LocalTemplateRenderer

  val applicationGlobal: ApplicationGlobalTrait = ApplicationGlobal

  def onError(ex: Exception)(implicit request: Request[_]): Result = {
    logger.error(
      """
        |
        |! %sInternal server error, for (%s) [%s] ->
        | """.stripMargin.format(ex match {
        case p: PlayException => "@" + p.id + " - "
        case _ => ""
      }, request.method, request.uri),
      ex
    )
    InternalServerError(applicationGlobal.internalServerErrorTemplate)
  }

} 
Example 53
Source File: VertexController.scala    From incubator-s2graph   with Apache License 2.0 5 votes vote down vote up
package org.apache.s2graph.rest.play.controllers

import org.apache.s2graph.core.rest.RequestParser
import org.apache.s2graph.core.storage.MutateResponse
import org.apache.s2graph.core.utils.logger
import org.apache.s2graph.core.{ExceptionHandler, GraphExceptions, S2Graph}
import org.apache.s2graph.rest.play.actors.QueueActor
import org.apache.s2graph.rest.play.config.Config
import play.api.libs.json.{JsValue, Json}
import play.api.mvc.{Controller, Result}

import scala.concurrent.Future

object VertexController extends Controller {
  private val s2: S2Graph = org.apache.s2graph.rest.play.Global.s2graph
  private val requestParser: RequestParser = org.apache.s2graph.rest.play.Global.s2parser
  private val walLogHandler: ExceptionHandler = org.apache.s2graph.rest.play.Global.wallLogHandler

  import ApplicationController._
  import ExceptionHandler._
  import play.api.libs.concurrent.Execution.Implicits._

  def tryMutates(jsValue: JsValue, operation: String, serviceNameOpt: Option[String] = None, columnNameOpt: Option[String] = None, withWait: Boolean = false): Future[Result] = {
    if (!Config.IS_WRITE_SERVER) Future.successful(Unauthorized)
    else {
      try {
        val vertices = requestParser.toVertices(jsValue, operation, serviceNameOpt, columnNameOpt)

        for (vertex <- vertices) {
          val kafkaTopic = toKafkaTopic(vertex.isAsync)
          walLogHandler.enqueue(toKafkaMessage(kafkaTopic, vertex, None))
        }

        //FIXME:
        val verticesToStore = vertices.filterNot(v => skipElement(v.isAsync))
        if (verticesToStore.isEmpty) Future.successful(jsonResponse(Json.toJson(Seq.empty[Boolean])))
        else {
          if (withWait) {
            val rets = s2.mutateVertices(verticesToStore, withWait = true).map(_.map(_.isSuccess))
            rets.map(Json.toJson(_)).map(jsonResponse(_))
          } else {
            val rets = verticesToStore.map { vertex => QueueActor.router ! vertex; true }
            Future.successful(jsonResponse(Json.toJson(rets)))
          }
        }
      } catch {
        case e: GraphExceptions.JsonParseException => Future.successful(BadRequest(s"e"))
        case e: Exception =>
          logger.error(s"[Failed] tryMutates", e)
          Future.successful(InternalServerError(s"${e.getStackTrace}"))
      }
    }
  }

  def inserts() = withHeaderAsync(jsonParser) { request =>
    tryMutates(request.body, "insert")
  }

  def insertsWithWait() = withHeaderAsync(jsonParser) { request =>
    tryMutates(request.body, "insert", withWait = true)
  }

  def insertsSimple(serviceName: String, columnName: String) = withHeaderAsync(jsonParser) { request =>
    tryMutates(request.body, "insert", Some(serviceName), Some(columnName))
  }

  def deletes() = withHeaderAsync(jsonParser) { request =>
    tryMutates(request.body, "delete")
  }

  def deletesWithWait() = withHeaderAsync(jsonParser) { request =>
    tryMutates(request.body, "delete", withWait = true)
  }

  def deletesSimple(serviceName: String, columnName: String) = withHeaderAsync(jsonParser) { request =>
    tryMutates(request.body, "delete", Some(serviceName), Some(columnName))
  }

  def deletesAll() = withHeaderAsync(jsonParser) { request =>
    tryMutates(request.body, "deleteAll")
  }

  def deletesAllSimple(serviceName: String, columnName: String) = withHeaderAsync(jsonParser) { request =>
    tryMutates(request.body, "deleteAll", Some(serviceName), Some(columnName))
  }

} 
Example 54
Source File: InvitesController.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.identities.controllers

import java.util.UUID

import com.dataengi.crm.identities.errors.InvitesControllerErrors
import cats.instances.all._
import com.dataengi.crm.common.context.types._
import com.dataengi.crm.common.controllers.ApplicationController
import com.dataengi.crm.identities.actions.SecuredFilteredAction
import com.dataengi.crm.identities.errors.AuthenticationServiceErrors
import com.dataengi.crm.identities.formatters.invites.InviteFormatter._
import com.google.inject.Inject
import com.mohiva.play.silhouette.api.Silhouette
import com.dataengi.crm.identities.formatters.invites.{InviteAdvertiserDataFormatter, InviteDataFormatter}
import com.dataengi.crm.identities.models.{Invite, InviteStatuses}
import com.dataengi.crm.identities.services.{AuthenticationService, InvitesService}
import play.api.mvc.{Action, AnyContent, ControllerComponents, Result}
import com.dataengi.crm.identities.utils.auth.DefaultEnv
import com.dataengi.crm.identities.views.html
import com.dataengi.crm.identities.views.html.error

import scala.concurrent.ExecutionContext

class InvitesController @Inject()(invitesService: InvitesService,
                                  authenticationService: AuthenticationService,
                                  val silhouette: Silhouette[DefaultEnv],
                                  components: ControllerComponents,
                                  implicit val executionContext: ExecutionContext)
    extends ApplicationController(components)
    with SecuredFilteredAction {

  def create() = SecuredAccessAction.async(parse.json(InviteDataFormatter.inviteDataFormatter)) { implicit request =>
    invitesService.create(request.body, request.identity.id.get)
  }

  def createAdvertiserInvite() =
    SecuredAccessAction.async(parse.json(InviteAdvertiserDataFormatter.inviteAdvertiserDataFormatter)) { implicit request =>
      invitesService.createAdvertiserInvite(request.body, request.identity.company.id.get, request.identity.id.get)
    }

  def getByCompany = SecuredAccessAction.async { implicit request =>
    for {
      companyId <- request.identity.company.id.toOrWithLeftError(InvitesControllerErrors.CompanyIdIsEmpty)
      invites   <- invitesService.getByCompanyId(companyId)
    } yield invites
  }

  def toSignUp(hash: UUID): Action[AnyContent] = Action.async {
    val getSignUpUrl = for {
      invite            <- invitesService.getByHash(hash).flatMap(checkStatus)
      redirectInviteUrl <- invitesService.getInviteUrl(invite)
    } yield Redirect(redirectInviteUrl)
    //    getSignUpUrl.asyncResult
    getSignUpUrl.value.map {
      case Right(result: Result) => result
      case Left(appErrorResult: ForbiddenResult) =>
        Ok(error(403, "URL is not active", appErrorResult.description))
      case Left(appErrorResult: AppErrorResult) =>
        Ok(html.error(403, "URL is not active", appErrorResult.description))
      case Left(appErrorResult: AppError) =>
        Ok(html.error(403, "URL is not active", appErrorResult.toString))
    }
  }

  private def checkStatus(invite: Invite): Or[Invite] =
    if (invite.status == InviteStatuses.Waiting)
      invite.toOr
    else
      AuthenticationServiceErrors.SignUpUrlAlreadyUsed.toErrorOrWithType[Invite]

  def all = SecuredAccessAction.async { implicit request =>
    invitesService.all()
  }

  def getByInvitedUser(invitedBy: Long) = SecuredAccessAction.async { implicit request =>
    invitesService.getByUserIdWhichInvite(invitedBy)
  }

  def remove(id: Long) = SecuredAccessAction.async { implicit request =>
    invitesService.remove(id)
  }

  def checkExistUser(email: String) = SecuredAccessAction.async { implicit request =>
    authenticationService.checkUserExist(email)
  }
} 
Example 55
Source File: PaperlessPreferencesControllerSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers

import config.ConfigDecorator
import controllers.auth.requests.UserRequest
import controllers.auth.{AuthJourney, WithActiveTabAction, WithBreadcrumbAction}
import models.{ActivatedOnlineFilerSelfAssessmentUser, NonFilerSelfAssessmentUser}
import org.mockito.Matchers._
import org.mockito.Mockito._
import org.scalatestplus.mockito.MockitoSugar
import play.api.i18n.MessagesApi
import play.api.mvc.{ActionBuilder, MessagesControllerComponents, Request, Result}
import play.api.test.FakeRequest
import play.api.test.Helpers._
import play.twirl.api.Html
import services.partials.PreferencesFrontendPartialService
import uk.gov.hmrc.auth.core.ConfidenceLevel
import uk.gov.hmrc.auth.core.retrieve.Credentials
import uk.gov.hmrc.domain.SaUtr
import uk.gov.hmrc.play.partials.HtmlPartial
import uk.gov.hmrc.renderer.TemplateRenderer
import util.UserRequestFixture.buildUserRequest
import util.{ActionBuilderFixture, BaseSpec, BetterOptionValues, LocalPartialRetriever, Tools}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{ExecutionContext, Future}

class PaperlessPreferencesControllerSpec extends BaseSpec with MockitoSugar {
  import BetterOptionValues._

  override implicit lazy val app = localGuiceApplicationBuilder().build()

  val mockPreferencesFrontendPartialService = mock[PreferencesFrontendPartialService]
  val mockAuthJourney = mock[AuthJourney]

  def controller: PaperlessPreferencesController =
    new PaperlessPreferencesController(
      mockPreferencesFrontendPartialService,
      mockAuthJourney,
      injected[WithActiveTabAction],
      injected[WithBreadcrumbAction],
      injected[MessagesControllerComponents],
      injected[Tools]
    )(mock[LocalPartialRetriever], injected[ConfigDecorator], injected[TemplateRenderer], injected[ExecutionContext]) {}

  "Calling PaperlessPreferencesController.managePreferences" should {
    "Redirect to  preferences-frontend manage paperless url when a user is logged in using GG" in {

      when(mockAuthJourney.authWithPersonalDetails).thenReturn(new ActionBuilderFixture {
        override def invokeBlock[A](request: Request[A], block: UserRequest[A] => Future[Result]): Future[Result] =
          block(
            buildUserRequest(request = request)
          )
      })

      val r = controller.managePreferences(FakeRequest())
      status(r) shouldBe SEE_OTHER

      val redirectUrl = redirectLocation(r).getValue
      val configDecorator = app.injector.instanceOf[ConfigDecorator]
      redirectUrl should include regex s"${configDecorator.preferencesFrontendService}/paperless/check-settings\\?returnUrl=.*\\&returnLinkText=.*"
    }

    "Return 400 for Verify users" in {

      when(mockAuthJourney.authWithPersonalDetails).thenReturn(new ActionBuilderFixture {
        override def invokeBlock[A](request: Request[A], block: UserRequest[A] => Future[Result]): Future[Result] =
          block(
            buildUserRequest(
              credentials = Credentials("", "Verify"),
              confidenceLevel = ConfidenceLevel.L500,
              request = request
            ))
      })

      val r = controller.managePreferences(FakeRequest())
      status(r) shouldBe BAD_REQUEST
    }
  }
} 
Example 56
Source File: FakeAuthJourney.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import controllers.auth.requests.UserRequest
import models.SelfAssessmentUserType
import play.api.mvc.{ActionBuilder, Request, Result}
import util.ActionBuilderFixture
import util.UserRequestFixture.buildUserRequest

import scala.concurrent.Future

class FakeAuthJourney(saUser: SelfAssessmentUserType) extends AuthJourney {
  private val actionBuilderFixture = new ActionBuilderFixture {
    override def invokeBlock[A](request: Request[A], block: UserRequest[A] => Future[Result]): Future[Result] =
      block(
        buildUserRequest(
          saUser = saUser,
          request = request
        ))
  }

  override val authWithPersonalDetails: ActionBuilderFixture = actionBuilderFixture
  override val authWithSelfAssessment: ActionBuilderFixture = actionBuilderFixture
  override val minimumAuthWithSelfAssessment: ActionBuilderFixture = actionBuilderFixture
} 
Example 57
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 58
Source File: UpdateAddressResponseSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import config.ConfigDecorator
import models.NonFilerSelfAssessmentUser
import org.scalatestplus.mockito.MockitoSugar
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc.Result
import play.api.mvc.Results.Ok
import play.api.test.FakeRequest
import play.api.test.Helpers._
import uk.gov.hmrc.auth.core.ConfidenceLevel
import uk.gov.hmrc.auth.core.retrieve.Credentials
import uk.gov.hmrc.http.HttpResponse
import util.UserRequestFixture.buildUserRequest
import util.BaseSpec

class UpdateAddressResponseSpec extends BaseSpec with I18nSupport with MockitoSugar {

  implicit val configDecorator: ConfigDecorator = injected[ConfigDecorator]

  override def messagesApi: MessagesApi = injected[MessagesApi]

  implicit val userRequest = buildUserRequest(
    saUser = NonFilerSelfAssessmentUser,
    credentials = Credentials("", "Verify"),
    confidenceLevel = ConfidenceLevel.L500,
    request = FakeRequest()
  )

  def genericFunc(): Result =
    Ok

  "UpdateAddressResponse.response" should {
    "return the block result for UpdateAddressSuccessResponse" in {
      val result = UpdateAddressSuccessResponse.response(genericFunc)
      status(result) shouldBe OK
    }

    "return BAD_REQUEST for UpdateAddressBadRequestResponse" in {
      val result = UpdateAddressBadRequestResponse.response(genericFunc)
      status(result) shouldBe BAD_REQUEST
    }

    "return INTERNAL_SERVER_ERROR for UpdateAddressUnexpectedResponse" in {
      val updateAddressResponse = UpdateAddressUnexpectedResponse(HttpResponse(123))
      val result = updateAddressResponse.response(genericFunc)
      status(result) shouldBe INTERNAL_SERVER_ERROR
    }

    "return INTERNAL_SERVER_ERROR for UpdateAddressErrorResponse" in {
      val updateAddressResponse = UpdateAddressErrorResponse(new RuntimeException("not used"))
      val result = updateAddressResponse.response(genericFunc)
      status(result) shouldBe INTERNAL_SERVER_ERROR
    }
  }
} 
Example 59
Source File: StartDateController.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.address

import com.google.inject.Inject
import config.ConfigDecorator
import controllers.auth.{AuthJourney, WithActiveTabAction}
import controllers.bindable.{AddrType, PostalAddrType, ResidentialAddrType}
import controllers.controllershelpers.AddressJourneyCachingHelper
import models.dto.DateDto
import models.{Address, SubmittedStartDateId}
import play.api.data.Form
import play.api.mvc.{Action, AnyContent, MessagesControllerComponents, Result}
import uk.gov.hmrc.renderer.TemplateRenderer
import util.{LanguageHelper, LocalPartialRetriever}
import views.html.interstitial.DisplayAddressInterstitialView
import views.html.personaldetails.{CannotUpdateAddressView, EnterStartDateView}

import scala.concurrent.{ExecutionContext, Future}

class StartDateController @Inject()(
  authJourney: AuthJourney,
  withActiveTabAction: WithActiveTabAction,
  cc: MessagesControllerComponents,
  cachingHelper: AddressJourneyCachingHelper,
  enterStartDateView: EnterStartDateView,
  cannotUpdateAddressView: CannotUpdateAddressView,
  displayAddressInterstitialView: DisplayAddressInterstitialView)(
  implicit partialRetriever: LocalPartialRetriever,
  configDecorator: ConfigDecorator,
  templateRenderer: TemplateRenderer,
  ec: ExecutionContext)
    extends AddressController(authJourney, withActiveTabAction, cc, displayAddressInterstitialView) {

  def onPageLoad(typ: AddrType): Action[AnyContent] =
    authenticate.async { implicit request =>
      addressJourneyEnforcer { _ => personDetails =>
        nonPostalJourneyEnforcer(typ) {
          cachingHelper.gettingCachedJourneyData(typ) { journeyData =>
            val newPostcode = journeyData.submittedAddressDto.map(_.postcode).getOrElse("").toString
            val oldPostcode = personDetails.address.flatMap(add => add.postcode).getOrElse("")
            journeyData.submittedAddressDto map { _ =>
              val postcodesMatch =
                if (newPostcode.replace(" ", "").equalsIgnoreCase(oldPostcode.replace(" ", ""))) {
                  journeyData.submittedStartDateDto.fold(dateDtoForm)(dateDtoForm.fill)
                } else {
                  dateDtoForm
                }

              Future.successful(Ok(enterStartDateView(postcodesMatch, typ)))
            } getOrElse {
              Future.successful(Redirect(routes.PersonalDetailsController.onPageLoad()))
            }
          }
        }
      }
    }

  def onSubmit(typ: AddrType): Action[AnyContent] =
    authenticate.async { implicit request =>
      addressJourneyEnforcer { _ => personDetails =>
        nonPostalJourneyEnforcer(typ) {
          dateDtoForm.bindFromRequest.fold(
            formWithErrors => {
              Future.successful(BadRequest(enterStartDateView(formWithErrors, typ)))
            },
            dateDto => {
              cachingHelper.addToCache(SubmittedStartDateId(typ), dateDto) map {
                _ =>
                  val proposedStartDate = dateDto.startDate

                  personDetails.address match {
                    case Some(Address(_, _, _, _, _, _, _, Some(currentStartDate), _, _)) =>
                      if (!currentStartDate.isBefore(proposedStartDate)) {
                        BadRequest(
                          cannotUpdateAddressView(typ, LanguageHelper.langUtils.Dates.formatDate(proposedStartDate)))
                      } else {
                        Redirect(routes.AddressSubmissionController.onPageLoad(typ))
                      }
                    case _ => Redirect(routes.AddressSubmissionController.onPageLoad(typ))
                  }
              }
            }
          )
        }
      }
    }

  private def dateDtoForm: Form[DateDto] = DateDto.form(configDecorator.currentLocalDate)

  private def nonPostalJourneyEnforcer(typ: AddrType)(block: => Future[Result]): Future[Result] =
    typ match {
      case _: ResidentialAddrType => block
      case PostalAddrType =>
        Future.successful(Redirect(controllers.address.routes.UpdateAddressController.onPageLoad(typ)))
    }
} 
Example 60
Source File: UpdateInternationalAddressController.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.address

import com.google.inject.Inject
import config.ConfigDecorator
import controllers.auth.{AuthJourney, WithActiveTabAction}
import controllers.bindable.{AddrType, PostalAddrType}
import controllers.controllershelpers.{AddressJourneyCachingHelper, CountryHelper}
import models.dto.{AddressDto, DateDto}
import models.{SubmittedAddressDtoId, SubmittedStartDateId}
import org.joda.time.LocalDate
import play.api.mvc.{Action, AnyContent, MessagesControllerComponents, Result}
import uk.gov.hmrc.play.audit.http.connector.AuditConnector
import uk.gov.hmrc.renderer.TemplateRenderer
import util.AuditServiceTools.buildAddressChangeEvent
import util.LocalPartialRetriever
import views.html.interstitial.DisplayAddressInterstitialView
import views.html.personaldetails.UpdateInternationalAddressView

import scala.concurrent.{ExecutionContext, Future}

class UpdateInternationalAddressController @Inject()(
  countryHelper: CountryHelper,
  cachingHelper: AddressJourneyCachingHelper,
  auditConnector: AuditConnector,
  authJourney: AuthJourney,
  withActiveTabAction: WithActiveTabAction,
  cc: MessagesControllerComponents,
  updateInternationalAddressView: UpdateInternationalAddressView,
  displayAddressInterstitialView: DisplayAddressInterstitialView)(
  implicit partialRetriever: LocalPartialRetriever,
  configDecorator: ConfigDecorator,
  templateRenderer: TemplateRenderer,
  ec: ExecutionContext)
    extends AddressController(authJourney, withActiveTabAction, cc, displayAddressInterstitialView) {

  def onPageLoad(typ: AddrType): Action[AnyContent] =
    authenticate.async { implicit request =>
      cachingHelper.gettingCachedJourneyData[Result](typ) { journeyData =>
        addressJourneyEnforcer { _ => personDetails =>
          typ match {
            case PostalAddrType =>
              auditConnector.sendEvent(
                buildAddressChangeEvent("postalAddressChangeLinkClicked", personDetails, isInternationalAddress = true))
              cachingHelper.enforceDisplayAddressPageVisited(journeyData.addressPageVisitedDto) {
                Future.successful(
                  Ok(
                    updateInternationalAddressView(
                      journeyData.submittedAddressDto.fold(AddressDto.internationalForm)(
                        AddressDto.internationalForm.fill),
                      typ,
                      countryHelper.countries
                    )
                  )
                )
              }

            case _ =>
              auditConnector.sendEvent(
                buildAddressChangeEvent("mainAddressChangeLinkClicked", personDetails, isInternationalAddress = true))
              cachingHelper.enforceResidencyChoiceSubmitted(journeyData) { _ =>
                Future.successful(
                  Ok(
                    updateInternationalAddressView(AddressDto.internationalForm, typ, countryHelper.countries)
                  )
                )
              }
          }
        }
      }
    }

  def onSubmit(typ: AddrType): Action[AnyContent] =
    authenticate.async { implicit request =>
      cachingHelper.gettingCachedJourneyData[Result](typ) { _ =>
        addressJourneyEnforcer { _ => _ =>
          AddressDto.internationalForm.bindFromRequest.fold(
            formWithErrors => {
              Future.successful(
                BadRequest(updateInternationalAddressView(formWithErrors, typ, countryHelper.countries)))
            },
            addressDto => {
              cachingHelper.addToCache(SubmittedAddressDtoId(typ), addressDto) flatMap { _ =>
                typ match {
                  case PostalAddrType =>
                    cachingHelper.addToCache(SubmittedStartDateId(typ), DateDto(LocalDate.now()))
                    Future.successful(Redirect(routes.AddressSubmissionController.onPageLoad(typ)))
                  case _ =>
                    Future.successful(Redirect(routes.StartDateController.onPageLoad(typ)))
                }
              }
            }
          )
        }
      }
    }
} 
Example 61
Source File: AddressController.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.address

import com.google.inject.Inject
import config.ConfigDecorator
import controllers.PertaxBaseController
import controllers.auth.{AuthJourney, WithActiveTabAction}
import controllers.auth.requests.UserRequest
import models.{Address, PersonDetails}
import play.api.mvc.{ActionBuilder, AnyContent, MessagesControllerComponents, Result}
import uk.gov.hmrc.domain.Nino
import uk.gov.hmrc.renderer.{ActiveTabYourAccount, TemplateRenderer}
import util.LocalPartialRetriever
import views.html.error
import views.html.interstitial.DisplayAddressInterstitialView

import scala.concurrent.{ExecutionContext, Future}

abstract class AddressController @Inject()(
  authJourney: AuthJourney,
  withActiveTabAction: WithActiveTabAction,
  cc: MessagesControllerComponents,
  displayAddressInterstitialView: DisplayAddressInterstitialView)(
  implicit partialRetriever: LocalPartialRetriever,
  configDecorator: ConfigDecorator,
  templateRenderer: TemplateRenderer,
  ec: ExecutionContext)
    extends PertaxBaseController(cc) {

  def authenticate: ActionBuilder[UserRequest, AnyContent] =
    authJourney.authWithPersonalDetails andThen withActiveTabAction
      .addActiveTab(ActiveTabYourAccount)

  def addressJourneyEnforcer(block: Nino => PersonDetails => Future[Result])(
    implicit request: UserRequest[_]): Future[Result] =
    (for {
      payeAccount   <- request.nino
      personDetails <- request.personDetails
    } yield {
      block(payeAccount)(personDetails)
    }).getOrElse {
      Future.successful {
        val continueUrl = configDecorator.pertaxFrontendHost + routes.PersonalDetailsController
          .onPageLoad()
          .url
        Ok(displayAddressInterstitialView(continueUrl))
      }
    }

  def internalServerError(implicit userRequest: UserRequest[_]): Result =
    InternalServerError(
      error(
        "global.error.InternalServerError500.title",
        Some("global.error.InternalServerError500.title"),
        List("global.error.InternalServerError500.message")
      ))
} 
Example 62
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 63
Source File: GetPersonDetailsAction.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import com.google.inject.Inject
import config.ConfigDecorator
import controllers.auth.requests.UserRequest
import models.PersonDetails
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc.Results.Locked
import play.api.mvc.{ActionFunction, ActionRefiner, ControllerComponents, MessagesControllerComponents, Result}
import services.partials.MessageFrontendService
import services.{CitizenDetailsService, PersonDetailsHiddenResponse, PersonDetailsSuccessResponse}
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.play.HeaderCarrierConverter
import uk.gov.hmrc.renderer.TemplateRenderer
import util.LocalPartialRetriever

import scala.concurrent.{ExecutionContext, Future}

class GetPersonDetailsAction @Inject()(
  citizenDetailsService: CitizenDetailsService,
  messageFrontendService: MessageFrontendService,
  cc: ControllerComponents,
  val messagesApi: MessagesApi)(
  implicit configDecorator: ConfigDecorator,
  partialRetriever: LocalPartialRetriever,
  ec: ExecutionContext,
  templateRenderer: TemplateRenderer)
    extends ActionRefiner[UserRequest, UserRequest] with ActionFunction[UserRequest, UserRequest] with I18nSupport {

  override protected def refine[A](request: UserRequest[A]): Future[Either[Result, UserRequest[A]]] =
    populatingUnreadMessageCount()(request).flatMap { messageCount =>
      if (!request.uri.contains("/signout")) {
        getPersonDetails()(request).map { a =>
          a.fold(
            Left(_),
            pd =>
              Right(
                UserRequest(
                  request.nino,
                  request.retrievedName,
                  request.saUserType,
                  request.credentials,
                  request.confidenceLevel,
                  pd,
                  request.trustedHelper,
                  request.profile,
                  messageCount,
                  request.activeTab,
                  request.breadcrumb,
                  request.request
                )
            )
          )
        }
      } else {
        Future.successful(
          Right(
            UserRequest(
              request.nino,
              request.retrievedName,
              request.saUserType,
              request.credentials,
              request.confidenceLevel,
              None,
              request.trustedHelper,
              request.profile,
              messageCount,
              request.activeTab,
              request.breadcrumb,
              request.request
            )
          )
        )
      }
    }

  def populatingUnreadMessageCount()(implicit request: UserRequest[_]): Future[Option[Int]] =
    messageFrontendService.getUnreadMessageCount

  private def getPersonDetails()(implicit request: UserRequest[_]): Future[Either[Result, Option[PersonDetails]]] = {

    implicit val hc: HeaderCarrier =
      HeaderCarrierConverter.fromHeadersAndSession(request.headers, Some(request.session))

    request.nino match {
      case Some(nino) =>
        citizenDetailsService.personDetails(nino).map {
          case PersonDetailsSuccessResponse(pd) => Right(Some(pd))
          case PersonDetailsHiddenResponse =>
            Left(Locked(views.html.manualCorrespondence()))
          case _ => Right(None)
        }
      case _ => Future.successful(Right(None))
    }
  }

  override protected def executionContext: ExecutionContext = cc.executionContext
} 
Example 64
Source File: WithActiveTabAction.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import controllers.auth.requests.UserRequest
import play.api.mvc.{ActionRefiner, MessagesControllerComponents, Result}
import uk.gov.hmrc.renderer.ActiveTab
import javax.inject.Inject

import scala.concurrent.{ExecutionContext, Future}

class WithActiveTabAction @Inject()(implicit ec: ExecutionContext) {

  def addActiveTab(currentActiveTab: ActiveTab): ActionRefiner[UserRequest, UserRequest] =
    new ActionRefiner[UserRequest, UserRequest] {
      override protected def refine[A](request: UserRequest[A]): Future[Either[Result, UserRequest[A]]] =
        Future.successful(
          Right(
            UserRequest(
              request.nino,
              request.retrievedName,
              request.saUserType,
              request.credentials,
              request.confidenceLevel,
              request.personDetails,
              request.trustedHelper,
              request.profile,
              request.unreadMessageCount,
              Some(currentActiveTab),
              request.breadcrumb,
              request.request
            )
          )
        )

      override protected def executionContext: ExecutionContext = ec
    }
} 
Example 65
Source File: SelfAssessmentStatusAction.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import com.google.inject.Inject
import controllers.auth.requests._
import models._
import play.api.mvc.{ActionFunction, ActionRefiner, ControllerComponents, Result}
import services.{CitizenDetailsService, EnrolmentStoreCachingService, MatchingDetailsSuccessResponse}
import uk.gov.hmrc.domain.{Nino, SaUtr}
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.play.HeaderCarrierConverter

import scala.concurrent.{ExecutionContext, Future}

class SelfAssessmentStatusAction @Inject()(
  citizenDetailsService: CitizenDetailsService,
  enrolmentsCachingService: EnrolmentStoreCachingService,
  cc: ControllerComponents)(implicit ec: ExecutionContext)
    extends ActionRefiner[AuthenticatedRequest, UserRequest] with ActionFunction[AuthenticatedRequest, UserRequest] {

  private def getSaUtrFromCitizenDetailsService(nino: Nino)(implicit hc: HeaderCarrier): Future[Option[SaUtr]] =
    citizenDetailsService.getMatchingDetails(nino) map {
      case MatchingDetailsSuccessResponse(matchingDetails) => matchingDetails.saUtr
      case _                                               => None
    }

  private def getSelfAssessmentUserType[A](
    implicit hc: HeaderCarrier,
    request: AuthenticatedRequest[A]): Future[SelfAssessmentUserType] =
    request.nino.fold[Future[SelfAssessmentUserType]](Future.successful(NonFilerSelfAssessmentUser)) { nino =>
      request.saEnrolment match {
        case Some(SelfAssessmentEnrolment(saUtr, Activated)) =>
          Future.successful(ActivatedOnlineFilerSelfAssessmentUser(saUtr))
        case Some(SelfAssessmentEnrolment(saUtr, NotYetActivated)) =>
          Future.successful(NotYetActivatedOnlineFilerSelfAssessmentUser(saUtr))
        case None =>
          getSaUtrFromCitizenDetailsService(nino).flatMap {
            case Some(saUtr) =>
              enrolmentsCachingService.getSaUserTypeFromCache(saUtr)
            case None => Future.successful(NonFilerSelfAssessmentUser)
          }
      }
    }

  override protected def refine[A](request: AuthenticatedRequest[A]): Future[Either[Result, UserRequest[A]]] = {
    implicit val hc: HeaderCarrier =
      HeaderCarrierConverter.fromHeadersAndSession(request.headers, Some(request.session))
    getSelfAssessmentUserType(hc, request).map { saType =>
      Right(
        UserRequest(
          request.nino,
          request.name,
          saType,
          request.credentials,
          request.confidenceLevel,
          None,
          request.trustedHelper,
          request.profile,
          None,
          None,
          None,
          request.request
        )
      )
    }
  }

  override protected def executionContext: ExecutionContext = cc.executionContext
} 
Example 66
Source File: WithBreadcrumbAction.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import controllers.auth.requests.UserRequest
import models.Breadcrumb
import play.api.mvc.{ActionRefiner, Result}
import com.google.inject.Inject

import scala.concurrent.{ExecutionContext, Future}

class WithBreadcrumbAction @Inject()(implicit ec: ExecutionContext) {

  def addBreadcrumb(breadcrumb: Breadcrumb): ActionRefiner[UserRequest, UserRequest] =
    new ActionRefiner[UserRequest, UserRequest] {
      override protected def refine[A](request: UserRequest[A]): Future[Either[Result, UserRequest[A]]] =
        Future.successful(
          Right(
            UserRequest(
              request.nino,
              request.retrievedName,
              request.saUserType,
              request.credentials,
              request.confidenceLevel,
              request.personDetails,
              request.trustedHelper,
              request.profile,
              request.unreadMessageCount,
              request.activeTab,
              Some(breadcrumb),
              request.request
            )
          )
        )

      override protected def executionContext: ExecutionContext = ec
    }

} 
Example 67
Source File: UpdateAddressResponse.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import config.ConfigDecorator
import controllers.auth.requests.UserRequest
import error.GenericErrors
import play.api.i18n.Messages
import play.api.mvc.Result
import uk.gov.hmrc.http.HttpResponse
import util.LocalPartialRetriever

sealed trait UpdateAddressResponse {
  def response(successResponseBlock: () => Result)(
    implicit request: UserRequest[_],
    configDecorator: ConfigDecorator,
    partialRetriever: LocalPartialRetriever,
    messages: Messages): Result =
    this match {
      case UpdateAddressBadRequestResponse    => GenericErrors.badRequest
      case UpdateAddressUnexpectedResponse(_) => GenericErrors.internalServerError
      case UpdateAddressErrorResponse(_)      => GenericErrors.internalServerError
      case UpdateAddressSuccessResponse       => successResponseBlock()
    }
}
case object UpdateAddressSuccessResponse extends UpdateAddressResponse
case object UpdateAddressBadRequestResponse extends UpdateAddressResponse
case class UpdateAddressUnexpectedResponse(r: HttpResponse) extends UpdateAddressResponse
case class UpdateAddressErrorResponse(cause: Exception) extends UpdateAddressResponse 
Example 68
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 69
Source File: GenericErrors.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package error

import config.ConfigDecorator
import controllers.auth.requests.UserRequest
import play.api.Play
import play.api.i18n.Messages
import play.api.mvc.Result
import play.api.mvc.Results.{BadRequest, InternalServerError}
import uk.gov.hmrc.renderer.TemplateRenderer
import util.LocalPartialRetriever

object GenericErrors {

  implicit val templateRenderer: TemplateRenderer = Play.current.injector.instanceOf[TemplateRenderer]

  def badRequest(
    implicit request: UserRequest[_],
    configDecorator: ConfigDecorator,
    partialRetriever: LocalPartialRetriever,
    messages: Messages): Result =
    BadRequest(
      views.html.error(
        "global.error.BadRequest.title",
        Some("global.error.BadRequest.title"),
        List("global.error.BadRequest.message1", "global.error.BadRequest.message2")))

  def internalServerError(
    implicit request: UserRequest[_],
    configDecorator: ConfigDecorator,
    partialRetriever: LocalPartialRetriever,
    messages: Messages): Result =
    InternalServerError(
      views.html.error(
        "global.error.InternalServerError500.title",
        Some("global.error.InternalServerError500.title"),
        List("global.error.InternalServerError500.message")))
} 
Example 70
Source File: SelfEmploymentEopsDeclarationResourceSpec.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package router.resources

import mocks.services.MockSelfEmploymentEopsDeclarationService
import play.api.mvc.Result
import play.api.test.FakeRequest
import router.errors.{ErrorCode, IncorrectAPIVersion, UnsupportedAPIVersion}
import support.ResourceSpec
import uk.gov.hmrc.http.HttpResponse

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class SelfEmploymentEopsDeclarationResourceSpec extends ResourceSpec
  with MockSelfEmploymentEopsDeclarationService {

  class Setup {
    val resource = new SelfEmploymentEopsDeclarationResource(
      service = mockSelfEmploymentEopsDeclarationService,
      authConnector = mockAuthConnector,
      cc = controllerComponents
    )
    mockAuthAction
  }

  val request = FakeRequest()

  "post" should {
    "return a 204 with the response headers" when {
      "the service returns a HttpResponse containing a 204 with no json response body" in new Setup {
        MockSelfEmploymentEopsDeclarationService.post()
          .returns(Future.successful(Right(HttpResponse(NO_CONTENT, None, testHeaderResponse))))

        val result: Future[Result] = resource.post("","","","")(FakeRequest().withBody(requestJson))
        status(result) shouldBe NO_CONTENT
        headers(result) shouldBe testHeader
        contentType(result) shouldBe None
      }
    }

    "return a 200 with a json response body and response headers" when {
      "the service returns a HttpResponse containing a 200 with a json response body" in new Setup {
        MockSelfEmploymentEopsDeclarationService.post()
          .returns(Future.successful(Right(HttpResponse(OK, Some(responseJson), testHeaderResponse))))

        val result: Future[Result] = resource.post("","","","")(FakeRequest().withBody(requestJson))
        status(result) shouldBe OK
        headers(result) shouldBe testHeader
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe responseJson
      }
    }

    "return a 406 with a json response body representing the error" when {
      "the service returns an IncorrectAPIVersion response" in new Setup {
        MockSelfEmploymentEopsDeclarationService.post()
          .returns(Future.successful(Left(IncorrectAPIVersion)))

        val result: Future[Result] = resource.post("","","","")(FakeRequest().withBody(requestJson))
        status(result) shouldBe NOT_ACCEPTABLE
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe ErrorCode.invalidAcceptHeader.asJson
      }
    }

    "return a 404 with a json response body representing the error" when {
      "the service returns an UnsupportedAPIVersion response" in new Setup {
        MockSelfEmploymentEopsDeclarationService.post()
          .returns(Future.successful(Left(UnsupportedAPIVersion)))

        val result: Future[Result] = resource.post("","","","")(FakeRequest().withBody(requestJson))
        status(result) shouldBe NOT_FOUND
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe ErrorCode.notFound.asJson
      }
    }
  }

} 
Example 71
Source File: BaseResource.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package router.resources

import javax.inject.Inject
import play.api.Logger
import play.api.libs.json.JsValue
import play.api.mvc.{ActionBuilder, AnyContent, BodyParser, ControllerComponents, Request, Result}
import router.errors.{ErrorCode, IncorrectAPIVersion, SelfAssessmentAPIError, UnsupportedAPIVersion}
import uk.gov.hmrc.auth.core.{AuthConnector, AuthorisationException, AuthorisedFunctions, InvalidBearerToken}
import uk.gov.hmrc.http.HttpResponse
import uk.gov.hmrc.play.bootstrap.controller.BackendController

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

class BaseResource @Inject()(cc: ControllerComponents, connector: AuthConnector) extends BackendController(cc) {

  def AuthAction: ActionBuilder[Request, AnyContent] = new ActionBuilder[Request, AnyContent] {

    private val authFunction: AuthorisedFunctions = new AuthorisedFunctions {
      override def authConnector: AuthConnector = connector
    }

    override def parser: BodyParser[AnyContent] = cc.parsers.defaultBodyParser

    override implicit protected def executionContext: ExecutionContext = cc.executionContext

    override def invokeBlock[A](request: Request[A], block: Request[A] => Future[Result]): Future[Result] = {
      implicit val req: Request[A] = request
      authFunction.authorised()(block(request)).recover{
        case _: InvalidBearerToken =>
          Logger.warn(s"[AuthorisedActions] invalid bearer token when trying to access ${request.uri}")
          Forbidden(ErrorCode.invalidBearerToken.asJson)
        case ex: AuthorisationException =>
          Logger.warn(s"[AuthorisedActions] authorisation exception caught when trying to access ${request.uri} : ${ex.reason}")
          Forbidden(ErrorCode.unauthorisedError.asJson)
      }
    }
  }

  private[resources] def buildResponse(apiResponse: HttpResponse): Result = {
    Try(apiResponse.json) match {
      case Success(_: JsValue) =>
        new Status(apiResponse.status)(apiResponse.json)
          .withHeaders(toSimpleHeaders(apiResponse.allHeaders):_*)
      case _ =>
        new Status(apiResponse.status)
          .withHeaders(toSimpleHeaders(apiResponse.allHeaders):_*)
    }
  }

  private[resources] def buildErrorResponse(error: SelfAssessmentAPIError): Result = {
    error match {
      case IncorrectAPIVersion => NotAcceptable(ErrorCode.invalidAcceptHeader.asJson)
      case UnsupportedAPIVersion => NotFound(ErrorCode.notFound.asJson)
    }
  }

  def toSimpleHeaders(headers: Map[String, Seq[String]]): Seq[(String, String)] = {
    (headers ++ Map(
      "X-Content-Type-Options" -> Seq("nosniff"),
      "Content-Type" -> Seq("application/json")
    )).flatMap { case (name, values) => values.map(name -> _) }.toSeq
  }

} 
Example 72
Source File: MockFilters.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.scaladsl.server.mocks

import java.util.concurrent.atomic.AtomicInteger

import akka.stream.Materializer
import com.lightbend.lagom.scaladsl.api.transport.Forbidden
import com.lightbend.lagom.scaladsl.api.transport.HeaderFilter
import com.lightbend.lagom.scaladsl.api.transport.RequestHeader
import com.lightbend.lagom.scaladsl.api.transport.ResponseHeader
import play.api.mvc.Filter
import play.api.mvc.Result
import play.api.mvc.{ RequestHeader => PlayRequestHeader }
import play.api.mvc.{ ResponseHeader => PlayResponseHeader }

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

// ------------------------------------------------------------------------------------------------------------
// This is a play filter that adds a header on the request and the adds a header on the response. Headers may only
// be added once so invoking this Filter twice breaks the test.
class VerboseHeaderPlayFilter(atomicInt: AtomicInteger, mt: Materializer)(implicit ctx: ExecutionContext)
    extends Filter {
  import VerboseHeaderPlayFilter._

  implicit override def mat: Materializer = mt

  override def apply(f: (PlayRequestHeader) => Future[Result])(rh: PlayRequestHeader): Future[Result] = {
    ensureMissing(rh.headers.toSimpleMap, addedOnRequest)
    val richerHeaders = rh.headers.add(addedOnRequest -> atomicInt.incrementAndGet().toString)
    val richerRequest = rh.withHeaders(richerHeaders)
    f(richerRequest).map {
      case result =>
        ensureMissing(result.header.headers, addedOnResponse)
        result.withHeaders(addedOnResponse -> atomicInt.incrementAndGet().toString)
    }
  }

  private def ensureMissing(headers: Map[String, String], key: String) =
    if (headers.get(key).isDefined) throw Forbidden(s"Header $key already exists.")
}

object VerboseHeaderPlayFilter {
  val addedOnRequest  = "addedOnRequest-play"
  val addedOnResponse = "addedOnResponse-play"
}

// ------------------------------------------------------------------------------------------------------------
// This is a Lagom HeaderFilter that adds a header on the request and the adds a header on the response.
class VerboseHeaderLagomFilter(atomicInteger: AtomicInteger) extends HeaderFilter {
  override def transformServerRequest(request: RequestHeader): RequestHeader =
    request.addHeader(VerboseHeaderLagomFilter.addedOnRequest, atomicInteger.incrementAndGet().toString)

  override def transformServerResponse(response: ResponseHeader, request: RequestHeader): ResponseHeader =
    response.addHeader(VerboseHeaderLagomFilter.addedOnResponse, atomicInteger.incrementAndGet().toString)

  override def transformClientResponse(response: ResponseHeader, request: RequestHeader): ResponseHeader = ???
  override def transformClientRequest(request: RequestHeader): RequestHeader                             = ???
}

object VerboseHeaderLagomFilter {
  val addedOnRequest  = "addedOnRequest-Lagom"
  val addedOnResponse = "addedOnResponse-Lagom"
} 
Example 73
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 74
Source File: ErrorHandler.scala    From akka-http-test   with Apache License 2.0 5 votes vote down vote up
import javax.inject._

import play.api._
import play.api.http.DefaultHttpErrorHandler
import play.api.libs.json.Json
import play.api.mvc.Results._
import play.api.mvc.{ RequestHeader, Result }
import play.api.routing.Router

import scala.concurrent.Future

@Singleton
class ErrorHandler @Inject() (env: Environment, config: Configuration, sourceMapper: OptionalSourceMapper, router: Provider[Router]) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {
  override protected def onNotFound(request: RequestHeader, message: String): Future[Result] = {
    Future.successful(NotFound(Json.obj("path" -> request.path, "messages" -> List("not found", message))))
  }

  override protected def onDevServerError(request: RequestHeader, exception: UsefulException): Future[Result] = {
    Future.successful(InternalServerError(Json.obj("path" -> request.path, "messages" -> List(exception.description))))
  }

  override protected def onProdServerError(request: RequestHeader, exception: UsefulException): Future[Result] = {
    Future.successful(InternalServerError(Json.obj("path" -> request.path, "messages" -> List(exception.description))))
  }

  override protected def onForbidden(request: RequestHeader, message: String): Future[Result] = {
    Future.successful(Forbidden(Json.obj("path" -> request.path, "messages" -> List("forbidden", message))))
  }
} 
Example 75
Source File: PlayAPISpec.scala    From playsonify   with MIT License 5 votes vote down vote up
package com.alexitc.playsonify.test

import java.net.URLEncoder

import org.scalatest.concurrent.ScalaFutures
import org.scalatestplus.play.PlaySpec
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.mvc.Result
import play.api.test.FakeRequest
import play.api.test.Helpers._
import play.api.{Application, Mode}

import scala.concurrent.Future


  def GET(url: String, extraHeaders: (String, String)*): Future[Result] = {
    val headers = JsonHeader :: extraHeaders.toList
    val request = FakeRequest("GET", url)
        .withHeaders(headers: _*)

    val response = route(application, request).get
    log(request, response)
    response
  }

  def POST(url: String, extraHeaders: (String, String)*): Future[Result] = {
    POST(url, None, extraHeaders: _*)
  }

  def POST(url: String, jsonBody: Option[String], extraHeaders: (String, String)*): Future[Result] = {
    val headers = JsonHeader :: extraHeaders.toList
    val json = jsonBody.getOrElse(EmptyJson)
    val request = FakeRequest("POST", url)
        .withHeaders(headers: _*)
        .withBody(json)

    val response = route(application, request).get
    log(request, response)
    response
  }

  def PUT(url: String, extraHeaders: (String, String)*): Future[Result] = {
    PUT(url, None, extraHeaders: _*)
  }

  def PUT(url: String, jsonBody: Option[String], extraHeaders: (String, String)*): Future[Result] = {
    val headers = JsonHeader :: extraHeaders.toList
    val json = jsonBody.getOrElse(EmptyJson)
    val request = FakeRequest("PUT", url)
        .withHeaders(headers: _*)
        .withBody(json)

    val response = route(application, request).get
    log(request, response)
    response
  }

  def DELETE(url: String, extraHeaders: (String, String)*): Future[Result] = {
    val headers = JsonHeader :: extraHeaders.toList
    val request = FakeRequest("DELETE", url)
        .withHeaders(headers: _*)

    val response = route(application, request).get
    log(request, response)

    response
  }
}

object PlayAPISpec {

  object Implicits {

    implicit class HttpExt(val params: List[(String, String)]) extends AnyVal {
      def toQueryString: String = {
        params
            .map { case (key, value) =>
              val encodedKey = URLEncoder.encode(key, "UTF-8")
              val encodedValue = URLEncoder.encode(value, "UTF-8")
              List(encodedKey, encodedValue).mkString("=")
            }
            .mkString("&")
      }
    }

    implicit class StringUrlExt(val url: String) extends AnyVal {
      def withQueryParams(params: (String, String)*): String = {
        List(url, params.toList.toQueryString).mkString("?")
      }
    }
  }
} 
Example 76
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 77
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 78
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 79
Source File: TaxCalcResourceSpec.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package router.resources

import mocks.services.MockTaxCalcService
import play.api.mvc.Result
import play.api.test.FakeRequest
import router.errors.{ErrorCode, IncorrectAPIVersion, UnsupportedAPIVersion}
import support.ResourceSpec
import uk.gov.hmrc.http.HttpResponse

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class TaxCalcResourceSpec extends ResourceSpec
  with MockTaxCalcService {

  class Setup {
    val resource = new TaxCalcResource(
      service = mockTaxCalcService,
      authConnector = mockAuthConnector,
      cc = controllerComponents
    )
    mockAuthAction
  }

  "get" should {
    "return a 200 with the response headers" when {
      "the service returns a HttpResponse containing a 200 with no json response body" in new Setup {
        MockTaxCalcService.get()
          .returns(Future.successful(Right(HttpResponse(OK, None, testHeaderResponse))))

        val result: Future[Result] = resource.get("","")(FakeRequest())
        status(result) shouldBe OK
        headers(result) shouldBe testHeader
        contentType(result) shouldBe None
      }
    }

    "return a 200 with a json response body and response headers" when {
      "the service returns a HttpResponse containing a 200 with a json response body" in new Setup {
        MockTaxCalcService.get()
          .returns(Future.successful(Right(HttpResponse(OK, Some(responseJson), testHeaderResponse))))

        val result: Future[Result] = resource.get("","")(FakeRequest())
        status(result) shouldBe OK
        headers(result) shouldBe testHeader
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe responseJson
      }
    }

    "return a 406 with a json response body representing the error" when {
      "the service returns an IncorrectAPIVersion response" in new Setup {
        MockTaxCalcService.get()
          .returns(Future.successful(Left(IncorrectAPIVersion)))

        val result: Future[Result] = resource.get("","")(FakeRequest())
        status(result) shouldBe NOT_ACCEPTABLE
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe ErrorCode.invalidAcceptHeader.asJson
      }
    }

    "return a 404 with a json response body representing the error" when {
      "the service returns an UnsupportedAPIVersion response" in new Setup {
        MockTaxCalcService.get()
          .returns(Future.successful(Left(UnsupportedAPIVersion)))

        val result: Future[Result] = resource.get("","")(FakeRequest())
        status(result) shouldBe NOT_FOUND
        contentType(result) shouldBe Some(JSON)
        contentAsJson(result) shouldBe ErrorCode.notFound.asJson
      }
    }
  }

} 
Example 80
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 81
Source File: NaptimePlayRouterTest.scala    From naptime   with Apache License 2.0 5 votes vote down vote up
package org.coursera.naptime.router2

import akka.util.ByteString
import com.google.inject.Injector
import org.coursera.naptime.resources.RootResource
import org.coursera.naptime.schema.Handler
import org.coursera.naptime.schema.HandlerKind
import org.coursera.naptime.schema.Parameter
import org.coursera.naptime.schema.Resource
import org.coursera.naptime.schema.ResourceKind
import org.junit.Test
import org.mockito.Mockito.when
import org.mockito.Matchers.any
import org.scalatest.junit.AssertionsForJUnit
import org.scalatest.mockito.MockitoSugar
import play.api.libs.streams.Accumulator
import play.api.mvc.EssentialAction
import play.api.mvc.RequestHeader
import play.api.mvc.RequestTaggingHandler
import play.api.mvc.Result
import play.api.test.FakeRequest

class NaptimePlayRouterTest extends AssertionsForJUnit with MockitoSugar {
  object FakeHandler extends  EssentialAction with RequestTaggingHandler {
    override def tagRequest(request: RequestHeader): RequestHeader = request

    override def apply(v1: RequestHeader): Accumulator[ByteString, Result] = ???
  }

  val resourceSchema = Resource(
    kind = ResourceKind.COLLECTION,
    name = "fakeResource",
    version = Some(1L),
    parentClass = Some(classOf[RootResource].getName),
    keyType = "java.lang.String",
    valueType = "FakeModel",
    mergedType = "FakeResourceModel",
    handlers = List(
      Handler(
        kind = HandlerKind.GET,
        name = "get",
        parameters =
          List(Parameter(name = "id", `type` = "String", attributes = List.empty, default = None)),
        inputBodyType = None,
        customOutputBodyType = None,
        attributes = List.empty)),
    className = "org.coursera.naptime.FakeResource",
    attributes = List.empty)

  val resourceRouter = mock[ResourceRouter]
  val resourceRouterBuilder = mock[ResourceRouterBuilder]
  when(resourceRouterBuilder.build(any())).thenReturn(resourceRouter)
  when(resourceRouterBuilder.schema).thenReturn(resourceSchema)

  val injector = mock[Injector]
  val naptimeRoutes = NaptimeRoutes(injector, Set(resourceRouterBuilder))
  val router = new NaptimePlayRouter(naptimeRoutes)

  @Test
  def simpleRouting(): Unit = {
    when(resourceRouter.routeRequest(any(), any())).thenReturn(Some(FakeHandler))
    val handler = router.handlerFor(FakeRequest())
    assert(handler.isDefined)
  }

  @Test
  def simpleRoutingNothing(): Unit = {
    when(resourceRouter.routeRequest(any(), any())).thenReturn(None)
    val handler = router.handlerFor(FakeRequest())
    assert(handler.isEmpty)
  }

  @Test
  def generateDocumentation(): Unit = {
    val documentation = router.documentation
    assert(1 === documentation.length)
    assert(
      (
        "GET --- GET",
        "/fakeResource.v1/$id",
        "[NAPTIME] org.coursera.naptime.FakeResource.get(id: String)") ===
        documentation.head)
  }
} 
Example 82
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 83
Source File: ControllerTest.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package test

import model.json.ResultMessage
import org.scalatest.{Assertion, BeforeAndAfterAll}
import org.scalatest.mockito.MockitoSugar
import org.scalatestplus.play.PlaySpec
import play.api.mvc.Result
import play.api.test.Helpers._
import play.test.WithApplication

import scala.concurrent.{Await, Future}
import scala.concurrent.duration._


  override def afterAll() {
    application.stopPlay()
  }

  def assertFutureResultStatus(future: Future[Result], status: Int) = {
    val result: Result = Await.result(future, 20 seconds)
    if(result.header.status != status){
      play.Logger.error(contentAsString(future))
    }
    assert(result.header.status == status)
  }

  def assertBodyJsonMessage(future: Future[Result], message: String, emptyExtras: Boolean): Assertion = {
    //val result: Result = Await.result(future,20 seconds)
    val bodyJson = contentAsJson(future)
    play.Logger.debug(s"BodyJson: $bodyJson")
    val jsResult = bodyJson.validate[ResultMessage]
    assert(jsResult.isSuccess)
    if(!emptyExtras) {
      assert(jsResult.get.extras.nonEmpty)
      if(jsResult.get.extras.isEmpty){
        play.Logger.debug(jsResult.toString)
      }
    }
    assert(jsResult.get.result === message)
  }

  def assertBodyJsonMessage(future: Future[Result], message: String): Assertion = {
    assertBodyJsonMessage(future, message, emptyExtras = true)
  }
} 
Example 84
Source File: ServiceTest.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package test

import org.scalatest.BeforeAndAfterAll
import org.scalatest.mockito.MockitoSugar
import org.scalatestplus.play.PlaySpec
import play.api.mvc.Result
import play.test.WithApplication
import services.state.ActionState

import scala.concurrent.{Await, Future}
import scala.concurrent.duration._


  override def afterAll() {
    application.stopPlay()
  }

  def assertState(future: Future[ActionState], actionState: ActionState) = {
    val result = Await.result(future, 20 seconds)
    assert(result === actionState)
  }

  def waitFor[T](future: Future[T]): T = {
    Await.result(future, 20 seconds)
  }
} 
Example 85
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 86
Source File: resources.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi

import cats.data.EitherT
import cats.implicits._
import play.api.Logger
import play.api.http.Status
import play.api.libs.json._
import play.api.mvc.Result
import play.api.mvc.Results.InternalServerError
import uk.gov.hmrc.vatapi.models.{AuthorisationErrorResult, ErrorResult, Errors, GenericErrorResult, InternalServerErrorResult, JsonValidationErrorResult, ValidationErrorResult}
import uk.gov.hmrc.vatapi.resources.wrappers.Response

import scala.concurrent.{ExecutionContext, Future}

package object resources {

  type BusinessResult[T] = EitherT[Future, ErrorResult, T]
  val GovTestScenarioHeader = "Gov-Test-Scenario"

  def unhandledResponse(status: Int, logger: Logger): Result = {
    logger.error(s"Unhandled response from DES. Status code: $status. Returning 500 to client.")
    InternalServerError(Json.toJson(Errors.InternalServerError("An internal server error occurred")))
  }

  def handleErrors(errorResult: ErrorResult): VatResult = {
    errorResult match {
      case GenericErrorResult(message) => VatResult.Failure(Status.BAD_REQUEST, Errors.badRequest(message))
      case JsonValidationErrorResult(errors) => VatResult.Failure(Status.BAD_REQUEST,Errors.badRequest(errors))
      case ValidationErrorResult(error) => VatResult.Failure(Status.BAD_REQUEST, Errors.badRequest(error))
      case AuthorisationErrorResult(error) => VatResult.Failure(Status.FORBIDDEN, error)
      case InternalServerErrorResult(error) => VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError(error))
    }
  }

  def validateJson[T](json: JsValue)(implicit reads: Reads[T], ec: ExecutionContext): BusinessResult[T] =
    BusinessResult {
      for {
        errors <- json.validate[T].asEither.left
      } yield JsonValidationErrorResult(errors)
    }

  def validate[T](value: T)(validate: PartialFunction[T, Errors.Error])(implicit ec: ExecutionContext): BusinessResult[T] =
    if (validate.isDefinedAt(value)) BusinessResult.failure(ValidationErrorResult(validate(value)))
    else BusinessResult.success(value)

  def authorise[T](value: T)(auth: PartialFunction[T, Errors.Error])(implicit ec: ExecutionContext): BusinessResult[T] =
    if (auth.isDefinedAt(value)) BusinessResult.failure(AuthorisationErrorResult(Errors.businessError(auth(value))))
    else BusinessResult.success(value)

  def execute[T](torun: Unit => Future[T])(implicit ec: ExecutionContext): BusinessResult[T] =
    BusinessResult {
      for {
        result <- torun(())
      } yield Right(result)
    }

  def fromDes[R <: Response](result: BusinessResult[R]): DesBusinessResult[R] = DesBusinessResult(result)

  object BusinessResult {

    def apply[T](eventuallyErrorOrResult: Future[Either[ErrorResult, T]]): BusinessResult[T] =
      new EitherT(eventuallyErrorOrResult)

    def apply[T](errorOrResult: Either[ErrorResult, T])(implicit ec: ExecutionContext): BusinessResult[T] =
      EitherT.fromEither(errorOrResult)

    def success[T](value: T)(implicit ec: ExecutionContext): BusinessResult[T] = EitherT.fromEither(Right(value))

    def failure[T](error: ErrorResult)(implicit ec: ExecutionContext): BusinessResult[T] = EitherT.fromEither(Left(error))

  }

} 
Example 87
Source File: BaseController.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.controllers

import play.api.libs.json.Json
import play.api.mvc.Result
import utils.{EndpointLogContext, Logging}
import v1.models.errors.ErrorWrapper

trait BaseController {
  self: Logging =>

  implicit class Response(result: Result) {

    def withApiHeaders(correlationId: String, responseHeaders: (String, String)*): Result = {

      val newHeaders: Seq[(String, String)] = responseHeaders ++ Seq(
        "X-CorrelationId" -> correlationId,
        "X-Content-Type-Options" -> "nosniff",
        "Content-Type" -> "application/json"
      )

      result.copy(header = result.header.copy(headers = result.header.headers ++ newHeaders))
    }
  }

  protected def getCorrelationId(errorWrapper: ErrorWrapper)(implicit endpointLogContext: EndpointLogContext): String = {
    errorWrapper.correlationId match {
      case Some(correlationId) =>
        logger.info(
          s"[${endpointLogContext.controllerName}][getCorrelationId] - " +
            s"Error received from DES ${Json.toJson(errorWrapper)} with CorrelationId: $correlationId")
        correlationId
      case None =>
        val correlationId = "No Correlation ID"
        logger.info(
          s"[${endpointLogContext.controllerName}][getCorrelationId] - " +
            s"Validation error: ${Json.toJson(errorWrapper)} with CorrelationId: $correlationId")
        correlationId
    }
  }
} 
Example 88
Source File: PaymentsController.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.controllers

import cats.data.EitherT
import cats.implicits._
import javax.inject.{Inject, Singleton}
import play.api.http.MimeTypes
import play.api.libs.json.Json
import play.api.mvc.{Action, AnyContent, ControllerComponents, Result}
import utils.{EndpointLogContext, Logging}
import v1.audit.AuditEvents
import v1.controllers.requestParsers.PaymentsRequestParser
import v1.models.audit.AuditResponse
import v1.models.errors._
import v1.models.request.payments.PaymentsRawData
import v1.services.{AuditService, EnrolmentsAuthService, PaymentsService}

import scala.concurrent.{ExecutionContext, Future}

@Singleton
class PaymentsController @Inject()(val authService: EnrolmentsAuthService,
                                   requestParser: PaymentsRequestParser,
                                   service: PaymentsService,
                                   auditService: AuditService,
                                   cc: ControllerComponents)(implicit ec: ExecutionContext)
extends AuthorisedController(cc) with BaseController with Logging {

  implicit val endpointLogContext: EndpointLogContext =
    EndpointLogContext(
      controllerName = "PaymentsController",
      endpointName = "retrievePayments"
    )

  def retrievePayments(vrn: String, from: Option[String], to: Option[String]): Action[AnyContent] =
    authorisedAction(vrn).async{ implicit request =>
      logger.info(s"[${endpointLogContext.controllerName}][${endpointLogContext.endpointName}] " +
        s"Successfully retrieved Payments from DES")

      val rawRequest: PaymentsRawData =
        PaymentsRawData(
          vrn = vrn,
          from = from,
          to = to
        )

      val result =
        for {
          parsedRequest <- EitherT.fromEither[Future](requestParser.parseRequest(rawRequest))
          serviceResponse <- EitherT(service.retrievePayments(parsedRequest))
        } yield {
          logger.info(s"[${endpointLogContext.controllerName}][${endpointLogContext.endpointName}] " +
            s"Successfully retrieved Payments from DES")

          auditService.auditEvent(AuditEvents.auditPayments(serviceResponse.correlationId,
            request.userDetails, AuditResponse(OK, Right(Some(Json.toJson(serviceResponse.responseData))))))

          Ok(Json.toJson(serviceResponse.responseData))
            .withApiHeaders(serviceResponse.correlationId)
            .as(MimeTypes.JSON)
        }

      result.leftMap{errorWrapper =>
        val correlationId = getCorrelationId(errorWrapper)
        val result = errorResult(errorWrapper).withApiHeaders(correlationId)
        logger.warn(ControllerError(endpointLogContext ,vrn, request, result.header.status, errorWrapper.error.message))

        auditService.auditEvent(AuditEvents.auditPayments(correlationId,
          request.userDetails, AuditResponse(httpStatus = result.header.status, Left(errorWrapper.auditErrors))))

        result
      }.merge

    }

  private def errorResult(errorWrapper: ErrorWrapper): Result = {
    (errorWrapper.error: @unchecked) match {
      case VrnFormatError | VrnFormatErrorDes |
           FinancialDataInvalidDateFromError | InvalidDateFromErrorDes |
           FinancialDataInvalidDateToError | InvalidDateToErrorDes |
           FinancialDataInvalidDateRangeError | InvalidDataError
      => BadRequest(Json.toJson(errorWrapper))
      case LegacyNotFoundError => NotFound(Json.toJson(errorWrapper))
      case DownstreamError => InternalServerError(Json.toJson(errorWrapper))
    }
  }
}