play.api.mvc.Request Scala Examples

The following examples show how to use play.api.mvc.Request. 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: 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 2
Source File: Roles.scala    From play-silhouette-postgres-async-seed   with Apache License 2.0 5 votes vote down vote up
package models.user

import com.mohiva.play.silhouette.api.{ Authenticator, Authorization }
import play.api.i18n._
import play.api.mvc.Request

import scala.concurrent.Future

case class WithRole(role: Role) extends Authorization[User, Authenticator] {
  override def isAuthorized[B](user: User, authenticator: Authenticator)(implicit request: Request[B], messages: Messages) = {
    Future.successful(user.roles match {
      case list: Set[Role] => list.contains(role)
      case _ => false
    })
  }
}

sealed trait Role extends Serializable {
  def name: String
}

object Role {
  def apply(role: String): Role = role match {
    case Admin.name => Admin
    case User.name => User
    case _ => Unknown
  }

  def unapply(role: Role): Option[String] = Some(role.name)

  object Admin extends Role {
    val name = "admin"
  }

  object User extends Role {
    val name = "user"
  }

  object Unknown extends Role {
    val name = "-"
  }
} 
Example 3
Source File: ActivityPerUser.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package services.contribution.feed.user

import play.api.mvc.{AnyContent, Request}
import play.api.libs.json._
import play.api.libs.functional.syntax._
import services.RuntimeAccessLevel
import services.generated.tables.records.DocumentRecord

case class ActivityPerUser(username: String, count: Long, documents: Seq[UserActivityPerDocument]) {

  def filter(docsAndPermissions: Seq[(DocumentRecord, RuntimeAccessLevel)]) = {
    val accessibleDocuments = documents.filter { activity => 
      docsAndPermissions
        .find(t => t._1.getId == activity.documentId) // Find the access level for this document
        .map(_._2.canReadData) // Check if allowed to read
        .getOrElse(false)     // Reject if not
    }

    val accessibleCount = accessibleDocuments.map(_.count).sum

    ActivityPerUser(username, accessibleCount, accessibleDocuments)
  }

  def enrich(docs: Seq[DocumentRecord])(implicit request: Request[AnyContent]) =
    ActivityPerUser(username, count, documents.map { activity => 
      val document = docs.find(_.getId == activity.documentId).get
      activity.enrich(document)
    })

}

object ActivityPerUser {

  implicit val activityPerUserWrites: Writes[ActivityPerUser] = (
    (JsPath \ "username").write[String] and
    (JsPath \ "contributions").write[Long] and 
    (JsPath \ "documents").write[Seq[UserActivityPerDocument]]
  )(unlift(ActivityPerUser.unapply))

} 
Example 4
Source File: UserActivityPerDocument.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package services.contribution.feed.user

import play.api.mvc.{AnyContent, Request}
import play.api.libs.json._
import play.api.libs.functional.syntax._
import services.generated.tables.records.DocumentRecord

trait UserActivityPerDocument {

  def documentId: String 

  def count: Long

  def enrich(doc: DocumentRecord)(implicit request: Request[AnyContent]): UserActivityPerDocument

}

object UserActivityPerDocument {

  implicit val userActivityPerDocumentWrites: Writes[UserActivityPerDocument] = (
    (JsPath \ "url").write[String] and
    (JsPath \ "title").write[String] and 
    (JsPath \ "author").writeNullable[String] and
    (JsPath \ "owner").write[String] and 
    (JsPath \ "contributions").write[Long] and
    (JsPath \ "entries").write[Seq[UserActivityFeedEntry]]
  )(_ match {
    case a: EnrichedUserActivityPerDocument => 
      (a.url, a.title, a.author, a.owner, a.count, a.entries)

    case _ =>
      // Should never happen
      throw new Exception("JSON serialization not available")
  })

}

case class RawUserActivityPerDocument(
  documentId: String,
  count: Long,
  entries: Seq[UserActivityFeedEntry]
) extends UserActivityPerDocument {

  def enrich(doc: DocumentRecord)(implicit request: Request[AnyContent]) = 
    EnrichedUserActivityPerDocument.build(documentId, count, entries, doc)

}

case class EnrichedUserActivityPerDocument(
  documentId: String,
  url: String, 
  title: String,
  author: Option[String],
  owner: String,
  count: Long, 
  entries: Seq[UserActivityFeedEntry]
) extends UserActivityPerDocument {

  // Nothing to enrich - dummy method
  def enrich(doc: DocumentRecord)(implicit request: Request[AnyContent]) = this

}

object EnrichedUserActivityPerDocument {

  def build(
    docId: String, 
    count: Long, 
    entries: Seq[UserActivityFeedEntry], 
    doc: DocumentRecord
  )(implicit request: Request[AnyContent]) =
    EnrichedUserActivityPerDocument(
      docId,
      controllers.document.routes.DocumentController.initialDocumentView(docId).absoluteURL,
      doc.getTitle,
      Option(doc.getAuthor),
      doc.getOwner,
      count,
      entries)

} 
Example 5
Source File: UserActivityFeed.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package services.contribution.feed.user

import com.sksamuel.elastic4s.searches.RichSearchResponse
import org.elasticsearch.search.aggregations.bucket.filter.InternalFilter
import org.elasticsearch.search.aggregations.bucket.histogram.InternalDateHistogram
import org.elasticsearch.search.aggregations.bucket.terms.Terms
import org.joda.time.{DateTime, DateTimeZone}
import play.api.mvc.{AnyContent, Request}
import scala.collection.JavaConverters._
import scala.concurrent.ExecutionContext
import services.ContentType
import services.contribution.{ContributionAction, ItemType}
import services.document.DocumentService
import services.user.User

object UserActivityFeed {

  private def parseAggregations(response: RichSearchResponse) = {
    val overTime = response.aggregations.getAs[InternalFilter]("over_time")
      .getAggregations.get("per_day").asInstanceOf[InternalDateHistogram]

    // Note: ES result is in ascending order, but we want descending (most recent first)
    overTime.getBuckets.asScala.toSeq.reverse.map { bucket => 
      val timestamp = new DateTime(bucket.getKey.asInstanceOf[DateTime].getMillis, DateTimeZone.UTC)

      val byUser: Seq[ActivityPerUser] = bucket.getAggregations.get("by_user").asInstanceOf[Terms]
        .getBuckets.asScala.map { bucket =>
          
          val byDocument: Seq[UserActivityPerDocument] = bucket.getAggregations.get("by_doc_id").asInstanceOf[Terms]
            .getBuckets.asScala.map { bucket => 
              // ActivityEntry is a flattened version of the three last nesting levels (action, item type and content type)  
              val entries = bucket.getAggregations.get("by_action").asInstanceOf[Terms]
                .getBuckets.asScala.flatMap { bucket => 
                  val thisAction = ContributionAction.withName(bucket.getKeyAsString)

                  bucket.getAggregations.get("by_item_type").asInstanceOf[Terms]
                    .getBuckets.asScala.flatMap { bucket => 
                      val thisType = ItemType.withName(bucket.getKeyAsString)

                      bucket.getAggregations.get("by_content_type").asInstanceOf[Terms]
                        .getBuckets.asScala.flatMap { bucket => 
                          // Content types also include "super types" ("TEXT", "IMAGE") which exist as 
                          // shorthands to simplify ES query, but are not actual valid content 
                          // types - just skip those
                          val maybeContentType = ContentType.withName(bucket.getKeyAsString)
                          maybeContentType.map { contentType => 
                            UserActivityFeedEntry(thisAction, thisType, contentType, bucket.getDocCount)
                          }
                        }
                    }
                }
              RawUserActivityPerDocument(bucket.getKeyAsString, bucket.getDocCount, entries)
            }
          ActivityPerUser(bucket.getKeyAsString, bucket.getDocCount, byDocument)
        }
      UserActivityPerDay(timestamp, bucket.getDocCount, byUser)
    }
  }

  def fromSearchResponse(
    loggedInAs: Option[String], response: RichSearchResponse
  )(implicit 
      documents: DocumentService, 
      request: Request[AnyContent],
      ctx: ExecutionContext
  ) = {
    val rawFeed = parseAggregations(response)
    
    // Get all distinct doc IDs in the feed and check if the current user has read permissions
    val docIds = rawFeed.flatMap { perDay => 
      perDay.users.flatMap { perUser => 
        perUser.documents.map { _.asInstanceOf[RawUserActivityPerDocument].documentId }
      }
    }.toSeq.distinct

    documents.getDocumentRecordsByIdWithAccessLevel(docIds, loggedInAs).map { docsAndPermissions => 
      // Filter the raw feed, so that only documents with sufficient runtime permissions show up
      val visibleFeed = rawFeed.map(_.filter(docsAndPermissions))

      // Inject document metadata (which isn't stored in ElasticSearch)
      val docs = docsAndPermissions.map(_._1)
      visibleFeed.map(_.enrich(docs))
    }
  }

} 
Example 6
Source File: UserActivityPerDay.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package services.contribution.feed.user

import org.joda.time.DateTime
import play.api.mvc.{AnyContent, Request}
import play.api.libs.json._
import play.api.libs.functional.syntax._
import services.{HasDate, HasNullableSeq, RuntimeAccessLevel}
import services.generated.tables.records.DocumentRecord

case class UserActivityPerDay(timestamp: DateTime, count: Long, users: Seq[ActivityPerUser]) {

  def filter(docsAndPermissions: Seq[(DocumentRecord, RuntimeAccessLevel)]) = {
    val filteredUsers = users
      .map(_.filter(docsAndPermissions)) // May now contain users with 0 visible edits - remove
      .filter(_.count > 0)

    val filteredCount = filteredUsers.map(_.count).sum
    UserActivityPerDay(timestamp, filteredCount, filteredUsers)
  }
    
  def enrich(docs: Seq[DocumentRecord])(implicit request: Request[AnyContent]) = 
    UserActivityPerDay(timestamp, count, users.map(_.enrich(docs)))
    
}

object UserActivityPerDay extends HasDate with HasNullableSeq {

  implicit val userActivityPerDayWrites: Writes[UserActivityPerDay] = (
    (JsPath \ "timestamp").write[DateTime] and
    (JsPath \ "contributions").write[Long] and
    (JsPath \ "users").writeNullable[Seq[ActivityPerUser]]
      .contramap(toOptSeq[ActivityPerUser])
  )(unlift(UserActivityPerDay.unapply))

} 
Example 7
Source File: ActivityFeedService.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package services.contribution.feed

import com.sksamuel.elastic4s.ElasticDsl._
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval
import play.api.mvc.{AnyContent, Request}
import services.contribution._
import services.contribution.feed.user.UserActivityFeed
import services.contribution.feed.document.DocumentActivityFeed
import services.document.DocumentService
import services.user.User
import storage.es.ES

trait ActivityFeedService { self: ContributionService =>

  def getUserActivityFeed(
    usernames: Seq[String], loggedInAs: Option[String]
  )(implicit request: Request[AnyContent], documents: DocumentService) = 
    es.client execute {
      search (ES.RECOGITO / ES.CONTRIBUTION) query {
        boolQuery
          should {
            usernames.map(username => termQuery("made_by" -> username))
          }
      } aggs (
        filterAggregation("over_time") query rangeQuery("made_at").gt("now-3M") subaggs (
          dateHistogramAggregation("per_day") field "made_at" minDocCount 0 interval DateHistogramInterval.DAY subaggs (
            termsAggregation("by_user") field "made_by" subaggs (
              termsAggregation("by_doc_id") field "affects_item.document_id" subaggs (
                termsAggregation("by_action") field "action" subaggs (
                  termsAggregation("by_item_type") field "affects_item.item_type" subaggs (
                    termsAggregation("by_content_type") field "affects_item.content_type"
                  )
                )
              )
            )
          )
        )
      ) size 0
    } flatMap { response => UserActivityFeed.fromSearchResponse(loggedInAs, response) }

  def getDocumentActivityFeed(
    docId: String
  )(implicit request: Request[AnyContent], documents: DocumentService) = 
    es.client execute {
      search (ES.RECOGITO / ES.CONTRIBUTION) query {
        termQuery("affects_item.document_id", docId)
      } aggs (
        filterAggregation("over_time") query rangeQuery("made_at").gt("now-3M") subaggs (
          dateHistogramAggregation("per_day") field "made_at" minDocCount 0 interval DateHistogramInterval.DAY subaggs (
            termsAggregation("by_user") field "made_by" subaggs (
              termsAggregation("by_part") field "affects_item.filepart_id" subaggs (
                termsAggregation("by_action") field "action" subaggs (
                  termsAggregation("by_item_type") field "affects_item.item_type"
                )
              )
            )
          )
        )
      ) size 0
    } flatMap { response => DocumentActivityFeed.fromSearchResponse(docId, response) }

} 
Example 8
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 9
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 10
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 11
Source File: DocumentActivityFeed.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package services.contribution.feed.document

import com.sksamuel.elastic4s.searches.RichSearchResponse
import java.util.UUID
import org.elasticsearch.search.aggregations.bucket.filter.InternalFilter
import org.elasticsearch.search.aggregations.bucket.histogram.InternalDateHistogram
import org.elasticsearch.search.aggregations.bucket.terms.Terms
import org.joda.time.{DateTime, DateTimeZone}
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.mvc.{AnyContent, Request}
import scala.collection.JavaConverters._
import scala.concurrent.ExecutionContext
import services.contribution.{ContributionAction, ItemType}
import services.document.{DocumentService, ExtendedDocumentMetadata}


case class DocumentActivityFeed(
  url: String, 
  title: String,
  author: Option[String],
  owner: String,
  activities: Seq[DocumentDayActivity])

object DocumentActivityFeed {

  implicit val documentActivityFeedWrites: Writes[DocumentActivityFeed] = (
    (JsPath \ "url").write[String] and
    (JsPath \ "title").write[String] and
    (JsPath \ "author").writeNullable[String] and
    (JsPath \ "owner").write[String] and
    (JsPath \ "timeline").write[Seq[DocumentDayActivity]]
  )(unlift(DocumentActivityFeed.unapply))

  private def parseAggregations(
    documentId: String,
    response: RichSearchResponse,
    doc: ExtendedDocumentMetadata
  )(implicit request: Request[AnyContent]) = {
    val overTime = response.aggregations.getAs[InternalFilter]("over_time")
      .getAggregations.get("per_day").asInstanceOf[InternalDateHistogram]

    // Note: ES result is in ascending order, but we want descending (most recent first)
    val activities = overTime.getBuckets.asScala.toSeq.reverse.map { bucket => 
      val timestamp = new DateTime(bucket.getKey.asInstanceOf[DateTime].getMillis, DateTimeZone.UTC)

      val byUser: Seq[DocumentActivityByUser] = bucket.getAggregations.get("by_user").asInstanceOf[Terms]
        .getBuckets.asScala.map { bucket =>           

          val byPart: Seq[DocumentActivityByPart] = bucket.getAggregations.get("by_part").asInstanceOf[Terms]
            .getBuckets.asScala.map { bucket => 
              // ActivityEntry is a flattened version of the two last nesting levels (action and type)
              val entries = bucket.getAggregations.get("by_action").asInstanceOf[Terms]
                .getBuckets.asScala.flatMap { bucket => 
                  val thisAction = ContributionAction.withName(bucket.getKeyAsString)

                  bucket.getAggregations.get("by_item_type").asInstanceOf[Terms]
                    .getBuckets.asScala.map { bucket => 
                      DocumentActivityFeedEntry(thisAction, ItemType.withName(bucket.getKeyAsString), bucket.getDocCount)
                    }              
                }
              DocumentActivityByPart.build(
                UUID.fromString(bucket.getKeyAsString), bucket.getDocCount, entries, doc)
            } 
          DocumentActivityByUser(bucket.getKeyAsString, bucket.getDocCount, byPart)
        }
      DocumentDayActivity(timestamp, bucket.getDocCount, byUser)
    }

    DocumentActivityFeed(
      controllers.document.routes.DocumentController.initialDocumentView(documentId).absoluteURL, 
      doc.title,
      doc.author,
      doc.ownerName,
      activities)
  }

  def fromSearchResponse(
    documentId: String, 
    response: RichSearchResponse
  )(implicit 
      request: Request[AnyContent],
      documents: DocumentService,
      ctx: ExecutionContext
  ) = documents.getExtendedMeta(documentId).map { _ match {
    case Some((doc, _)) => 
      parseAggregations(documentId, response, doc)

    case None =>
      // Should never happen - let it crash
      throw new Exception("Data integrity error: activity feed for document that is not in the DB")
  }}

} 
Example 12
Source File: TypeHelpers.scala    From CM-Well   with Apache License 2.0 5 votes vote down vote up
package cmwell.ws.util

import java.net.InetAddress
import cmwell.ws.Settings
import play.api.mvc.{Request, RequestHeader}
import play.api.http.HeaderNames


trait TypeHelpers {

  def asInt(number: String): Option[Int] = {
    //require(limit > 0, "must be positive!")
    try {
      val s = number.trim.dropWhile(_ == '0')
      require(s.forall(_.isDigit), s"Not a valid positive number format: $s")
      require(s.length < 10 || (s.length == 10 && s <= "2147483647"), s"the number $s seems to be too big") //don't try to parse something larger than MAX_INT
      Some(s.toInt)
    } catch {
      case _: NumberFormatException | _: NullPointerException => None
      case t: Throwable                                       => throw t
    }
  }

  def asLong(number: String): Option[Long] = {
    //require(limit > 0, "must be positive!")
    try {
      val s = number.trim.dropWhile(_ == '0')
      require(s.forall(_.isDigit), s"Not a valid positive number format: $s")
      //don't try to parse something larger than MAX_LONG
      require(s.length < 19 || (s.length == 19 && s <= "9223372036854775807"), s"the number $s seems to be too big")
      Some(s.toLong)
    } catch {
      case _: NumberFormatException | _: NullPointerException => None
      case t: Throwable                                       => throw t
    }
  }

  def asBoolean(s: String): Option[Boolean] = {
    if (null eq s) None
    else
      s.toLowerCase match {
        case "" | "t" | "true" | "yes" | "1" => Some(true)
        case "f" | "false" | "no" | "0"      => Some(false)
        case _                               => None
      }
  }

}

object TypeHelpers extends TypeHelpers

object RequestHelpers {

  def cmWellBase(implicit req: RequestHeader): String = {
    "http://" + req.headers
      .get(HeaderNames.HOST)
      .getOrElse(
        InetAddress.getLocalHost().getHostName() + Option(System.getProperty("application.port"))
          .map(":" + _)
          .getOrElse("")
      )
  }
} 
Example 13
Source File: HatServerProvider.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.resourceManagement

import java.io.StringWriter
import java.security.interfaces.RSAPublicKey
import javax.inject.{ Inject, Named, Singleton }

import akka.actor.ActorRef
import akka.pattern.ask
import akka.util.Timeout
import com.mohiva.play.silhouette.api.services.DynamicEnvironmentProviderService
import org.bouncycastle.util.io.pem.{ PemObject, PemWriter }
import org.hatdex.hat.api.service.RemoteExecutionContext
import org.hatdex.hat.resourceManagement.actors.HatServerProviderActor
import org.hatdex.hat.utils.LoggingProvider
import play.api.cache.{ AsyncCacheApi, NamedCache }
import play.api.Configuration
import play.api.mvc.Request

import scala.concurrent.Future
import scala.concurrent.duration._

trait HatServerProvider extends DynamicEnvironmentProviderService[HatServer] {
  def retrieve[B](request: Request[B]): Future[Option[HatServer]]
  def retrieve(hatAddress: String): Future[Option[HatServer]]
  def toString(publicKey: RSAPublicKey): String = {
    val pemObject = new PemObject("PUBLIC KEY", publicKey.getEncoded)
    val stringPemWriter = new StringWriter()
    val pemWriter: PemWriter = new PemWriter(stringPemWriter)
    pemWriter.writeObject(pemObject)
    pemWriter.flush()
    val pemPublicKey = stringPemWriter.toString
    pemPublicKey
  }
}

@Singleton
class HatServerProviderImpl @Inject() (
    configuration: Configuration,
    @NamedCache("hatserver-cache") cache: AsyncCacheApi,
    loggingProvider: LoggingProvider,
    @Named("hatServerProviderActor") serverProviderActor: ActorRef)(
    implicit
    val ec: RemoteExecutionContext) extends HatServerProvider {

  private val logger = loggingProvider.logger(this.getClass)

  def retrieve[B](request: Request[B]): Future[Option[HatServer]] = {
    val hatAddress = request.host //.split(':').headOption.getOrElse(request.host)
    retrieve(hatAddress)
  }

  implicit val timeout: Timeout = configuration.get[FiniteDuration]("resourceManagement.serverProvisioningTimeout")
  implicit val serverInfoTimeout: Duration = configuration.get[FiniteDuration]("resourceManagement.serverIdleTimeout")

  def retrieve(hatAddress: String): Future[Option[HatServer]] = {
    cache.get[HatServer](s"server:$hatAddress")
      .flatMap {
        case Some(server) => Future.successful(Some(server))
        case _ =>
          (serverProviderActor ? HatServerProviderActor.HatServerRetrieve(hatAddress)) map {
            case server: HatServer =>
              logger.debug(s"Got back server $server")
              cache.set(s"server:$hatAddress", server, serverInfoTimeout)
              Some(server)
            case error: HatServerDiscoveryException =>
              logger.warn(s"Got back error $error")
              throw error
            case message =>
              logger.warn(s"Unknown message $message from HAT Server provider actor")
              val error = new HatServerDiscoveryException("Unknown message")
              throw error
          } recoverWith {
            case e =>
              logger.warn(s"Error while retrieving HAT $hatAddress info: ${e.getMessage}")
              val error = new HatServerDiscoveryException("HAT Server info retrieval failed", e)
              throw error
          }
      }
  }

} 
Example 14
Source File: SignUpController.scala    From silhouette-vuejs-app   with Apache License 2.0 5 votes vote down vote up
package controllers

import java.util.UUID

import javax.inject.Inject
import com.mohiva.play.silhouette.api._
import forms.SignUpForm
import models.services._
import play.api.i18n.I18nSupport
import play.api.mvc.{AbstractController, AnyContent, ControllerComponents, Request}
import utils.auth.DefaultEnv

import scala.concurrent.{ExecutionContext, Future}


  def submit = silhouette.UnsecuredAction.async { implicit request: Request[AnyContent] =>
    SignUpForm.form.bindFromRequest.fold(
      _ => Future.successful(BadRequest),
      data => {
        val activationUrlProvider: UUID => String = authTokenId => routes.ActivateAccountController.activate(authTokenId).absoluteURL()

        signUpService.signUpByCredentials(data, request.remoteAddress, activationUrlProvider).map {
          case UserCreated(user) =>
            silhouette.env.eventBus.publish(SignUpEvent(user, request))
            Ok
          case UserAlreadyExists =>
            Conflict
          case InvalidRecaptchaCode =>
            BadRequest("Captcha code is not correct")
        }
      }
    )
  }
} 
Example 15
Source File: ResetPasswordController.scala    From silhouette-vuejs-app   with Apache License 2.0 5 votes vote down vote up
package controllers

import java.util.UUID

import javax.inject.Inject
import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.util.{PasswordHasherRegistry, PasswordInfo}
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import forms.ResetPasswordForm
import models.services.{AuthTokenService, UserService}
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, AnyContent, ControllerComponents, Request}
import utils.auth.DefaultEnv

import scala.concurrent.{ExecutionContext, Future}


  def submit(token: UUID) = silhouette.UnsecuredAction.async { implicit request: Request[AnyContent] =>
    authTokenService.validate(token).flatMap {
      case Some(authToken) =>
        ResetPasswordForm.form.bindFromRequest.fold(
          _ => Future.successful(BadRequest),
          password => userService.retrieveUserLoginInfo(authToken.userID, CredentialsProvider.ID).flatMap {
            case Some((user, loginInfo)) =>
              val passwordInfo = passwordHasherRegistry.current.hash(password)
              authInfoRepository.update[PasswordInfo](loginInfo, passwordInfo).map { _ =>
                Ok
              }
            case _ => Future.successful(BadRequest(Json.obj("message" -> "Reset token is either invalid or has expired. Please reset your password again.")))
          }
        )
      case None => Future.successful(BadRequest(Json.obj("message" -> "Reset token is either invalid or has expired. Please reset your password again.")))
    }
  }
} 
Example 16
Source File: SignInController.scala    From silhouette-vuejs-app   with Apache License 2.0 5 votes vote down vote up
package controllers

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.util.Clock
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import forms.SignInForm
import javax.inject.Inject
import models.services._
import play.api.Configuration
import play.api.i18n.I18nSupport
import play.api.libs.json.Json
import play.api.mvc.{AnyContent, Request}
import utils.auth.DefaultEnv

import scala.concurrent.{ExecutionContext, Future}


  def submit = silhouette.UnsecuredAction.async { implicit request: Request[AnyContent] =>
    SignInForm.form.bindFromRequest.fold(
      _ => Future.successful(BadRequest),
      data => {
        authenticateService.credentials(data.email, data.password).flatMap {
          case Success(user) =>
            val loginInfo = LoginInfo(CredentialsProvider.ID, user.email.get)
            authenticateUser(user, loginInfo, data.rememberMe)
          case InvalidPassword(attemptsAllowed) =>
            Future.successful(Forbidden(Json.obj("errorCode" -> "InvalidPassword", "attemptsAllowed" -> attemptsAllowed)))
          case NonActivatedUserEmail =>
            Future.successful(Forbidden(Json.obj("errorCode" -> "NonActivatedUserEmail")))
          case UserNotFound =>
            Future.successful(Forbidden(Json.obj("errorCode" -> "UserNotFound")))
          case ToManyAuthenticateRequests(nextAllowedAttemptTime) =>
            Future.successful(TooManyRequests(Json.obj("errorCode" -> "TooManyRequests", "nextAllowedAttemptTime" -> nextAllowedAttemptTime)))
        }
        .recover {
          case e =>
            logger.error(s"Sign in error email = ${data.email}", e)
            InternalServerError(Json.obj("errorCode" -> "SystemError"))
        }
      }
    )
  }
} 
Example 17
Source File: form_data_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
package form_data.yaml

import play.api.libs.Files.TemporaryFile
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc.{AnyContent, Request}
import de.zalando.play.controllers.PlayBodyParsing

import java.io.File
import scala.math.BigInt

import de.zalando.play.controllers.PlayPathBindables


object FormDataParser {

    def postmultipartParseForm(request: Request[AnyContent]):Either[Seq[String],(String, BothPostYear, MultipartPostAvatar)] = {
        val contentType = request.contentType.getOrElse("application/x-www-form-urlencoded")
        def fromDataParts(data: Map[String, Seq[String]], files: Map[String, Option[FilePart[TemporaryFile]]], useFiles: Boolean):Either[Seq[String],(String, BothPostYear, MultipartPostAvatar)] = {
            val name: Either[String,String] = PlayBodyParsing.fromParameters[String]("form")("name", data)
            val year: Either[String,BothPostYear] = PlayBodyParsing.fromParameters[BothPostYear]("form")("year", data)
            val avatar: Either[String,MultipartPostAvatar] = if (useFiles) PlayBodyParsing.fromFileOptional("avatar", files("avatar")) else PlayBodyParsing.fromParameters[MultipartPostAvatar]("form")("avatar", data)
            val all = Seq(name, year, avatar)
            val errors = all.filter(_.isLeft).flatMap(_.left.toSeq)
            if (errors.nonEmpty) Left(errors) else Right((name.right.toOption.get, year.right.toOption.get, avatar.right.toOption.get))
        }
        contentType.toLowerCase match {
            
            case "multipart/form-data" => request.body.asMultipartFormData.map { form =>
                val files: Map[String, Option[FilePart[TemporaryFile]]] =
                (("avatar", form.file("avatar")) :: Nil).toMap
                fromDataParts(form.dataParts, files, useFiles = true)
            }.getOrElse(Left(Seq("Could not find 'multipart/form-data' body")))
            
            case other =>
                Left(Seq("Content type " + other + " is not supported"))
        }
    }


    def postbothParseForm(request: Request[AnyContent]):Either[Seq[String],(String, BothPostYear, MultipartPostAvatar, File)] = {
        val contentType = request.contentType.getOrElse("application/x-www-form-urlencoded")
        def fromDataParts(data: Map[String, Seq[String]], files: Map[String, Option[FilePart[TemporaryFile]]], useFiles: Boolean):Either[Seq[String],(String, BothPostYear, MultipartPostAvatar, File)] = {
            val name: Either[String,String] = PlayBodyParsing.fromParameters[String]("form")("name", data)
            val year: Either[String,BothPostYear] = PlayBodyParsing.fromParameters[BothPostYear]("form")("year", data)
            val avatar: Either[String,MultipartPostAvatar] = if (useFiles) PlayBodyParsing.fromFileOptional("avatar", files("avatar")) else PlayBodyParsing.fromParameters[MultipartPostAvatar]("form")("avatar", data)
            val ringtone: Either[String,File] = if (useFiles) PlayBodyParsing.fromFileRequired("ringtone", files("ringtone")) else PlayBodyParsing.fromParameters[File]("form")("ringtone", data)
            val all = Seq(name, year, avatar, ringtone)
            val errors = all.filter(_.isLeft).flatMap(_.left.toSeq)
            if (errors.nonEmpty) Left(errors) else Right((name.right.toOption.get, year.right.toOption.get, avatar.right.toOption.get, ringtone.right.toOption.get))
        }
        contentType.toLowerCase match {
            case "application/x-www-form-urlencoded" => request.body.asFormUrlEncoded.map { form =>
                val noFiles = Map.empty[String, Option[FilePart[TemporaryFile]]]
                fromDataParts(form, noFiles, useFiles = false)
            }.getOrElse(Left(Seq("Could not find 'application/x-www-form-urlencoded' body")))
            
            case "multipart/form-data" => request.body.asMultipartFormData.map { form =>
                val files: Map[String, Option[FilePart[TemporaryFile]]] =
                (("avatar", form.file("avatar")) :: ("ringtone", form.file("ringtone")) :: Nil).toMap
                fromDataParts(form.dataParts, files, useFiles = true)
            }.getOrElse(Left(Seq("Could not find 'multipart/form-data' body")))
            
            case other =>
                Left(Seq("Content type " + other + " is not supported"))
        }
    }


    def posturl_encodedParseForm(request: Request[AnyContent]):Either[Seq[String],(String, BothPostYear, File)] = {
        val contentType = request.contentType.getOrElse("application/x-www-form-urlencoded")
        def fromDataParts(data: Map[String, Seq[String]], files: Map[String, Option[FilePart[TemporaryFile]]], useFiles: Boolean):Either[Seq[String],(String, BothPostYear, File)] = {
            val name: Either[String,String] = PlayBodyParsing.fromParameters[String]("form")("name", data)
            val year: Either[String,BothPostYear] = PlayBodyParsing.fromParameters[BothPostYear]("form")("year", data)
            val avatar: Either[String,File] = if (useFiles) PlayBodyParsing.fromFileRequired("avatar", files("avatar")) else PlayBodyParsing.fromParameters[File]("form")("avatar", data)
            val all = Seq(name, year, avatar)
            val errors = all.filter(_.isLeft).flatMap(_.left.toSeq)
            if (errors.nonEmpty) Left(errors) else Right((name.right.toOption.get, year.right.toOption.get, avatar.right.toOption.get))
        }
        contentType.toLowerCase match {
            case "application/x-www-form-urlencoded" => request.body.asFormUrlEncoded.map { form =>
                val noFiles = Map.empty[String, Option[FilePart[TemporaryFile]]]
                fromDataParts(form, noFiles, useFiles = false)
            }.getOrElse(Left(Seq("Could not find 'application/x-www-form-urlencoded' body")))
            
            case other =>
                Left(Seq("Content type " + other + " is not supported"))
        }
    }

} 
Example 18
package authentication.services

import authentication.api._
import authentication.exceptions.InvalidPasswordException
import authentication.models._
import org.mindrot.jbcrypt.BCrypt
import play.api.mvc.Request
import slick.dbio.DBIO

import scala.concurrent.ExecutionContext

private[authentication] class UsernameAndPasswordAuthenticator(
                                                       tokenGenerator: TokenGenerator[IdProfile, JwtToken],
                                                       securityUserProvider: SecurityUserProvider
                                                     )
                                                     (implicit private val ec: ExecutionContext)
  extends Authenticator[CredentialsWrapper] {

  override def authenticate(request: Request[CredentialsWrapper]): DBIO[String] = {
    require(request != null)

    val EmailAndPasswordCredentials(email, password) = request.body.user

    securityUserProvider.findByEmail(email)
      .map(securityUser => {
        if (authenticated(password, securityUser))
          tokenGenerator.generate(IdProfile(securityUser.id)).token
        else
          throw new InvalidPasswordException(email.toString)
      })
  }

  private def authenticated(givenPassword: PlainTextPassword, secUsr: SecurityUser) = {
    BCrypt.checkpw(givenPassword.value, secUsr.password.value)
  }

} 
Example 19
Source File: WebAnnotation.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.document.downloads.serializers.annotations.webannotation

import org.joda.time.DateTime
import play.api.mvc.{AnyContent, Request}
import play.api.libs.json._
import play.api.libs.functional.syntax._
import services.HasDate
import services.annotation.Annotation
import services.entity.Entity
import services.generated.tables.records.DocumentFilepartRecord

case class WebAnnotation(
  filepart: DocumentFilepartRecord,
  recogitoBaseURI: String,
  annotation: Annotation,
  entities: Seq[Entity]
)

object WebAnnotation extends HasDate {
  
  implicit def webAnnotationWrites(implicit request: Request[AnyContent]): Writes[WebAnnotation] = (
    (JsPath \ "@context").write[String] and
    (JsPath \ "id").write[String] and
    (JsPath \ "type").write[String] and
    (JsPath \ "generator").write[Generator] and
    (JsPath \ "generated").write[DateTime] and
    (JsPath \ "body").write[Seq[WebAnnotationBody]] and
    (JsPath \ "target").write[WebAnnotationTarget]
  )(a => (
    "http://www.w3.org/ns/anno.jsonld",
    s"${a.recogitoBaseURI}annotation/${a.annotation.annotationId}",
    "Annotation",
    Generator(a.recogitoBaseURI),
    DateTime.now,
    a.annotation.bodies.flatMap(b => WebAnnotationBody.fromAnnotationBody(b, a.recogitoBaseURI, a.entities)),
    WebAnnotationTarget.fromAnnotation(a.filepart, a.annotation)
  ))

} 
Example 20
Source File: PlayRequestToRawBody.scala    From tapir   with Apache License 2.0 5 votes vote down vote up
package sttp.tapir.server.play

import java.io.ByteArrayInputStream
import java.nio.charset.Charset

import akka.stream.Materializer
import akka.util.ByteString
import play.api.mvc.{RawBuffer, Request}
import play.core.parsers.Multipart
import sttp.model.Part
import sttp.tapir.{RawBodyType, RawPart}
import sttp.tapir.internal._

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

class PlayRequestToRawBody(serverOptions: PlayServerOptions) {
  def apply[R](bodyType: RawBodyType[R], charset: Option[Charset], request: Request[RawBuffer], body: ByteString)(implicit
      mat: Materializer
  ): Future[R] = {
    bodyType match {
      case RawBodyType.StringBody(defaultCharset) => Future(new String(body.toArray, charset.getOrElse(defaultCharset)))
      case RawBodyType.ByteArrayBody              => Future(body.toArray)
      case RawBodyType.ByteBufferBody             => Future(body.toByteBuffer)
      case RawBodyType.InputStreamBody            => Future(body.toArray).map(new ByteArrayInputStream(_))
      case RawBodyType.FileBody =>
        Future(java.nio.file.Files.write(serverOptions.temporaryFileCreator.create().path, body.toArray))
          .map(p => p.toFile)
      case m: RawBodyType.MultipartBody => multiPartRequestToRawBody(request, m, body)
    }
  }

  private def multiPartRequestToRawBody[R](request: Request[RawBuffer], m: RawBodyType.MultipartBody, body: ByteString)(implicit
      mat: Materializer
  ): Future[Seq[RawPart]] = {
    val bodyParser = serverOptions.playBodyParsers.multipartFormData(
      Multipart.handleFilePartAsTemporaryFile(serverOptions.temporaryFileCreator)
    )
    bodyParser.apply(request).run(body).flatMap {
      case Left(_) =>
        Future.failed(new IllegalArgumentException("Unable to parse multipart form data.")) // TODO
      case Right(value) =>
        val dataParts = value.dataParts.map {
          case (key, value) =>
            apply(
              m.partType(key).get,
              charset(m.partType(key).get),
              request,
              ByteString(value.flatMap(_.getBytes).toArray)
            ).map(body => Part(key, body).asInstanceOf[RawPart])
        }.toSeq

        val fileParts = value.files.map(f => {
          apply(
            m.partType(f.key).get,
            charset(m.partType(f.key).get),
            request,
            ByteString.apply(java.nio.file.Files.readAllBytes(f.ref.path))
          ).map(body =>
            Part(f.key, body, Map(f.key -> f.dispositionType, Part.FileNameDispositionParam -> f.filename), Nil)
              .asInstanceOf[RawPart]
          )
        })
        Future.sequence(dataParts ++ fileParts)
    }
  }
} 
Example 21
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 22
Source File: PlayRouter.scala    From caliban   with Apache License 2.0 5 votes vote down vote up
package caliban

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

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

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

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

} 
Example 23
Source File: form_data_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package form_data.yaml

import play.api.libs.Files.TemporaryFile
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc.{AnyContent, Request}
import de.zalando.play.controllers.PlayBodyParsing

import java.io.File
import scala.math.BigInt

import de.zalando.play.controllers.PlayPathBindables


object FormDataParser {

    def postmultipartParseForm(request: Request[AnyContent]):Either[Seq[String],(String, BothPostYear, MultipartPostAvatar)] = {
        val contentType = request.contentType.getOrElse("application/x-www-form-urlencoded")
        def fromDataParts(data: Map[String, Seq[String]], files: Map[String, Option[FilePart[TemporaryFile]]], useFiles: Boolean):Either[Seq[String],(String, BothPostYear, MultipartPostAvatar)] = {
            val name: Either[String,String] = PlayBodyParsing.fromParameters[String]("form")("name", data)
            val year: Either[String,BothPostYear] = PlayBodyParsing.fromParameters[BothPostYear]("form")("year", data)
            val avatar: Either[String,MultipartPostAvatar] = if (useFiles) PlayBodyParsing.fromFileOptional("avatar", files("avatar")) else PlayBodyParsing.fromParameters[MultipartPostAvatar]("form")("avatar", data)
            val all = Seq(name, year, avatar)
            val errors = all.filter(_.isLeft).flatMap(_.left.toSeq)
            if (errors.nonEmpty) Left(errors) else Right((name.right.toOption.get, year.right.toOption.get, avatar.right.toOption.get))
        }
        contentType.toLowerCase match {
            
            case "multipart/form-data" => request.body.asMultipartFormData.map { form =>
                val files: Map[String, Option[FilePart[TemporaryFile]]] =
                (("avatar", form.file("avatar")) :: Nil).toMap
                fromDataParts(form.dataParts, files, useFiles = true)
            }.getOrElse(Left(Seq("Could not find 'multipart/form-data' body")))
            
            case other =>
                Left(Seq("Content type " + other + " is not supported"))
        }
    }


    def postbothParseForm(request: Request[AnyContent]):Either[Seq[String],(String, BothPostYear, MultipartPostAvatar, File)] = {
        val contentType = request.contentType.getOrElse("application/x-www-form-urlencoded")
        def fromDataParts(data: Map[String, Seq[String]], files: Map[String, Option[FilePart[TemporaryFile]]], useFiles: Boolean):Either[Seq[String],(String, BothPostYear, MultipartPostAvatar, File)] = {
            val name: Either[String,String] = PlayBodyParsing.fromParameters[String]("form")("name", data)
            val year: Either[String,BothPostYear] = PlayBodyParsing.fromParameters[BothPostYear]("form")("year", data)
            val avatar: Either[String,MultipartPostAvatar] = if (useFiles) PlayBodyParsing.fromFileOptional("avatar", files("avatar")) else PlayBodyParsing.fromParameters[MultipartPostAvatar]("form")("avatar", data)
            val ringtone: Either[String,File] = if (useFiles) PlayBodyParsing.fromFileRequired("ringtone", files("ringtone")) else PlayBodyParsing.fromParameters[File]("form")("ringtone", data)
            val all = Seq(name, year, avatar, ringtone)
            val errors = all.filter(_.isLeft).flatMap(_.left.toSeq)
            if (errors.nonEmpty) Left(errors) else Right((name.right.toOption.get, year.right.toOption.get, avatar.right.toOption.get, ringtone.right.toOption.get))
        }
        contentType.toLowerCase match {
            case "application/x-www-form-urlencoded" => request.body.asFormUrlEncoded.map { form =>
                val noFiles = Map.empty[String, Option[FilePart[TemporaryFile]]]
                fromDataParts(form, noFiles, useFiles = false)
            }.getOrElse(Left(Seq("Could not find 'application/x-www-form-urlencoded' body")))
            
            case "multipart/form-data" => request.body.asMultipartFormData.map { form =>
                val files: Map[String, Option[FilePart[TemporaryFile]]] =
                (("avatar", form.file("avatar")) :: ("ringtone", form.file("ringtone")) :: Nil).toMap
                fromDataParts(form.dataParts, files, useFiles = true)
            }.getOrElse(Left(Seq("Could not find 'multipart/form-data' body")))
            
            case other =>
                Left(Seq("Content type " + other + " is not supported"))
        }
    }


    def posturl_encodedParseForm(request: Request[AnyContent]):Either[Seq[String],(String, BothPostYear, File)] = {
        val contentType = request.contentType.getOrElse("application/x-www-form-urlencoded")
        def fromDataParts(data: Map[String, Seq[String]], files: Map[String, Option[FilePart[TemporaryFile]]], useFiles: Boolean):Either[Seq[String],(String, BothPostYear, File)] = {
            val name: Either[String,String] = PlayBodyParsing.fromParameters[String]("form")("name", data)
            val year: Either[String,BothPostYear] = PlayBodyParsing.fromParameters[BothPostYear]("form")("year", data)
            val avatar: Either[String,File] = if (useFiles) PlayBodyParsing.fromFileRequired("avatar", files("avatar")) else PlayBodyParsing.fromParameters[File]("form")("avatar", data)
            val all = Seq(name, year, avatar)
            val errors = all.filter(_.isLeft).flatMap(_.left.toSeq)
            if (errors.nonEmpty) Left(errors) else Right((name.right.toOption.get, year.right.toOption.get, avatar.right.toOption.get))
        }
        contentType.toLowerCase match {
            case "application/x-www-form-urlencoded" => request.body.asFormUrlEncoded.map { form =>
                val noFiles = Map.empty[String, Option[FilePart[TemporaryFile]]]
                fromDataParts(form, noFiles, useFiles = false)
            }.getOrElse(Left(Seq("Could not find 'application/x-www-form-urlencoded' body")))
            
            case other =>
                Left(Seq("Content type " + other + " is not supported"))
        }
    }

} 
Example 24
Source File: DeleteActions.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.document.settings.actions

import controllers.document.settings.SettingsController
import services.RuntimeAccessLevel
import services.generated.tables.records.DocumentRecord
import services.user.Roles._
import play.api.mvc.{ AnyContent, Request }
import play.api.libs.json.Json
import scala.concurrent.Future
import scala.util.Try

trait DeleteActions { self: SettingsController =>
  
  protected def documentOwnerAction(docId: String, username: String, action: DocumentRecord => Future[Boolean]) = {
    documents.getDocumentRecordById(docId, Some(username)).flatMap(_ match {
      case Some((document, accesslevel)) => {
        if (accesslevel == RuntimeAccessLevel.OWNER) // We allow only the owner to delete a document
          action(document).map { success =>
            if (success) Ok else InternalServerError
          }
        else
          Future.successful(ForbiddenPage)
      }

      case None =>
        Future.successful(NotFoundPage) // No document with that ID found in DB
    }).recover { case t =>
      t.printStackTrace()
      InternalServerError(t.getMessage)
    }
  }

  
  def deleteAnnotations(docId: String) = self.silhouette.SecuredAction.async { implicit request =>
    documentOwnerAction(docId, request.identity.username, { document =>
      val deleteAnnotations = annotations.deleteByDocId(docId)
      val deleteContributions = contributions.deleteHistory(docId) 
      for {
        s1 <- deleteAnnotations
        s2 <- deleteContributions
      } yield (s1 && s2)
    })
  }

} 
Example 25
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 26
Source File: AnnotationsToWebAnno.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.document.downloads.serializers.annotations.webannotation

import controllers.document.downloads.serializers.BaseSerializer
import services.ContentType
import services.annotation.{AnnotationService, AnnotationBody}
import services.document.{ExtendedDocumentMetadata, DocumentService}
import services.entity.EntityType
import services.entity.builtin.EntityService
import play.api.mvc.{AnyContent, Request}
import play.api.libs.json.Json
import scala.concurrent.ExecutionContext
import storage.es.ES 

trait AnnotationsToWebAnno extends BaseSerializer {

  def documentToWebAnnotation(
    doc: ExtendedDocumentMetadata
  )(implicit 
    documentService: DocumentService,
    entityService: EntityService,
    annotationService: AnnotationService,
    request: Request[AnyContent], 
    ctx: ExecutionContext
  ) = {
    // To be used as 'generator' URI
    val recogitoURI = controllers.landing.routes.LandingController.index().absoluteURL

    val fAnnotations = annotationService.findByDocId(doc.id, 0, ES.MAX_SIZE)
    val fPlaces = entityService.listEntitiesInDocument(doc.id, Some(EntityType.PLACE), 0, ES.MAX_SIZE)

    val f = for {
      annotations <- fAnnotations
      places <- fPlaces
    } yield (annotations.map(_._1), places.items.map(_._1.entity))

    f.map { case (annotations, places) =>
      Json.toJson(annotations.map { annotation =>
        val filepart = doc.fileparts.find(_.getId == annotation.annotates.filepartId).get

        val placesOnThisAnnotation = annotation.bodies
          .filter(_.hasType == AnnotationBody.PLACE)
          .filter(_.uri.isDefined)
          .flatMap(body => {
            places.find(entity => entity.uris.contains(body.uri.get))
          })

        WebAnnotation(filepart, recogitoURI, annotation, placesOnThisAnnotation)
      })
    }
  }

} 
Example 27
Source File: WebAnnotationTarget.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.document.downloads.serializers.annotations.webannotation

import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.mvc.{ AnyContent, Request }
import services.ContentType
import services.annotation.Annotation
import services.generated.tables.records.DocumentFilepartRecord

case class WebAnnotationTarget(source: String, hasType: String, selectors: Seq[WebAnnotationSelector])

object WebAnnotationTarget {

  def fromAnnotation(filepart: DocumentFilepartRecord, annotation: Annotation)(implicit req: Request[AnyContent]) = {

    import services.ContentType._

    // Source URI is either Recogito (for uploaded content) or original source (for IIIF)
    val source = ContentType.withName(filepart.getContentType).get match {
      case IMAGE_IIIF =>
        val fileURL = filepart.getFile
        if (fileURL.endsWith("/info.json"))
          fileURL.dropRight(10)
        else 
          fileURL

      case _ => controllers.document.annotation.routes.AnnotationController
        .resolveFromPart(annotation.annotates.filepartId).absoluteURL
    }

    annotation.annotates.contentType match {
      // Plaintest gets a Text target with two alternative selectors: TextQuote + TextPosition
      case TEXT_PLAIN =>
        WebAnnotationTarget(source, "Text", Seq(
          TextPositionSelector.fromAnnotation(annotation),
          TextQuoteSelector.fromAnnotation(annotation)))

      // TODO TEI gets a Text target with two alternative selectors: TextQuote + XPath Range
      case TEXT_TEIXML =>
        WebAnnotationTarget(source, "Text", Seq(
          TextQuoteSelector.fromAnnotation(annotation),
          XPathRangeSelector.fromAnnotation(annotation)))

      // Images get an Image target with a fragment selector
      case IMAGE_UPLOAD | IMAGE_IIIF =>
        WebAnnotationTarget(source, "Image", Seq(ImageFragmentSelector.fromAnnotation(annotation)))

      // CSV gets a Dataset target with a Data Position selector
      case DATA_CSV  =>
        WebAnnotationTarget(source, "Dataset", Seq(TableFragmentSelector.fromAnnotation(annotation)))

      case c =>
        // Should never happen
        throw new IllegalArgumentException(s"Unable to create Web Annotation target for content type ${c}")
    }

  }

  implicit val webAnnotationTargetWrites: Writes[WebAnnotationTarget] = (
    (JsPath \ "source").write[String] and
    (JsPath \ "type").write[String] and
    (JsPath \ "selector").write[Seq[WebAnnotationSelector]]
  )(t => (t.source, t.hasType, t.selectors))

} 
Example 28
Source File: DocumentActivityByPart.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package services.contribution.feed.document

import java.util.UUID
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.mvc.{AnyContent, Request}
import services.document.ExtendedDocumentMetadata

case class DocumentActivityByPart(
  url: String, 
  partTitle: String,
  partSequenceNumber: Int,
  count: Long, 
  entries: Seq[DocumentActivityFeedEntry])

object DocumentActivityByPart {

  def build(
    partId: UUID, 
    count: Long, 
    entries: Seq[DocumentActivityFeedEntry], 
    doc: ExtendedDocumentMetadata
  )(implicit request: Request[AnyContent]) = {
    val part = doc.fileparts.find(_.getId == partId).get
    val url = controllers.document.annotation.routes.AnnotationController.showAnnotationView(doc.id, part.getSequenceNo).absoluteURL
    DocumentActivityByPart(url, part.getTitle, part.getSequenceNo, count, entries)
  }

  implicit val documentActivityByPartWrites: Writes[DocumentActivityByPart] = (
    (JsPath \ "url").write[String] and
    (JsPath \ "title").write[String] and
    (JsPath \ "sequence_number").write[Int] and
    (JsPath \ "contributions").write[Long] and 
    (JsPath \ "entries").write[Seq[DocumentActivityFeedEntry]]
  )(unlift(DocumentActivityByPart.unapply))

} 
Example 29
Source File: AnnotationList.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.document.downloads.serializers.annotations.annotationlist

import play.api.mvc.{AnyContent, Request}
import play.api.libs.json._
import play.api.libs.functional.syntax._

case class AnnotationList(id: String, resources: Seq[AnnotationResource])

object AnnotationList {
    
  implicit def annotationListWrites(implicit request: Request[AnyContent]): Writes[AnnotationList] = (
    (JsPath \ "@context").write[String] and
    (JsPath \ "@id").write[String] and
    (JsPath \ "@type").write[String] and
    (JsPath \ "resources").write[Seq[AnnotationResource]]
  )(a => (
    "http://iiif.io/api/presentation/2/context.json",
    a.id,
    "sc:AnnotationList",
    a.resources
  ))

} 
Example 30
Source File: AnnotationsToAnnotationList.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.document.downloads.serializers.annotations.annotationlist

import controllers.document.downloads.serializers.BaseSerializer
import services.ContentType
import services.annotation.{Annotation, AnnotationService}
import services.document.{ExtendedDocumentMetadata, DocumentService}
import play.api.mvc.{AnyContent, Request}
import play.api.libs.json.Json
import scala.concurrent.ExecutionContext

trait AnnotationsToAnnotationList extends BaseSerializer {

  private def toAnnotationResource(baseURI: String, annotation: Annotation) = 
    AnnotationResource(
      s"${baseURI}/annotation/${annotation.annotationId}", 
      "[annotation text goes here]", 
      s"${baseURI}/document/${annotation.annotates.documentId}"
    )

  def documentToIIIF2(doc: ExtendedDocumentMetadata)(implicit documentService: DocumentService,
      annotationService: AnnotationService, request: Request[AnyContent], ctx: ExecutionContext) = {

    // To be used as 'generator' URI
    val recogitoURI = controllers.landing.routes.LandingController.index().absoluteURL
    val listId = s"${recogitoURI}/api/document/${doc.id}/iiif/annotations"

    annotationService.findByDocId(doc.id).map { annotations =>
      Json.toJson(AnnotationList(listId, annotations.map(t => toAnnotationResource(recogitoURI, t._1))))
    }
  }

} 
Example 31
Source File: SearchController.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.my.directory.search

import controllers.{Security, HasPrettyPrintJSON}
import controllers.my.directory.ConfiguredPresentation
import com.mohiva.play.silhouette.api.Silhouette
import javax.inject.{Inject, Singleton}
import org.joda.time.DateTime
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.mvc.{AnyContent, Request, AbstractController, ControllerComponents}
import scala.concurrent.{ExecutionContext, Future}
import scala.util.Try
import services.HasDate
import services.document.DocumentService
import services.document.search._

@Singleton
class SearchController @Inject() (
  components: ControllerComponents,
  silhouette: Silhouette[Security.Env],
  documentService: DocumentService,
  implicit val ctx: ExecutionContext
) extends AbstractController(components) 
    with HasPrettyPrintJSON
    with HasDate {

  import ConfiguredPresentation._

  implicit val searchOptionsReads: Reads[SearchArgs] = (
    (JsPath \ "q").readNullable[String] and
    (JsPath \ "in").readNullable[String]
      .map(_.flatMap(Scope.withName).getOrElse(Scope.ALL)) and
    (JsPath \ "type").readNullable[String]
      .map(_.flatMap(DocumentType.withName)) and
    (JsPath \ "owner").readNullable[String] and
    (JsPath \ "max_age").readNullable[DateTime]
  )(SearchArgs.apply _) 

  private def parseQueryString(params: Map[String, String]) = 
    params.get("q").map { q => // Require at least a query phrase
      SearchArgs(
        Some(q),
        params.get("in").flatMap(Scope.withName).getOrElse(Scope.ALL),
        params.get("type").flatMap(DocumentType.withName),
        params.get("owner"),
        params.get("max_age").flatMap(parseDate)
      ) 
    }

  def parseSearchArgs(request: Request[AnyContent]) = request.body.asJson match {
    case Some(json) =>
      Try(Json.fromJson[SearchArgs](json).get).toOption

    case None => // Try query string instead
      val asMap = request.queryString
        .mapValues(_.headOption)
        .filter(_._2.isDefined)
        .mapValues(_.get)
      parseQueryString(asMap)
  }
  
  
  def search = silhouette.UserAwareAction.async { implicit request =>
    parseSearchArgs(request) match {
      case Some(args) => 
        documentService.search(request.identity.map(_.username), args).map { documents => 
          val presentation = ConfiguredPresentation.forMyDocument(documents, None, None)
          jsonOk(Json.toJson(presentation))
        }

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

} 
Example 32
Source File: SortByDB.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.my.directory.list.document

import controllers.my.directory._
import controllers.my.directory.list.DirectoryController
import java.util.UUID
import play.api.libs.json.Json
import play.api.mvc.{AnyContent, Request}
import scala.concurrent.{ExecutionContext, Future}
import services.{Page, SortOrder}
import services.document.DocumentService
import services.generated.tables.records.DocumentRecord

trait SortByDB { self: DirectoryController =>

  
  protected def getSharedDocumentsSortedByDB(
    username: String,
    folder: Option[UUID],
    offset: Int, 
    size: Int, 
    config: Option[PresentationConfig]
  )(implicit request: Request[AnyContent]) = {   
    documentsByDB(
      config, 
      () => documents.listDocumentsSharedWithMe(
              username, folder, offset, size,
              config.flatMap(_.sort.map(_.sortBy)), 
              config.flatMap(_.sort.map(_.order)))
    ).map { case (sharedDocs, indexProperties) =>
      ConfiguredPresentation.forSharedDocument(sharedDocs, indexProperties.map(_.toMap), config.map(_.columns))
    }
  }

  protected def getAccessibleDocumentsSortedByDB(
    owner: String, 
    folder: Option[UUID],
    loggedIn: Option[String],
    offset: Int,
    size: Int,
    config: Option[PresentationConfig]
  )(implicit request: Request[AnyContent]) = {
    documentsByDB(
      config,
      () => documents.listAccessibleDocuments(
              owner, folder, loggedIn, offset, size,
              config.flatMap(_.sort.map(_.sortBy)),
              config.flatMap(_.sort.map(_.order)))
    ).map { case (documents, indexProperties) =>
      ConfiguredPresentation.forAccessibleDocument(documents, indexProperties.map(_.toMap), config.map(_.columns))
    }
  }

} 
Example 33
Source File: SortByIndex.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.my.directory.list.document

import controllers.my.directory._
import controllers.my.directory.list.DirectoryController
import java.util.UUID
import play.api.libs.json.Json
import play.api.mvc.{AnyContent, Request}
import scala.concurrent.Future
import services.{ContentType, Page}

trait SortByIndex { self: DirectoryController =>

  private def sortByIndexProperty(
    docIds: Seq[String], 
    sort: Sorting,
    offset: Int, 
    size: Int
  ): Future[Seq[String]] = {
    if (docIds.isEmpty) { // Just being defensive here
      Future.successful(docIds)
    } else {
      sort.sortBy match {
        case "last_edit_at" => contributions.sortDocsByLastModifiedAt(docIds, sort.order, offset, size)
        case "last_edit_by" => contributions.sortDocsByLastModifiedBy(docIds, sort.order, offset, size)
        case "annotations" => annotations.sortDocsByAnnotationCount(docIds, sort.order, offset, size)
        case _ => Future.successful(docIds)
      }
    }
  }

  protected def getMyDocumentsSortedByIndex(
    username: String,
    folder: Option[UUID],
    offset: Int, 
    size: Int,
    config: PresentationConfig
  )(implicit request: Request[AnyContent]) = {
    val startTime = System.currentTimeMillis

    val f = for {
      allIds <- documents.listIds(folder, username)
      sortedIds <- sortByIndexProperty(allIds, config.sort.get, offset, size)
      documents <- documents.getDocumentsById(sortedIds)
      indexProperties <- fetchIndexProperties(sortedIds, config)      
    } yield (allIds, sortedIds, documents, indexProperties)

    f.map { case (allIds, sortedIds, documents, indexProperties) => 
      val dbResult = Page(System.currentTimeMillis - startTime, allIds.size, offset, size, documents)
      ConfiguredPresentation.forMyDocument(dbResult, Some(indexProperties.toMap), Some(config.columns))
    }
  }

  protected def getSharedDocumentsSortedByIndex(
    username: String,
    folder: Option[UUID],
    offset: Int, 
    size: Int,
    config: PresentationConfig
  )(implicit request: Request[AnyContent]) = {
    val startTime = System.currentTimeMillis

    val f = for {
      allIds <- documents.listIdsSharedWithMe(username, folder)
      sortedIds <- sortByIndexProperty(allIds, config.sort.get, offset, size)
      documents <- documents.getDocsSharedWithMeById(sortedIds, username)
      indexProperties <- fetchIndexProperties(sortedIds, config)
    } yield (allIds, sortedIds, documents, indexProperties)

    f.map { case (allIds, sortedIds, documents, indexProperties) =>
      val dbResult = Page(System.currentTimeMillis - startTime, allIds.size, offset, size, documents)
      ConfiguredPresentation.forSharedDocument(dbResult, Some(indexProperties.toMap), Some(config.columns))
    }
  }

  protected def getAccessibleDocumentsSortedByIndex(
    owner: String, 
    folder: Option[UUID],
    loggedIn: Option[String],
    offset: Int,
    size: Int,
    config: PresentationConfig
  )(implicit request: Request[AnyContent]) = {
    val startTime = System.currentTimeMillis

    val f = for {
      allIds <- documents.listAccessibleIds(owner, folder, loggedIn)
      sortedIds <- sortByIndexProperty(allIds, config.sort.get, offset, size)
      documents <- documents.getDocumentsById(sortedIds)
      indexProperties <- fetchIndexProperties(sortedIds, config)
    } yield (allIds, sortedIds, documents, indexProperties)

    f.map { case (allIds, sortedIds, documents, indexProperties) =>
      // TODO fetch with sharing permissions, if any
      val dbResult = Page(System.currentTimeMillis - startTime, allIds.size, offset, size, documents)
      ConfiguredPresentation.forMyDocument(dbResult, Some(indexProperties.toMap), Some(config.columns))
    }
  }

} 
Example 34
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 35
Source File: MockDividendsService.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package mocks.services

import mocks.Mock
import org.mockito.stubbing.OngoingStubbing
import org.scalatest.Suite
import play.api.libs.json.JsValue
import play.api.mvc.Request
import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome
import router.services.DividendsService
import uk.gov.hmrc.http.HeaderCarrier

import scala.concurrent.Future

trait MockDividendsService extends Mock { _: Suite =>

  val mockDividendsService = mock[DividendsService]

  object MockDividendsService {

    def put(body: JsValue): OngoingStubbing[Future[SelfAssessmentOutcome]] = {
      when(mockDividendsService.put(eqTo(body))(any[HeaderCarrier](), any[Request[_]]()))
    }

    def get(): OngoingStubbing[Future[SelfAssessmentOutcome]] = {
      when(mockDividendsService.get()(any[HeaderCarrier](), any[Request[_]]()))
    }
  }

  override protected def beforeEach(): Unit = {
    super.beforeEach()
    reset(mockDividendsService)
  }
} 
Example 36
Source File: UserRequestFixture.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package util

import controllers.auth.requests.UserRequest
import models._
import play.api.mvc.Request
import uk.gov.hmrc.auth.core.ConfidenceLevel
import uk.gov.hmrc.auth.core.retrieve.v2.TrustedHelper
import uk.gov.hmrc.auth.core.retrieve.{Credentials, Name}
import uk.gov.hmrc.domain.{Nino, SaUtr, SaUtrGenerator}

object UserRequestFixture {

  def buildUserRequest[A](
    nino: Option[Nino] = Some(Fixtures.fakeNino),
    userName: Option[UserName] = Some(UserName(Name(Some("Firstname"), Some("Lastname")))),
    saUser: SelfAssessmentUserType = ActivatedOnlineFilerSelfAssessmentUser(SaUtr(new SaUtrGenerator().nextSaUtr.utr)),
    credentials: Credentials = Credentials("", UserDetails.GovernmentGatewayAuthProvider),
    confidenceLevel: ConfidenceLevel = ConfidenceLevel.L200,
    personDetails: Option[PersonDetails] = Some(Fixtures.buildPersonDetails),
    trustedHelper: Option[TrustedHelper] = None,
    profile: Option[String] = None,
    messageCount: Option[Int] = None,
    request: Request[A]): UserRequest[A] =
    UserRequest(
      nino,
      userName,
      saUser,
      credentials,
      confidenceLevel,
      personDetails,
      trustedHelper,
      profile,
      messageCount,
      None,
      None,
      request)

} 
Example 37
Source File: CustomAuthenticator.scala    From playsonify   with MIT License 5 votes vote down vote up
package com.alexitc.playsonify.play.common

import com.alexitc.playsonify.core.FutureApplicationResult
import com.alexitc.playsonify.play.AbstractAuthenticatorService
import org.scalactic.{One, Or}
import play.api.libs.json.JsValue
import play.api.mvc.Request
import play.api.test.Helpers.AUTHORIZATION

import scala.concurrent.Future

class CustomAuthenticator extends AbstractAuthenticatorService[CustomUser] {

  override def authenticate(request: Request[JsValue]): FutureApplicationResult[CustomUser] = {
    val header = request
        .headers
        .get(AUTHORIZATION)
        .map(CustomUser.apply)

    val result = Or.from(header, One(CustomError.FailedAuthError))
    Future.successful(result)
  }
} 
Example 38
Source File: DummyAuthenticatorService.scala    From playsonify   with MIT License 5 votes vote down vote up
package com.alexitc.example

import com.alexitc.playsonify.core.FutureApplicationResult
import com.alexitc.playsonify.play.AbstractAuthenticatorService
import org.scalactic.{One, Or}
import play.api.http.HeaderNames
import play.api.libs.json.JsValue
import play.api.mvc.Request

import scala.concurrent.Future
import scala.util.Try

class DummyAuthenticatorService extends AbstractAuthenticatorService[Int] {

  override def authenticate(request: Request[JsValue]): FutureApplicationResult[Int] = {
    val userIdMaybe = request
      .headers
      .get(HeaderNames.AUTHORIZATION)
      .flatMap { header => Try(header.toInt).toOption }

    val result = Or.from(userIdMaybe, One(SimpleAuthError.InvalidAuthorizationHeader))
    Future.successful(result)
  }
} 
Example 39
Source File: RestContextTest.scala    From naptime   with Apache License 2.0 5 votes vote down vote up
package org.coursera.naptime

import org.junit.Test
import play.api.i18n.Lang
import play.api.mvc.Request
import org.mockito.Mockito.when
import org.scalatest.junit.AssertionsForJUnit
import org.scalatest.mockito.MockitoSugar

class RestContextTest extends AssertionsForJUnit with MockitoSugar {

  private[this] def makeContext(languagePreferences: Seq[Lang]): RestContext[Unit, Unit] = {
    val mockRequest = mock[Request[Unit]]
    val restContext = new RestContext((), (), mockRequest, null, null, null)
    when(mockRequest.acceptLanguages).thenReturn(languagePreferences)
    restContext
  }

  def test(
      requestLanguages: Seq[Lang],
      availableLanguages: Set[Lang],
      defaultLanguage: Lang,
      expected: Lang): Unit = {
    val restContext = makeContext(requestLanguages)
    assert(restContext.selectLanguage(availableLanguages, defaultLanguage) === expected)
  }

  @Test
  def basicLanguage(): Unit = {
    test(
      requestLanguages = Seq(Lang("en")),
      availableLanguages = Set(Lang("fr"), Lang("en")),
      defaultLanguage = Lang("en"),
      expected = Lang("en"))
  }

  @Test
  def defaultFallback(): Unit = {
    test(
      requestLanguages = Seq(Lang("zh")),
      availableLanguages = Set(Lang("fr"), Lang("en")),
      defaultLanguage = Lang("en"),
      expected = Lang("en"))
  }

  @Test
  def choosePreferred(): Unit = {
    test(
      requestLanguages = Seq(Lang("zh"), Lang("fr"), Lang("en")),
      availableLanguages = Set(Lang("fr"), Lang("en")),
      defaultLanguage = Lang("en"),
      expected = Lang("fr"))
  }
} 
Example 40
Source File: AuditService.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.services

import javax.inject.Inject
import org.joda.time.{DateTime, DateTimeZone}
import play.api.Logger
import play.api.libs.json.{Json, Writes}
import play.api.mvc.Request
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.play.audit.AuditExtensions
import uk.gov.hmrc.play.audit.http.connector.AuditConnector
import uk.gov.hmrc.play.audit.model.ExtendedDataEvent
import uk.gov.hmrc.vatapi.models.audit.AuditEvent
import uk.gov.hmrc.vatapi.resources.BusinessResult

import scala.concurrent.ExecutionContext

class AuditService @Inject()(auditConnector: AuditConnector) {

  val logger: Logger = Logger(this.getClass)

  def audit[T](event: AuditEvent[T])(
    implicit hc: HeaderCarrier,
    fmt: Writes[T],
    request: Request[_],
    ec: ExecutionContext
  ): BusinessResult[Unit] = {

    logger.debug(s"[AuditService][audit] Generating ${event.auditType} audit event for vat-api.")

    val auditEvent =
      ExtendedDataEvent(
        auditSource = "vat-api",
        auditType = event.auditType,
        tags = AuditExtensions.auditHeaderCarrier(hc).toAuditTags(event.transactionName, request.path),
        detail = Json.toJson(event.detail),
        generatedAt = DateTime.now(DateTimeZone.UTC)
      )

    BusinessResult.success(auditConnector.sendExtendedEvent(auditEvent))

  }

} 
Example 41
Source File: ApplicationGlobal.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.config

import com.typesafe.config.Config
import net.ceedubs.ficus.Ficus._
import play.api.Mode.Mode
import play.api.i18n.{I18nSupport, Messages, MessagesApi}
import play.api.mvc.Request
import play.api.{Application, Configuration, Play}
import play.twirl.api.Html
import uk.gov.hmrc.crypto.ApplicationCrypto
import uk.gov.hmrc.nisp.config.wiring.NispAuditConnector
import uk.gov.hmrc.nisp.controllers.NispFrontendController
import uk.gov.hmrc.nisp.controllers.partial.PartialRetriever
import uk.gov.hmrc.play.config.{AppName, ControllerConfig, RunMode}
import uk.gov.hmrc.play.frontend.bootstrap.DefaultFrontendGlobal
import uk.gov.hmrc.play.frontend.filters.{FrontendAuditFilter, FrontendLoggingFilter, MicroserviceFilterSupport}

object ApplicationGlobal extends ApplicationGlobalTrait {
  override protected def mode: Mode = Play.current.mode
  override protected def runModeConfiguration: Configuration = Play.current.configuration
  override def messagesApi = Play.current.injector.instanceOf[MessagesApi]
}

trait ApplicationGlobalTrait extends DefaultFrontendGlobal with RunMode with PartialRetriever with NispFrontendController with I18nSupport {

  implicit lazy val app:Application = Play.current

  override val auditConnector = NispAuditConnector
  override val loggingFilter = NispLoggingFilter
  override val frontendAuditFilter = NispFrontendAuditFilter

  override def onStart(app: Application) {
    super.onStart(app)
    new ApplicationCrypto(Play.current.configuration.underlying).verifyConfiguration()
  }

  override def internalServerErrorTemplate(implicit request: Request[_]): Html =
    uk.gov.hmrc.nisp.views.html.service_error_500()

  override def standardErrorTemplate(pageTitle: String, heading: String, message: String)(implicit request: Request[_]): Html =
    uk.gov.hmrc.nisp.views.html.global_error(pageTitle, heading, message)

  override def notFoundTemplate(implicit request: Request[_]): Html = {
    uk.gov.hmrc.nisp.views.html.page_not_found_template()
  }

  override def microserviceMetricsConfig(implicit app: Application): Option[Configuration] = app.configuration.getConfig(s"microservice.metrics")
}

object ControllerConfiguration extends ControllerConfig {
  lazy val controllerConfigs = Play.current.configuration.underlying.as[Config]("controllers")
}

object NispLoggingFilter extends FrontendLoggingFilter with MicroserviceFilterSupport {
  override def controllerNeedsLogging(controllerName: String): Boolean = ControllerConfiguration.paramsForController(controllerName).needsLogging
}

object NispFrontendAuditFilter extends FrontendAuditFilter with RunMode with AppName with MicroserviceFilterSupport {
  override lazy val maskedFormFields = Seq.empty
  override lazy val applicationPort = None
  override lazy val auditConnector = NispAuditConnector
  override def controllerNeedsAuditing(controllerName: String): Boolean = ControllerConfiguration.paramsForController(controllerName).needsAuditing
  override protected def mode: Mode = Play.current.mode
  override protected def runModeConfiguration: Configuration = Play.current.configuration
  override protected def appNameConfiguration: Configuration = Play.current.configuration
} 
Example 42
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 43
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 44
Source File: NispBreadcrumb.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.utils

import play.api.i18n.Messages
import play.api.mvc.Request
import uk.gov.hmrc.nisp.config.ApplicationConfig
import uk.gov.hmrc.nisp.controllers.routes
import uk.gov.hmrc.play.breadcrumb.model.{Breadcrumb, BreadcrumbItem}

object NispBreadcrumb extends NispBreadcrumb {
  override lazy val applicationConfig = ApplicationConfig
}

trait NispBreadcrumb{

  val applicationConfig: ApplicationConfig

  def initialBreadCrumbList(implicit messages: Messages) = List((messages("nisp.breadcrumb.account"), applicationConfig.pertaxFrontendUrl))

  lazy val mainContentHeaderPartialUrl = applicationConfig.breadcrumbPartialUrl

   def buildBreadCrumb(implicit request: Request[_], messages: Messages): Breadcrumb = {
    val links = Map(
      "account" -> (Messages("nisp.breadcrumb.pension"), routes.StatePensionController.show().url),
      "nirecord" -> (Messages("nisp.breadcrumb.nirecord"), routes.NIRecordController.showFull().url),
      "voluntarycontribs" -> (Messages("nisp.breadcrumb.nirecord.voluntaryContrib"), routes.NIRecordController.showVoluntaryContributions().url),
      "gapsandhowtocheck" -> (Messages("nisp.breadcrumb.nirecord.gapsandhowtocheck"), routes.NIRecordController.showGapsAndHowToCheckThem().url),
      "exclusion" -> (Messages("nisp.breadcrumb.excluded"), routes.ExclusionController.showSP().url),
      "exclusionni" -> (Messages("nisp.breadcrumb.excluded"), routes.ExclusionController.showNI().url),
      "cope" -> (Messages("nisp.breadcrumb.cope"), routes.StatePensionController.showCope().url)
    )

    val items: List[Option[(String, String)]] = request.path.split("/").filter(!_.isEmpty).map(links.get).toList
    val breacrumList = initialBreadCrumbList ::: items.flatten

    val bcItems: Seq[BreadcrumbItem] = breacrumList.map( { case(label, url) => BreadcrumbItem(label, url) })
    Breadcrumb(bcItems.toVector)
  }

} 
Example 45
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 46
Source File: AddressControllerSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.address

import controllers.auth.AuthJourney
import controllers.auth.requests.UserRequest
import play.api.mvc.Request
import play.api.mvc.Results._
import play.api.test.FakeRequest
import play.api.test.Helpers._
import util.UserRequestFixture.buildUserRequest

class AddressControllerSpec extends AddressBaseSpec {

  object SUT
      extends AddressController(
        injected[AuthJourney],
        withActiveTabAction,
        cc,
        displayAddressInterstitialView
      )

  "addressJourneyEnforcer" should {

    "complete given block" when {

      "a nino and person details are present in the request" in {

        def userRequest[A]: UserRequest[A] =
          buildUserRequest(request = FakeRequest().asInstanceOf[Request[A]])

        val expectedContent = "Success"

        val result = SUT.addressJourneyEnforcer { _ => _ =>
          Ok(expectedContent)
        }(userRequest)

        status(result) shouldBe OK
        contentAsString(result) shouldBe expectedContent
      }
    }

    "show the address interstitial view page" when {

      "a nino cannot be found in the request" in {

        def userRequest[A]: UserRequest[A] =
          buildUserRequest(nino = None, request = FakeRequest().asInstanceOf[Request[A]])

        val result = SUT.addressJourneyEnforcer { _ => _ =>
          Ok("Success")
        }(userRequest)

        status(result) shouldBe OK
        contentAsString(result) should include(messages("label.you_can_see_this_part_of_your_account_if_you_complete"))
      }

      "person details cannot be found in the request" in {
        implicit def userRequest[A]: UserRequest[A] =
          buildUserRequest(personDetails = None, request = FakeRequest().asInstanceOf[Request[A]])

        val result = SUT.addressJourneyEnforcer { _ => _ =>
          Ok("Success")
        }

        status(result) shouldBe OK
        contentAsString(result) should include(messages("label.you_can_see_this_part_of_your_account_if_you_complete"))

      }
    }
  }

  "internalServerError" should {

    "return 500 and render the correct page" in {
      def userRequest[A]: UserRequest[A] =
        buildUserRequest(request = FakeRequest().asInstanceOf[Request[A]])

      val result = SUT.internalServerError(userRequest)

      status(result) shouldBe INTERNAL_SERVER_ERROR
      contentAsString(result) should include(messages("global.error.InternalServerError500.title"))
    }
  }
} 
Example 47
Source File: TaxCreditsChoiceControllerSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.address

import models.dto.AddressPageVisitedDto
import org.mockito.Matchers.any
import org.mockito.Mockito.{times, verify}
import play.api.http.Status.{BAD_REQUEST, OK, SEE_OTHER}
import play.api.libs.json.Json
import play.api.mvc.Request
import play.api.test.FakeRequest
import play.api.test.Helpers._
import uk.gov.hmrc.http.cache.client.CacheMap
import views.html.personaldetails.TaxCreditsChoiceView

class TaxCreditsChoiceControllerSpec extends AddressBaseSpec {

  trait LocalSetup extends AddressControllerSetup {

    def controller: TaxCreditsChoiceController =
      new TaxCreditsChoiceController(
        mockAuthJourney,
        withActiveTabAction,
        cc,
        addressJourneyCachingHelper,
        injected[TaxCreditsChoiceView],
        displayAddressInterstitialView
      )

    def sessionCacheResponse: Option[CacheMap] =
      Some(CacheMap("id", Map("addressPageVisitedDto" -> Json.toJson(AddressPageVisitedDto(true)))))

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

  "onPageLoad" should {

    "return OK if there is an entry in the cache to say the user previously visited the 'personal details' page" in new LocalSetup {

      val result = controller.onPageLoad(currentRequest)

      status(result) shouldBe OK
      verify(mockLocalSessionCache, times(1)).fetch()(any(), any())
    }

    "redirect back to the start of the journey if there is no entry in the cache to say the user previously visited the 'personal details' page" in new LocalSetup {
      override def sessionCacheResponse: Option[CacheMap] = None

      val result = controller.onPageLoad(currentRequest)

      status(result) shouldBe SEE_OTHER
      redirectLocation(result) shouldBe Some("/personal-account/personal-details")
      verify(mockLocalSessionCache, times(1)).fetch()(any(), any())
    }
  }

  "onSubmit" should {

    "redirect to expected tax credits page when supplied with value = Yes (true)" in new LocalSetup {

      override def currentRequest[A]: Request[A] =
        FakeRequest("POST", "")
          .withFormUrlEncodedBody("taxCreditsChoice" -> "true")
          .asInstanceOf[Request[A]]

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

      status(result) shouldBe SEE_OTHER
      redirectLocation(result) shouldBe Some("/tax-credits-service/personal/change-address")
    }

    "redirect to ResidencyChoice page when supplied with value = No (false)" in new LocalSetup {

      override def currentRequest[A]: Request[A] =
        FakeRequest("POST", "")
          .withFormUrlEncodedBody("taxCreditsChoice" -> "false")
          .asInstanceOf[Request[A]]

      val result = controller.onSubmit(FakeRequest())

      status(result) shouldBe SEE_OTHER
      redirectLocation(result) shouldBe Some("/personal-account/your-address/residency-choice")
    }

    "return a bad request when supplied no value" in new LocalSetup {

      override def currentRequest[A]: Request[A] =
        FakeRequest("POST", "")
          .asInstanceOf[Request[A]]

      val result = controller.onSubmit(FakeRequest())

      status(result) shouldBe BAD_REQUEST
    }
  }
} 
Example 48
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 49
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 50
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 51
Source File: UserRequest.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.auth.requests

import models._
import org.joda.time.DateTime
import play.api.mvc.{Request, WrappedRequest}
import uk.gov.hmrc.auth.core.ConfidenceLevel
import uk.gov.hmrc.auth.core.retrieve.Credentials
import uk.gov.hmrc.auth.core.retrieve.v2.TrustedHelper
import uk.gov.hmrc.domain.Nino
import uk.gov.hmrc.renderer.ActiveTab

case class UserRequest[+A](
  nino: Option[Nino],
  retrievedName: Option[UserName],
  saUserType: SelfAssessmentUserType,
  credentials: Credentials,
  confidenceLevel: ConfidenceLevel,
  personDetails: Option[PersonDetails],
  trustedHelper: Option[TrustedHelper],
  profile: Option[String],
  unreadMessageCount: Option[Int] = None,
  activeTab: Option[ActiveTab] = None,
  breadcrumb: Option[Breadcrumb] = None,
  request: Request[A])
    extends WrappedRequest[A](request) {

  def name: Option[String] = personDetails match {
    case Some(personDetails) => personDetails.person.shortName
    case _                   => retrievedName.map(_.toString)
  }

  def isGovernmentGateway: Boolean = credentials.providerType == "GovernmentGateway"

  def isVerify: Boolean = credentials.providerType == "Verify"

  def isSa: Boolean = saUserType != NonFilerSelfAssessmentUser

} 
Example 52
Source File: AuthenticatedRequest.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.auth.requests

import models.UserName
import org.joda.time.DateTime
import play.api.mvc.{Request, WrappedRequest}
import uk.gov.hmrc.auth.core.retrieve.Credentials
import uk.gov.hmrc.auth.core.retrieve.v2.TrustedHelper
import uk.gov.hmrc.auth.core.{ConfidenceLevel, Enrolment}
import uk.gov.hmrc.domain.{Nino, SaUtr}

sealed trait SelfAssessmentStatus
case object Activated extends SelfAssessmentStatus
case object NotYetActivated extends SelfAssessmentStatus

object SelfAssessmentStatus {

  def fromString(value: String): SelfAssessmentStatus = value match {
    case "Activated"       => Activated
    case "NotYetActivated" => NotYetActivated
    case _                 => throw new RuntimeException(s"Unexpected Self Assessment enrolment status of $value was returned")
  }
}

case class SelfAssessmentEnrolment(saUtr: SaUtr, status: SelfAssessmentStatus)

case class AuthenticatedRequest[A](
  nino: Option[Nino],
  saEnrolment: Option[SelfAssessmentEnrolment],
  credentials: Credentials,
  confidenceLevel: ConfidenceLevel,
  name: Option[UserName],
  trustedHelper: Option[TrustedHelper],
  profile: Option[String],
  enrolments: Set[Enrolment],
  request: Request[A])
    extends WrappedRequest[A](request) 
Example 53
Source File: AuditTags.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import play.api.mvc.Request
import uk.gov.hmrc.http.HeaderCarrier

private[auth] trait AuditTags {
  def buildTags(request: Request[_])(implicit hc: HeaderCarrier): Map[String, String] =
    Map(
      "X-Request-Id" -> hc.requestId.map(_.value).getOrElse(""),
      "X-Session-Id" -> hc.sessionId.map(_.value).getOrElse(""),
      "path"         -> request.path,
      "clientIP"     -> hc.trueClientIp.getOrElse(""),
      "clientPort"   -> hc.trueClientPort.getOrElse(""),
      "type"         -> "Audit"
    )
} 
Example 54
Source File: SelfAssessmentService.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package router.services

import javax.inject.Inject
import play.api.libs.json.JsValue
import play.api.mvc.Request
import router.connectors.SelfAssessmentConnector
import router.constants.Versions._
import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome
import uk.gov.hmrc.http.HeaderCarrier

import scala.concurrent.Future

class SelfAssessmentService @Inject()(val selfAssessmentConnector: SelfAssessmentConnector) extends Service {

  def get()(implicit hc: HeaderCarrier, req: Request[_]): Future[SelfAssessmentOutcome] = {
    withApiVersion {
      case Some(VERSION_1) => selfAssessmentConnector.get(s"${req.uri}")
      case Some(VERSION_2) => selfAssessmentConnector.get(req.uri)(convertHeaderToVersion1)
    }
  }

  def post(body: JsValue)(implicit hc: HeaderCarrier, req: Request[_]): Future[SelfAssessmentOutcome] = {
    withApiVersion {
      case Some(VERSION_1) => selfAssessmentConnector.post(req.uri, body)
      case Some(VERSION_2) => selfAssessmentConnector.post(req.uri, body)(convertHeaderToVersion1)
    }
  }

  def put(body: JsValue)(implicit hc: HeaderCarrier, req: Request[_]): Future[SelfAssessmentOutcome] = {
    withApiVersion {
      case Some(VERSION_1) => selfAssessmentConnector.put(req.uri, body)
      case Some(VERSION_2) => selfAssessmentConnector.put(req.uri, body)(convertHeaderToVersion1)
    }
  }
} 
Example 55
Source File: ReleaseTwoService.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package router.services

import config.AppConfig
import javax.inject.Inject
import play.api.libs.json.JsValue
import play.api.mvc.Request
import router.connectors.SelfAssessmentConnector
import router.constants.Versions.{VERSION_1, VERSION_2}
import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome
import uk.gov.hmrc.http.HeaderCarrier

import scala.concurrent.Future

class ReleaseTwoService @Inject()(val appConfig: AppConfig,
                                  val selfAssessmentConnector: SelfAssessmentConnector) extends Service {

  val r2 = "/r2"

  def create(body: JsValue)(implicit hc: HeaderCarrier, req: Request[_]): Future[SelfAssessmentOutcome] = {


    withApiVersion {
      case Some(VERSION_1) => selfAssessmentConnector.post(r2+req.uri, body)
      case Some(VERSION_2) => selfAssessmentConnector.post(r2+req.uri, body)(convertHeaderToVersion1)
    }
  }

  def get()(implicit hc: HeaderCarrier, req: Request[_]): Future[SelfAssessmentOutcome] = {

    withApiVersion {
      case Some(VERSION_1) => selfAssessmentConnector.get(r2+req.uri)
      case Some(VERSION_2) => selfAssessmentConnector.get(r2+req.uri)(convertHeaderToVersion1)
    }
  }

  def amend(body: JsValue)(implicit hc: HeaderCarrier, req: Request[_]): Future[SelfAssessmentOutcome] = {

    withApiVersion {
      case Some(VERSION_1) => selfAssessmentConnector.put(r2+req.uri, body)
      case Some(VERSION_2) => selfAssessmentConnector.put(r2+req.uri, body)(convertHeaderToVersion1)
    }
  }

} 
Example 56
Source File: CrystallisationService.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package router.services

import config.AppConfig
import javax.inject.Inject
import play.api.libs.json.JsValue
import play.api.mvc.Request
import router.connectors.{CrystallisationConnector, SelfAssessmentConnector}
import router.constants.Versions._
import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome
import uk.gov.hmrc.http.HeaderCarrier

import scala.concurrent.Future

class CrystallisationService @Inject() (val appConfig: AppConfig,
                                        val crystallisationConnector: CrystallisationConnector,
                                        val selfAssessmentConnector: SelfAssessmentConnector
                                       ) extends Service {

  def post(body: JsValue)(implicit hc: HeaderCarrier, req: Request[_]): Future[SelfAssessmentOutcome] = {

    withApiVersion {
      case Some(VERSION_2) => crystallisationConnector.post(s"/$VERSION_2${req.uri}", body)
    }
  }

  def postEmpty(implicit hc: HeaderCarrier, req: Request[_]): Future[SelfAssessmentOutcome] = {

    withApiVersion {
      case Some(VERSION_2) => crystallisationConnector.postEmpty(s"/$VERSION_2${req.uri}")
    }
  }

  def get()(implicit hc: HeaderCarrier, req: Request[_]): Future[SelfAssessmentOutcome] = {
    withApiVersion {
      case Some(VERSION_1) => selfAssessmentConnector.get(req.uri)
      case Some(VERSION_2) => crystallisationConnector.get(s"/$VERSION_2${req.uri}")}
  }
} 
Example 57
Source File: DividendsService.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package router.services

import config.AppConfig
import javax.inject.Inject
import play.api.libs.json.JsValue
import play.api.mvc.Request
import router.connectors.DividendsConnector
import router.constants.Versions.VERSION_2
import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome
import uk.gov.hmrc.http.HeaderCarrier

import scala.concurrent.Future

class DividendsService @Inject()(val appConfig: AppConfig,
                                 val dividendsConnector: DividendsConnector) extends Service {


  def put(body: JsValue)(implicit hc: HeaderCarrier, req: Request[_]): Future[SelfAssessmentOutcome] = {

    withApiVersion {
      case Some(VERSION_2) => dividendsConnector.put(s"/$VERSION_2${req.uri}", body)
    }
  }

  def get()(implicit hc: HeaderCarrier, req: Request[_]): Future[SelfAssessmentOutcome] = {
    withApiVersion {
      case Some(VERSION_2) => dividendsConnector.get(s"/$VERSION_2${req.uri}")
    }
  }
} 
Example 58
Source File: SavingsAccountService.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package router.services

import config.AppConfig
import javax.inject.Inject
import play.api.libs.json.JsValue
import play.api.mvc.Request
import router.connectors.SavingsAccountConnector
import router.constants.Versions.VERSION_2
import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome
import uk.gov.hmrc.http.HeaderCarrier

import scala.concurrent.Future

class SavingsAccountService @Inject()(val appConfig: AppConfig,
                                      val savingsAccountConnector: SavingsAccountConnector) extends Service {


  def post(body: JsValue)(implicit hc: HeaderCarrier, req: Request[_]): Future[SelfAssessmentOutcome] = {
    withApiVersion {
      case Some(VERSION_2) => savingsAccountConnector.post(s"/$VERSION_2${req.uri}", body)
    }
  }

  def get()(implicit hc: HeaderCarrier, req: Request[_]): Future[SelfAssessmentOutcome] = {
    withApiVersion {
      case Some(VERSION_2) => savingsAccountConnector.get(s"/$VERSION_2${req.uri}")
    }
  }

  def put(body: JsValue)(implicit hc: HeaderCarrier, req: Request[_]): Future[SelfAssessmentOutcome] = {
    withApiVersion {
      case Some(VERSION_2) => savingsAccountConnector.put(s"/$VERSION_2${req.uri}", body)
    }
  }
} 
Example 59
Source File: CharitableGivingService.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package router.services

import config.AppConfig
import javax.inject.Inject
import play.api.libs.json.JsValue
import play.api.mvc.Request
import router.connectors.CharitableGivingConnector
import router.constants.Versions.VERSION_2
import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome
import uk.gov.hmrc.http.HeaderCarrier

import scala.concurrent.Future

class CharitableGivingService @Inject()(val appConfig: AppConfig,
                                        val charitableGivingConnector: CharitableGivingConnector) extends Service {


  def put(body: JsValue)(implicit hc: HeaderCarrier, req: Request[_]): Future[SelfAssessmentOutcome] = {

    withApiVersion {
      case Some(VERSION_2) => charitableGivingConnector.put(s"/$VERSION_2${req.uri}", body)
    }
  }

  def get()(implicit hc: HeaderCarrier, req: Request[_]): Future[SelfAssessmentOutcome] = {
    withApiVersion {
      case Some(VERSION_2) => charitableGivingConnector.get(s"/$VERSION_2${req.uri}")
    }
  }

} 
Example 60
Source File: MockSelfAssessmentService.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package mocks.services

import mocks.Mock
import org.mockito.stubbing.OngoingStubbing
import org.scalatest.Suite
import play.api.libs.json.JsValue
import play.api.mvc.Request
import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome
import router.services.SelfAssessmentService
import uk.gov.hmrc.http.HeaderCarrier

import scala.concurrent.Future

trait MockSelfAssessmentService extends Mock { _: Suite =>

  val mockSelfAssessmentService = mock[SelfAssessmentService]

  object MockSelfAssessmentService {
    def get(): OngoingStubbing[Future[SelfAssessmentOutcome]] = {
      when(mockSelfAssessmentService.get()(any[HeaderCarrier](), any[Request[_]]()))
    }

    def post(body: JsValue): OngoingStubbing[Future[SelfAssessmentOutcome]] = {
      when(mockSelfAssessmentService.post(eqTo(body))(any[HeaderCarrier](), any[Request[_]]()))
    }

    def put(body: JsValue): OngoingStubbing[Future[SelfAssessmentOutcome]] = {
      when(mockSelfAssessmentService.put(eqTo(body))(any[HeaderCarrier](), any[Request[_]]()))
    }
  }

  override protected def beforeEach(): Unit = {
    super.beforeEach()
    reset(mockSelfAssessmentService)
  }
} 
Example 61
Source File: MockCrystallisationService.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package mocks.services

import mocks.Mock
import org.mockito.stubbing.OngoingStubbing
import org.scalatest.Suite
import play.api.libs.json.JsValue
import play.api.mvc.Request
import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome
import router.services.CrystallisationService
import uk.gov.hmrc.http.HeaderCarrier

import scala.concurrent.Future

trait MockCrystallisationService extends Mock { _: Suite =>
  val mockCrystallisationService = mock[CrystallisationService]

  object MockCrystallisationService {

    def post(body: JsValue): OngoingStubbing[Future[SelfAssessmentOutcome]] = {
      when(mockCrystallisationService.post(eqTo(body))(any[HeaderCarrier](), any[Request[_]]()))
    }

    def postEmpty: OngoingStubbing[Future[SelfAssessmentOutcome]] = {
      when(mockCrystallisationService.postEmpty(any[HeaderCarrier](), any[Request[_]]()))
    }

    def get(): OngoingStubbing[Future[SelfAssessmentOutcome]] = {
      when(mockCrystallisationService.get()(any[HeaderCarrier](), any[Request[_]]()))
    }
  }

  override protected def beforeEach(): Unit = {
    super.beforeEach()
    reset(mockCrystallisationService)
  }

} 
Example 62
Source File: MockPropertyEopsObligationsService.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package mocks.services

import mocks.Mock
import org.mockito.stubbing.OngoingStubbing
import org.scalatest.Suite
import play.api.mvc.Request
import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome
import router.services.PropertyEopsObligationsService
import uk.gov.hmrc.http.HeaderCarrier

import scala.concurrent.Future

trait MockPropertyEopsObligationsService extends Mock { _: Suite =>

  val mockPropertyEopsObligationsService = mock[PropertyEopsObligationsService]

  object MockPropertyEopsObligationsService {
    def get(): OngoingStubbing[Future[SelfAssessmentOutcome]] = {
      when(mockPropertyEopsObligationsService.get()(any[HeaderCarrier](), any[Request[_]]()))
    }
  }

  override protected def beforeEach(): Unit = {
    super.beforeEach()
    reset(mockPropertyEopsObligationsService)
  }
} 
Example 63
Source File: MockTaxCalcService.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package mocks.services

import mocks.Mock
import org.mockito.stubbing.OngoingStubbing
import org.scalatest.Suite
import play.api.mvc.Request
import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome
import router.services.TaxCalcService
import uk.gov.hmrc.http.HeaderCarrier

import scala.concurrent.Future

trait MockTaxCalcService extends Mock { _: Suite =>

  val mockTaxCalcService = mock[TaxCalcService]

  object MockTaxCalcService {
    def get(): OngoingStubbing[Future[SelfAssessmentOutcome]] = {
      when(mockTaxCalcService.get()(any[HeaderCarrier](), any[Request[_]]()))
    }
  }

  override protected def beforeEach(): Unit = {
    super.beforeEach()
    reset(mockTaxCalcService)
  }
} 
Example 64
Source File: MockSavingsAccountService.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package mocks.services

import mocks.Mock
import org.mockito.stubbing.OngoingStubbing
import org.scalatest.Suite
import play.api.libs.json.JsValue
import play.api.mvc.Request
import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome
import router.services.SavingsAccountService
import uk.gov.hmrc.http.HeaderCarrier

import scala.concurrent.Future

trait MockSavingsAccountService extends Mock { _: Suite =>

  lazy val mockSavingsAccountService: SavingsAccountService = mock[SavingsAccountService]

  object MockSavingsAccountService {

    def post(body: JsValue): OngoingStubbing[Future[SelfAssessmentOutcome]] = {
      when(mockSavingsAccountService.post(eqTo(body))(any[HeaderCarrier](), any[Request[_]]()))
    }

    def get(): OngoingStubbing[Future[SelfAssessmentOutcome]] = {
      when(mockSavingsAccountService.get()(any[HeaderCarrier](), any[Request[_]]()))
    }

    def put(body: JsValue) = {
      when(mockSavingsAccountService.put(eqTo(body))(any[HeaderCarrier](), any[Request[_]]()))
    }

  }

  override protected def beforeEach(): Unit = {
    super.beforeEach()
    reset(mockSavingsAccountService)
  }
} 
Example 65
Source File: MockPropertyEopsDeclarationService.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package mocks.services

import mocks.Mock
import org.mockito.stubbing.OngoingStubbing
import org.scalatest.Suite
import play.api.libs.json.JsValue
import play.api.mvc.Request
import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome
import router.services.PropertyEopsDeclarationService
import uk.gov.hmrc.http.HeaderCarrier

import scala.concurrent.Future

trait MockPropertyEopsDeclarationService extends Mock { _: Suite =>

  val mockPropertyEopsDeclarationService = mock[PropertyEopsDeclarationService]

  object MockPropertyEopsDeclarationService {
    def post(): OngoingStubbing[Future[SelfAssessmentOutcome]] = {
      when(mockPropertyEopsDeclarationService.post(any[JsValue]())(any[HeaderCarrier](), any[Request[_]]()))
    }
  }

  override protected def beforeEach(): Unit = {
    super.beforeEach()
    reset(mockPropertyEopsDeclarationService)
  }
} 
Example 66
Source File: MockReleaseTwoService.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package mocks.services

import mocks.Mock
import org.mockito.stubbing.OngoingStubbing
import org.scalatest.Suite
import play.api.libs.json.JsValue
import play.api.mvc.Request
import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome
import router.services.ReleaseTwoService
import uk.gov.hmrc.http.HeaderCarrier

import scala.concurrent.Future

trait MockReleaseTwoService extends Mock { _: Suite =>

  val mockReleaseTwoService = mock[ReleaseTwoService]

  object MockReleaseTwoService {
    def create(body: JsValue): OngoingStubbing[Future[SelfAssessmentOutcome]] = {
      when(mockReleaseTwoService.create(eqTo(body))(any[HeaderCarrier](), any[Request[_]]()))
    }

    def get(): OngoingStubbing[Future[SelfAssessmentOutcome]] = {
      when(mockReleaseTwoService.get()(any[HeaderCarrier](), any[Request[_]]()))
    }

    def amend(body: JsValue): OngoingStubbing[Future[SelfAssessmentOutcome]] = {
      when(mockReleaseTwoService.amend(eqTo(body))(any[HeaderCarrier](), any[Request[_]]()))
    }
  }

  override protected def beforeEach(): Unit = {
    super.beforeEach()
    reset(mockReleaseTwoService)
  }
} 
Example 67
Source File: MockCharitableGivingService.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package mocks.services

import mocks.Mock
import org.mockito.stubbing.OngoingStubbing
import org.scalatest.Suite
import play.api.libs.json.JsValue
import play.api.mvc.Request
import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome
import router.services.CharitableGivingService
import uk.gov.hmrc.http.HeaderCarrier

import scala.concurrent.Future

trait MockCharitableGivingService extends Mock { _: Suite =>

  val mockCharitableGivingService = mock[CharitableGivingService]

  object MockCharitableGivingService {

    def put(body: JsValue): OngoingStubbing[Future[SelfAssessmentOutcome]] = {
      when(mockCharitableGivingService.put(eqTo(body))(any[HeaderCarrier](), any[Request[_]]()))
    }

    def get(): OngoingStubbing[Future[SelfAssessmentOutcome]] = {
      when(mockCharitableGivingService.get()(any[HeaderCarrier](), any[Request[_]]()))
    }
  }

  override protected def beforeEach(): Unit = {
    super.beforeEach()
    reset(mockCharitableGivingService)
  }
} 
Example 68
Source File: MockSelfEmploymentEopsDeclarationService.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package mocks.services

import mocks.Mock
import org.mockito.stubbing.OngoingStubbing
import org.scalatest.Suite
import play.api.libs.json.JsValue
import play.api.mvc.Request
import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome
import router.services.SelfEmploymentEopsDeclarationService
import uk.gov.hmrc.http.HeaderCarrier

import scala.concurrent.Future

trait MockSelfEmploymentEopsDeclarationService extends Mock { _: Suite =>

  val mockSelfEmploymentEopsDeclarationService = mock[SelfEmploymentEopsDeclarationService]

  object MockSelfEmploymentEopsDeclarationService {
    def post(): OngoingStubbing[Future[SelfAssessmentOutcome]] = {
      when(mockSelfEmploymentEopsDeclarationService.post(any[JsValue]())(any[HeaderCarrier](), any[Request[_]]()))
    }
  }

  override protected def beforeEach(): Unit = {
    super.beforeEach()
    reset(mockSelfEmploymentEopsDeclarationService)
  }
}