play.api.http.Status Scala Examples
The following examples show how to use play.api.http.Status.
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: RealWorldWithServerAndTestConfigBaseTest.scala From scala-play-realworld-example-app with MIT License | 5 votes |
package commons_test.test_helpers import java.util.concurrent.Executors import commons_test.test_helpers.RealWorldWithServerAndTestConfigBaseTest.RealWorldWithTestConfig import commons_test.test_helpers.WsScalaTestClientWithHost.TestWsClient import config.RealWorldComponents import org.scalatest._ import play.api.ApplicationLoader.Context import play.api.Configuration import play.api.http.Status import play.api.test.DefaultAwaitTimeout import scala.concurrent.ExecutionContext trait RealWorldWithServerBaseTest extends FlatSpec with MustMatchers with OptionValues with WsScalaTestClientWithHost with OneServerPerTestWithComponents_FixedForCompileTimeTestSetUp with Status with DefaultAwaitTimeout with WithAwaitUtilities with WithTestExecutionContext { override implicit val executionContext: ExecutionContext = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(1)) implicit val host: Host = Host("http://localhost:") override type TestComponents <: RealWorldWithTestConfig implicit def wsClientWithConnectionData: TestWsClient = { TestWsClient(host, portNumber, components.wsClient) } } object RealWorldWithServerAndTestConfigBaseTest { class RealWorldWithTestConfig(context: Context) extends RealWorldComponents(context) { override def configuration: Configuration = { val testConfig = Configuration.from(TestUtils.config) val config = super.configuration testConfig.withFallback(config) } } } class RealWorldWithServerAndTestConfigBaseTest extends RealWorldWithServerBaseTest { override type TestComponents = RealWorldWithTestConfig override def createComponents: TestComponents = { new RealWorldWithTestConfig(context) } }
Example 2
Source File: UnitSpec.scala From self-assessment-api with Apache License 2.0 | 5 votes |
package support import org.scalatest.EitherValues import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike import play.api.http.{HeaderNames, MimeTypes, Status} import play.api.mvc.ControllerComponents import play.api.test.Helpers.stubControllerComponents import play.api.test.{DefaultAwaitTimeout, FutureAwaits, ResultExtractors} import uk.gov.hmrc.http.HeaderCarrier import scala.util.control.NoStackTrace trait UnitSpec extends AnyWordSpecLike with EitherValues with Matchers with FutureAwaits with DefaultAwaitTimeout with ResultExtractors with HeaderNames with Status with MimeTypes { lazy val controllerComponents: ControllerComponents = stubControllerComponents() implicit val hc: HeaderCarrier = HeaderCarrier() val testException: Throwable = new NoStackTrace { override def getMessage: String = "A test exception was thrown" } }
Example 3
Source File: SelfAssessmentHttpParserSpec.scala From self-assessment-api with Apache License 2.0 | 5 votes |
package router.httpParsers import play.api.http.Status import play.api.libs.json.Json import support.UnitSpec import uk.gov.hmrc.http.HttpResponse class SelfAssessmentHttpParserSpec extends UnitSpec { val httpParser: SelfAssessmentHttpParser = new SelfAssessmentHttpParser "SelfAssessmentHttpParser" should { "return a response" when { val testJson = Json.toJson(s"""{"testKey":"testValue"}""") "self-assessment returns a 200 (OK) response" in { val response = HttpResponse(Status.OK, Some(testJson)) val result = httpParser.read("GET", "/", response).right.value result shouldBe response result.status shouldBe Status.OK result.body shouldBe testJson.toString } "self-assessment returns a 500 (InternalServerError)" in { val response = HttpResponse(Status.INTERNAL_SERVER_ERROR, Some(testJson)) val result = httpParser.read("GET", "/any-url", response).right.value result shouldBe response result.status shouldBe Status.INTERNAL_SERVER_ERROR result.body shouldBe testJson.toString } "self-assessment returns a 400 (BadRequest)" in { val response = HttpResponse(Status.BAD_REQUEST, Some(testJson)) val result = httpParser.read("GET", "/any/url", response).right.value result shouldBe response result.status shouldBe Status.BAD_REQUEST result.body shouldBe testJson.toString } } } }
Example 4
Source File: TaxCalcConnectorSpec.scala From self-assessment-api with Apache License 2.0 | 5 votes |
package router.connectors import mocks.MockHttp import mocks.config.MockAppConfig import mocks.httpParser.MockSelfAssessmentHttpParser import play.api.http.Status import play.api.libs.json.Json import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome import support.UnitSpec import uk.gov.hmrc.http.HttpResponse import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future class TaxCalcConnectorSpec extends UnitSpec with MockHttp with MockAppConfig with MockSelfAssessmentHttpParser { class Setup { object TestConnector extends TaxCalcConnector( mockHttp, mockSelfAssessmentHttpParser, mockAppConfig ) MockAppConfig.taxCalcUrl returns taxCalcUrl } lazy val taxCalcUrl = "test-sa-api-url" val path = "/2.0/test-path" "get" should { "return a HttpResponse" when { "a successful HttpResponse is returned" in new Setup { val response = HttpResponse(Status.OK, Some(Json.obj())) MockSelfAssessmentHttpParser.read.returns(Right(response)) MockHttp.GET[SelfAssessmentOutcome](s"$taxCalcUrl$path").returns(Future.successful(Right(response))) await(TestConnector.get(path)(hc)) shouldBe Right(response) } } } }
Example 5
Source File: CrystallisationConnectorSpec.scala From self-assessment-api with Apache License 2.0 | 5 votes |
package router.connectors import mocks.MockHttp import mocks.config.MockAppConfig import mocks.httpParser.MockSelfAssessmentHttpParser import play.api.http.Status import play.api.libs.json.{JsValue, Json} import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome import support.UnitSpec import uk.gov.hmrc.http.HttpResponse import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future class CrystallisationConnectorSpec extends UnitSpec with MockHttp with MockAppConfig with MockSelfAssessmentHttpParser { class Setup { object TestConnector extends CrystallisationConnector( mockHttp, mockSelfAssessmentHttpParser, mockAppConfig ) MockAppConfig.crystallisationApiUrl returns crystallisationApiUrl } lazy val crystallisationApiUrl = "test-di-api-url" val path = "/2.0/test-path" "post" should { "return a HttpResponse" when { "a successful HttpResponse is returned" in new Setup { val response = HttpResponse(Status.NO_CONTENT) val requestJson = Json.obj("test" -> "request json") MockSelfAssessmentHttpParser.read.returns(Right(response)) MockHttp.POST[JsValue, SelfAssessmentOutcome](s"$crystallisationApiUrl$path", requestJson) .returns(Future.successful(Right(response))) await(TestConnector.post(path, requestJson)(hc)) shouldBe Right(response) } } } "postEmpty" should { "return a HttpResponse" when { "a successful HttpResponse is returned" in new Setup { val response = HttpResponse(Status.NO_CONTENT) MockSelfAssessmentHttpParser.read.returns(Right(response)) MockHttp.POSTEmpty[SelfAssessmentOutcome](s"$crystallisationApiUrl$path") .returns(Future.successful(Right(response))) await(TestConnector.postEmpty(path)(hc)) shouldBe Right(response) } } } "retrieve" should { "return a HttpResponse" when { "a successful HttpResponse is returned" in new Setup { val response = HttpResponse(Status.OK, Some(Json.obj())) MockSelfAssessmentHttpParser.read.returns(Right(response)) MockHttp.GET[SelfAssessmentOutcome](s"$crystallisationApiUrl$path") .returns(Future.successful(Right(response))) await(TestConnector.get(path)(hc)) shouldBe Right(response) } } } }
Example 6
Source File: DividendsConnectorSpec.scala From self-assessment-api with Apache License 2.0 | 5 votes |
package router.connectors import mocks.MockHttp import mocks.config.MockAppConfig import mocks.httpParser.MockSelfAssessmentHttpParser import play.api.http.Status import play.api.libs.json.{JsValue, Json} import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome import support.UnitSpec import uk.gov.hmrc.http.HttpResponse import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future class DividendsConnectorSpec extends UnitSpec with MockHttp with MockAppConfig with MockSelfAssessmentHttpParser { class Setup { object TestConnector extends DividendsConnector( mockHttp, mockSelfAssessmentHttpParser, mockAppConfig ) MockAppConfig.dividendsApiUrl returns dividendsApiUrl } lazy val dividendsApiUrl = "test-di-api-url" val path = "/2.0/test-path" "amend" should { "return a HttpResponse" when { "a successful HttpResponse is returned" in new Setup { val response = HttpResponse(Status.OK, Some(Json.obj())) val requestJson = Json.obj("test" -> "request json") MockSelfAssessmentHttpParser.read.returns(Right(response)) MockHttp.PUT[JsValue, SelfAssessmentOutcome](s"$dividendsApiUrl$path", requestJson).returns(Future.successful(Right(response))) await(TestConnector.put(path, requestJson)(hc)) shouldBe Right(response) } } } "retrieve" should { "return a HttpResponse" when { "a successful HttpResponse is returned" in new Setup { val response = HttpResponse(Status.OK, Some(Json.obj())) MockSelfAssessmentHttpParser.read.returns(Right(response)) MockHttp.GET[SelfAssessmentOutcome](s"$dividendsApiUrl$path").returns(Future.successful(Right(response))) await(TestConnector.get(path)(hc)) shouldBe Right(response) } } } }
Example 7
Source File: CharitableGivingConnectorSpec.scala From self-assessment-api with Apache License 2.0 | 5 votes |
package router.connectors import mocks.MockHttp import mocks.config.MockAppConfig import mocks.httpParser.MockSelfAssessmentHttpParser import play.api.http.Status import play.api.libs.json.{JsValue, Json} import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome import support.UnitSpec import uk.gov.hmrc.http.HttpResponse import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future class CharitableGivingConnectorSpec extends UnitSpec with MockHttp with MockAppConfig with MockSelfAssessmentHttpParser { class Setup { object TestConnector extends CharitableGivingConnector( mockHttp, mockSelfAssessmentHttpParser, mockAppConfig ) MockAppConfig.cgApiUrl returns cgApiUrl } lazy val cgApiUrl = "test-cg-api-url" val path = "/2.0/test-path" "amend" should { "return a HttpResponse" when { "a successful HttpResponse is returned" in new Setup { val response = HttpResponse(Status.OK, Some(Json.obj())) val requestJson = Json.obj("test" -> "request json") MockSelfAssessmentHttpParser.read.returns(Right(response)) MockHttp.PUT[JsValue, SelfAssessmentOutcome](s"$cgApiUrl$path", requestJson).returns(Future.successful(Right(response))) await(TestConnector.put(path, requestJson)(hc)) shouldBe Right(response) } } } "retrieve" should { "return a HttpResponse" when { "a successful HttpResponse is returned" in new Setup { val response = HttpResponse(Status.OK, Some(Json.obj())) MockSelfAssessmentHttpParser.read.returns(Right(response)) MockHttp.GET[SelfAssessmentOutcome](s"$cgApiUrl$path").returns(Future.successful(Right(response))) await(TestConnector.get(path)(hc)) shouldBe Right(response) } } } }
Example 8
Source File: SavingsAccountsConnectorSpec.scala From self-assessment-api with Apache License 2.0 | 5 votes |
package router.connectors import mocks.MockHttp import mocks.config.MockAppConfig import mocks.httpParser.MockSelfAssessmentHttpParser import play.api.http.Status import play.api.libs.json.{JsValue, Json} import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome import support.UnitSpec import uk.gov.hmrc.http.HttpResponse import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future class SavingsAccountsConnectorSpec extends UnitSpec with MockHttp with MockAppConfig with MockSelfAssessmentHttpParser { class Setup { object TestConnector extends SavingsAccountConnector( mockHttp, mockSelfAssessmentHttpParser, mockAppConfig ) MockAppConfig.savingsAccountsApiUrl returns savingsAccountsApiUrl } lazy val savingsAccountsApiUrl = "test-di-api-url" val path = "/2.0/test-path" "create" should { "return a HttpResponse" when { "a successful HttpResponse is returned" in new Setup { val response = HttpResponse(Status.CREATED, Some(Json.obj())) val requestJson = Json.obj("test" -> "request json") MockSelfAssessmentHttpParser.read.returns(Right(response)) MockHttp.POST[JsValue, SelfAssessmentOutcome](s"$savingsAccountsApiUrl$path", requestJson).returns(Future.successful(Right(response))) await(TestConnector.post(path, requestJson)(hc)) shouldBe Right(response) } } } "retrieve" should { "return a HttpResponse" when { "a successful HttpResponse is returned" in new Setup { val response = HttpResponse(Status.OK, Some(Json.obj())) MockSelfAssessmentHttpParser.read.returns(Right(response)) MockHttp.GET[SelfAssessmentOutcome](s"$savingsAccountsApiUrl$path").returns(Future.successful(Right(response))) await(TestConnector.get(path)(hc)) shouldBe Right(response) } } } "amend" should { "return a HttpResponse" when { "a successful HttpResponse is returned" in new Setup { val response = HttpResponse(Status.NO_CONTENT) val requestJson = Json.obj("test" -> "request json") MockSelfAssessmentHttpParser.read.returns(Right(response)) MockHttp.PUT[JsValue, SelfAssessmentOutcome](s"$savingsAccountsApiUrl$path", requestJson).returns(Future.successful(Right(response))) await(TestConnector.put(path, requestJson)(hc)) shouldBe Right(response) } } } }
Example 9
Source File: SelfEmploymentConnectorSpec.scala From self-assessment-api with Apache License 2.0 | 5 votes |
package router.connectors import mocks.MockHttp import mocks.config.MockAppConfig import mocks.httpParser.MockSelfAssessmentHttpParser import play.api.http.Status import play.api.libs.json.{JsValue, Json} import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome import support.UnitSpec import uk.gov.hmrc.http.HttpResponse import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future class SelfEmploymentConnectorSpec extends UnitSpec with MockHttp with MockAppConfig with MockSelfAssessmentHttpParser { class Setup { object TestConnector extends SelfEmploymentConnector( mockHttp, mockSelfAssessmentHttpParser, mockAppConfig ) MockAppConfig.selfEmploymentUrl returns selfEmploymentUrl } lazy val selfEmploymentUrl = "test-sa-api-url" val path = "/2.0/test-path" "post" should { "return an HttpResponse" when { "a successful HttpResponse with no content is returned" in new Setup { val response = HttpResponse(Status.NO_CONTENT) val requestJson = Json.obj("test" -> "request json") MockHttp.POST[JsValue, SelfAssessmentOutcome](s"$selfEmploymentUrl$path", requestJson).returns(Future.successful(Right(response))) await(TestConnector.post(path, requestJson)(hc)) shouldBe Right(response) } } } }
Example 10
Source File: PropertyConnectorSpec.scala From self-assessment-api with Apache License 2.0 | 5 votes |
package router.connectors import mocks.MockHttp import mocks.config.MockAppConfig import mocks.httpParser.MockSelfAssessmentHttpParser import play.api.http.Status import play.api.libs.json.{JsValue, Json} import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome import support.UnitSpec import uk.gov.hmrc.http.HttpResponse import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future class PropertyConnectorSpec extends UnitSpec with MockHttp with MockAppConfig with MockSelfAssessmentHttpParser { class Setup { object TestConnector extends PropertyConnector( mockHttp, mockSelfAssessmentHttpParser, mockAppConfig ) MockAppConfig.propertyUrl returns propertyUrl } lazy val propertyUrl = "test-sa-api-url" val path = "/2.0/test-path" "get" should { "return a HttpResponse" when { "a successful HttpResponse is returned" in new Setup { val response = HttpResponse(Status.OK, Some(Json.obj())) MockSelfAssessmentHttpParser.read.returns(Right(response)) MockHttp.GET[SelfAssessmentOutcome](s"$propertyUrl$path").returns(Future.successful(Right(response))) await(TestConnector.get(path)(hc)) shouldBe Right(response) } } } "post" should { "return an HttpResponse" when { "a successful HttpResponse with no content is returned" in new Setup { val response = HttpResponse(Status.NO_CONTENT) val requestJson = Json.obj("test" -> "request json") MockHttp.POST[JsValue, SelfAssessmentOutcome](s"$propertyUrl$path", requestJson).returns(Future.successful(Right(response))) await(TestConnector.post(path, requestJson)(hc)) shouldBe Right(response) } } } }
Example 11
Source File: SelfAssessmentConnectorSpec.scala From self-assessment-api with Apache License 2.0 | 5 votes |
package router.connectors import mocks.MockHttp import mocks.config.MockAppConfig import mocks.httpParser.MockSelfAssessmentHttpParser import play.api.http.Status import play.api.libs.json.Json import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome import support.UnitSpec import uk.gov.hmrc.http.HttpResponse import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future class SelfAssessmentConnectorSpec extends UnitSpec with MockHttp with MockAppConfig with MockSelfAssessmentHttpParser { class Setup { object TestConnector extends SelfAssessmentConnector( mockHttp, mockSelfAssessmentHttpParser, mockAppConfig ) MockAppConfig.saApiUrl returns saApiUrl } lazy val saApiUrl = "test-sa-api-url" val path = "/test-path" "get" should { "return a HttpResponse" when { "a successful HttpResponse is returned" in new Setup { val response = HttpResponse(Status.OK, Some(Json.obj())) MockSelfAssessmentHttpParser.read.returns(Right(response)) MockHttp.GET[SelfAssessmentOutcome](s"$saApiUrl$path").returns(Future.successful(Right(response))) await(TestConnector.get(path)(hc)) shouldBe Right(response) } } } }
Example 12
Source File: IntegrationSpec.scala From self-assessment-api with Apache License 2.0 | 5 votes |
package support import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec import org.scalatestplus.play.guice.GuiceOneServerPerSuite import play.api.Application import play.api.http.{HeaderNames, MimeTypes, Status} import play.api.inject.guice.GuiceApplicationBuilder import support.functional.FunctionalSyntax import support.wiremock.WireMockSupport trait IntegrationSpec extends AnyWordSpec with GuiceOneServerPerSuite with WireMockSupport with Matchers with Status with HeaderNames with MimeTypes with FakeApplicationConfig with FunctionalSyntax { override implicit lazy val app: Application = new GuiceApplicationBuilder() .configure(fakeApplicationConfig) .build() }
Example 13
Source File: HatBodyParsers.scala From HAT2.0 with GNU Affero General Public License v3.0 | 5 votes |
package org.hatdex.hat.utils import javax.inject.Inject import play.api.http.{ HttpErrorHandler, Status } import play.api.libs.json.{ JsError, Reads } import play.api.mvc.{ BodyParser, PlayBodyParsers } import scala.concurrent.{ ExecutionContext, Future } class HatBodyParsers @Inject() (errorHandler: HttpErrorHandler, playBodyParsers: PlayBodyParsers)( implicit val ec: ExecutionContext) { def json[A](implicit reader: Reads[A]): BodyParser[A] = BodyParser("json reader") { request => playBodyParsers.json(request) mapFuture { case Left(simpleResult) => Future.successful(Left(simpleResult)) case Right(jsValue) => jsValue.validate(reader) map { a => Future.successful(Right(a)) } recoverTotal { jsError => val msg = JsError.toJson(jsError).toString() errorHandler.onClientError(request, Status.BAD_REQUEST, msg) map Left.apply } } } }
Example 14
Source File: ApiResult.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.web.api.domain.utils import java.time.Instant import gospeak.core.domain.utils.BasicCtx import gospeak.web.utils.BasicReq import gospeak.libs.scala.domain.Page import play.api.http.Status import play.api.libs.json._ sealed trait ApiResult[+A] extends Product with Serializable { def data: A val execMs: Long } object ApiResult { def of[A](p: A)(implicit ctx: BasicCtx): ItemResult[A] = ItemResult[A]( data = p, execMs = Instant.now().toEpochMilli - ctx.now.toEpochMilli) def of[A, B](p: Page[A], f: A => B)(implicit ctx: BasicCtx): PageResult[Seq[B]] = PageResult[Seq[B]]( data = p.items.map(f), totalItems = p.total.value, pageSize = p.params.pageSize.value, pageNo = p.params.page.value, execMs = Instant.now().toEpochMilli - ctx.now.toEpochMilli) def notFound(message: String)(implicit ctx: BasicCtx): ErrorResult = err(Status.NOT_FOUND, message) def badRequest(message: String)(implicit ctx: BasicCtx): ErrorResult = err(Status.BAD_REQUEST, message) def badRequest(errors: Seq[(JsPath, Seq[JsonValidationError])])(implicit req: BasicReq[JsValue]): ErrorResult = badRequest("Invalid request body:" + errors.map { case (path, errs) => s"\n - ${path.toJsonString}: ${errs.map(req.format).mkString(", ")}" }.mkString) def forbidden(message: String)(implicit ctx: BasicCtx): ErrorResult = err(Status.FORBIDDEN, message) def internalServerError(message: String)(implicit ctx: BasicCtx): ErrorResult = err(Status.INTERNAL_SERVER_ERROR, message) private def err(status: Int, message: String)(implicit ctx: BasicCtx): ErrorResult = ErrorResult( status = status, message = message, execMs = Instant.now().toEpochMilli - ctx.now.toEpochMilli) } final case class ItemResult[A](data: A, execMs: Long) extends ApiResult[A] object ItemResult { implicit def writes[A](implicit a: Writes[A]): Writes[ItemResult[A]] = Json.writes[ItemResult[A]] } final case class PageResult[A](data: A, totalItems: Long, pageSize: Int, pageNo: Int, execMs: Long) extends ApiResult[A] object PageResult { implicit def writes[A](implicit a: Writes[A]): Writes[PageResult[A]] = Json.writes[PageResult[A]] } final case class ErrorResult(status: Int, message: String, execMs: Long) extends ApiResult[Nothing] { override def data: Nothing = throw new NoSuchElementException("ErrorResponse.data") } object ErrorResult { implicit val writes: Writes[ErrorResult] = Json.writes[ErrorResult] }
Example 15
Source File: CustomSecuredErrorHandler.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.web.auth.services import com.mohiva.play.silhouette.api.actions.SecuredErrorHandler import gospeak.web.api.domain.utils.ErrorResult import gospeak.web.auth.routes.AuthCtrl import gospeak.web.pages.user.routes.UserCtrl import gospeak.web.utils.HttpUtils import play.api.http.Status import play.api.i18n.{I18nSupport, MessagesApi} import play.api.libs.json.Json import play.api.mvc.Results._ import play.api.mvc.{RequestHeader, Result} import scala.concurrent.Future class CustomSecuredErrorHandler(val messagesApi: MessagesApi) extends SecuredErrorHandler with I18nSupport { override def onNotAuthenticated(implicit req: RequestHeader): Future[Result] = { val message = "Unauthorized: please login" if (req.uri.startsWith("/api")) { Future.successful(Unauthorized(Json.toJson(ErrorResult(Status.UNAUTHORIZED, message, execMs = 0)))) } else { Future.successful(Redirect(AuthCtrl.login(Some(req.uri))).flashing("warning" -> message)) } } override def onNotAuthorized(implicit req: RequestHeader): Future[Result] = { val message = "Forbidden: it seems you lack some rights here" if (req.uri.startsWith("/api")) { Future.successful(Unauthorized(Json.toJson(ErrorResult(Status.FORBIDDEN, message, execMs = 0)))) } else { val next = Redirect(HttpUtils.getReferer(req.headers).getOrElse(UserCtrl.index().path())) Future.successful(next.flashing("error" -> message)) } } }
Example 16
Source File: TalkCtrlSpec.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.web.pages.user.talks import gospeak.core.domain.messages.Message import gospeak.libs.scala.BasicMessageBus import gospeak.libs.scala.domain.Page import gospeak.web.services.MessageSrv import gospeak.web.testingutils.CtrlSpec import org.scalatest.BeforeAndAfterEach import play.api.http.Status import play.api.test.Helpers._ class TalkCtrlSpec extends CtrlSpec with BeforeAndAfterEach { private val params = Page.Params() private val messageSrv = new MessageSrv(db.group, db.cfp, db.venue, db.proposal, db.sponsor, db.user) private val messageBus = new BasicMessageBus[Message]() private val ctrl = new TalkCtrl(cc, silhouette, conf, db.user, db.userRequest, db.talk, db.externalEvent, db.externalProposal, emailSrv, messageSrv, messageBus) override def beforeEach(): Unit = db.migrate().unsafeRunSync() override def afterEach(): Unit = db.dropTables().unsafeRunSync() describe("TalkCtrl") { describe("list") { it("should return 200") { val res = ctrl.list(params).apply(securedReq) status(res) shouldBe Status.OK contentAsString(res) should include("""<div class="jumbotron">""") } } } }
Example 17
Source File: HomeCtrlSpec.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.web.pages.published import gospeak.web.testingutils.CtrlSpec import play.api.http.Status import play.api.test.Helpers._ class HomeCtrlSpec extends CtrlSpec { private val ctrl = new HomeCtrl(cc, silhouette, conf, db.user, db.talk, db.group, db.cfp, db.event, db.proposal, db.externalCfp, db.externalEvent, db.externalProposal) describe("HomeCtrl") { it("should return 200") { val res = ctrl.index().apply(unsecuredReq) status(res) shouldBe Status.OK contentAsString(res) should include("Introducing Gospeak") } } }
Example 18
Source File: CfpCtrlSpec.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.web.pages.published.cfps import gospeak.core.domain.messages.Message import gospeak.libs.scala.BasicMessageBus import gospeak.libs.scala.domain.Page import gospeak.web.services.MessageSrv import gospeak.web.testingutils.CtrlSpec import org.scalatest.BeforeAndAfterEach import play.api.http.Status import play.api.test.Helpers._ class CfpCtrlSpec extends CtrlSpec with BeforeAndAfterEach { private val params = Page.Params() private val messageSrv = new MessageSrv(db.group, db.cfp, db.venue, db.proposal, db.sponsor, db.user) private val messageBus = new BasicMessageBus[Message]() private val ctrl = new CfpCtrl(cc, silhouette, conf, db.group, db.cfp, db.talk, db.proposal, db.userRequest, db.externalEvent, db.externalCfp, authSrv, emailSrv, messageSrv, messageBus) override def beforeEach(): Unit = db.migrate().unsafeRunSync() override def afterEach(): Unit = db.dropTables().unsafeRunSync() describe("CfpCtrl") { it("should display the cfp list page empty") { val res = ctrl.list(params).apply(unsecuredReq) status(res) shouldBe Status.OK } } }
Example 19
Source File: AuthCtrlSpec.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.web.auth import gospeak.core.domain.User import gospeak.core.testingutils.Generators._ import gospeak.libs.scala.domain.{EmailAddress, Secret} import gospeak.web.testingutils.CtrlSpec import gospeak.web.utils.GsForms.SignupData import org.scalatest.BeforeAndAfterEach import play.api.http.Status import play.api.mvc.{AnyContentAsFormUrlEncoded, RequestHeader, Result} import play.api.test.Helpers._ import scala.concurrent.Future class AuthCtrlSpec extends CtrlSpec with BeforeAndAfterEach { private val _ = aEmailAddress // to keep the `gospeak.core.testingutils.Generators._` import private val ctrl = new AuthCtrl(cc, silhouette, conf, db.user, db.userRequest, db.group, authSrv, emailSrv) private val redirect: Option[String] = None // private val signupData = random[SignupData] // TODO add generators constraints: firstName&lastName should not be empty, password should have 8 char at least private val signupData = SignupData(User.Slug.from("slug").right.get, "first", "last", EmailAddress.from("[email protected]").right.get, Secret("passpass"), rememberMe = true) override def beforeEach(): Unit = { db.migrate().unsafeRunSync() emailSrv.sentEmails.clear() } override def afterEach(): Unit = db.dropTables().unsafeRunSync() describe("AuthCtrl") { describe("signup") { it("should return form when not authenticated") { val res = ctrl.signup(redirect).apply(unsecuredReq) status(res) shouldBe Status.OK } it("should redirect to user home when authenticated") { val res = ctrl.signup(redirect).apply(securedReq) status(res) shouldBe Status.SEE_OTHER } it("should create a user and credentials then login") { val res = AuthCtrlSpec.doSignup(signupData)(unsecuredReq)(ctrl) contentAsString(res) shouldBe "" headers(res) should contain key "Location" status(res) shouldBe Status.SEE_OTHER emailSrv.sentEmails should have length 1 } it("should find the user, create credentials then login") { } it("should fail if credentials already exist") { } } describe("login") { it("should return form when not authenticated") { val res = ctrl.login(redirect).apply(unsecuredReq) status(res) shouldBe Status.OK } it("should redirect to user home when authenticated") { val res = ctrl.login(redirect).apply(securedReq) status(res) shouldBe Status.SEE_OTHER } } describe("forgotPassword") { it("should return form when not authenticated") { val res = ctrl.forgotPassword(redirect).apply(unsecuredReq) status(res) shouldBe Status.OK } it("should redirect to user home when authenticated") { val res = ctrl.forgotPassword(redirect).apply(securedReq) status(res) shouldBe Status.SEE_OTHER } } } } object AuthCtrlSpec { def doSignup(data: SignupData, redirect: Option[String] = None)(req: RequestHeader)(ctrl: AuthCtrl): Future[Result] = { ctrl.doSignup(redirect).apply(req.withBody(AnyContentAsFormUrlEncoded(Map( "slug" -> Seq(data.slug.value), "first-name" -> Seq(data.firstName), "last-name" -> Seq(data.lastName), "email" -> Seq(data.email.value), "password" -> Seq(data.password.decode), "rememberMe" -> Seq(data.rememberMe.toString) )))) } }
Example 20
Source File: TestAuthFixture.scala From metronome with Apache License 2.0 | 5 votes |
package dcos.metronome package api import dcos.metronome.utils.test.Mockito import mesosphere.marathon.core.plugin.{PluginDefinitions, PluginManager} import mesosphere.marathon.plugin.auth.{AuthorizedAction, Identity, Authorizer, Authenticator} import mesosphere.marathon.plugin.http.{HttpResponse, HttpRequest} import play.api.http.Status import scala.concurrent.Future import scala.reflect.ClassTag class TestAuthFixture extends Mockito with Status { type Auth = Authenticator with Authorizer val identity: Identity = new Identity {} var authenticated: Boolean = true var authorized: Boolean = true val authFn: Any => Boolean = { _ => true } def auth: Auth = new Authorizer with Authenticator { override def authenticate(request: HttpRequest): Future[Option[Identity]] = { Future.successful(if (authenticated) Some(identity) else None) } override def handleNotAuthenticated(request: HttpRequest, response: HttpResponse): Unit = { response.status(FORBIDDEN) } override def handleNotAuthorized(principal: Identity, response: HttpResponse): Unit = { response.status(UNAUTHORIZED) } override def isAuthorized[Resource]( principal: Identity, action: AuthorizedAction[Resource], resource: Resource ): Boolean = { authFn(resource) && authorized } } val pluginManager = new PluginManager { override def definitions: PluginDefinitions = PluginDefinitions.None override def plugins[T](implicit ct: ClassTag[T]): Seq[T] = ct.runtimeClass.getSimpleName match { case "Authorizer" => Seq(auth.asInstanceOf[T]) case "Authenticator" => Seq(auth.asInstanceOf[T]) case _ => Seq.empty[T] } } }
Example 21
Source File: SlackFail.scala From slack-client with MIT License | 5 votes |
package com.kifi.slack.models import play.api.http.Status import play.api.http.Status._ import play.api.libs.json._ // Failures on our end that deal with slack sealed abstract class SlackFail(val status: Int, val code: String, val extra: JsValue = JsNull) extends Exception(s"$code: ${Json.stringify(extra)}") { import play.api.mvc.Results.Status def asResponse = Status(status)(Json.obj("error" -> code, "extra" -> extra)) } object SlackFail { case object NoAppCredentials extends SlackFail(UNAUTHORIZED, "no_app_credentials") case object NoAuthCode extends SlackFail(BAD_REQUEST, "no_auth_code") case object InvalidAuthState extends SlackFail(BAD_REQUEST, "invalid_auth_state") case class MalformedPayload(payload: JsValue) extends SlackFail(BAD_REQUEST, "malformed_payload", payload) case class MalformedState(state: SlackAuthState) extends SlackFail(BAD_REQUEST, "malformed_state", JsString(state.state)) case class SlackResponse(response: SlackAPIErrorResponse) extends SlackFail(response.status, response.error, response.payload) } // Failures that Slack can give case class SlackAPIErrorResponse(status: Int, error: String, payload: JsValue) extends Exception(s"$status response: $error ($payload)") object SlackAPIErrorResponse { def ApiError(status: Int, payload: JsValue) = SlackAPIErrorResponse(status, (payload \ "error").asOpt[String] getOrElse "api_error", payload) val TokenRevoked = SlackAPIErrorResponse(Status.NOT_FOUND, SlackErrorCode.TOKEN_REVOKED, JsNull) val WebhookRevoked = SlackAPIErrorResponse(Status.NOT_FOUND, SlackErrorCode.WEBHOOK_REVOKED, JsNull) } object SlackErrorCode { def unapply(fail: SlackAPIErrorResponse) = Some(fail.error) val ACCOUNT_INACTIVE = "account_inactive" val ALREADY_REACTED = "already_reacted" val CANT_UPDATE_MESSAGE = "cant_update_message" val CHANNEL_NOT_FOUND = "channel_not_found" val EDIT_WINDOW_CLOSED = "edit_window_closed" val INVALID_AUTH = "invalid_auth" val IS_ARCHIVED = "is_archived" val MESSAGE_NOT_FOUND = "message_not_found" val NOT_IN_CHANNEL = "not_in_channel" val RESTRICTED_ACTION = "restricted_action" val TOKEN_REVOKED = "token_revoked" val WEBHOOK_REVOKED = "webhook_revoked" }
Example 22
Source File: HttpsFilter.scala From scala-clippy with Apache License 2.0 | 5 votes |
package controllers import play.api.http.Status import play.api.mvc.{Filter, RequestHeader, Result, Results} import scala.concurrent.Future class HttpsFilter extends Filter { def apply(nextFilter: (RequestHeader) => Future[Result])(requestHeader: RequestHeader): Future[Result] = requestHeader.headers.get("x-forwarded-proto") match { case Some(header) => if (header == "https") { nextFilter(requestHeader) } else { Future.successful( Results.Redirect("https://" + requestHeader.host + requestHeader.uri, Status.MOVED_PERMANENTLY) ) } case None => nextFilter(requestHeader) } }
Example 23
Source File: ControllerBaseSpec.scala From vat-api with Apache License 2.0 | 5 votes |
package v1.controllers import play.api.http.{HeaderNames, MimeTypes, Status} import play.api.mvc.{AnyContentAsEmpty, ControllerComponents} import play.api.test.Helpers.stubControllerComponents import play.api.test.{FakeRequest, ResultExtractors} import support.UnitSpec class ControllerBaseSpec extends UnitSpec with Status with MimeTypes with HeaderNames with ResultExtractors { implicit lazy val fakeRequest: FakeRequest[AnyContentAsEmpty.type] = FakeRequest() lazy val cc: ControllerComponents = stubControllerComponents() lazy val fakeGetRequest: FakeRequest[AnyContentAsEmpty.type] = fakeRequest.withHeaders( HeaderNames.AUTHORIZATION -> "Bearer Token", "X-Client-Id" -> "client-Id" ) def fakePostRequest[T](body: T): FakeRequest[T] = fakeRequest.withBody(body) }
Example 24
Source File: CitizenDetailsService.scala From nisp-frontend with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.nisp.services import javax.inject.Inject import play.api.Logger import play.api.http.Status import uk.gov.hmrc.domain.Nino import uk.gov.hmrc.nisp.connectors.CitizenDetailsConnector import uk.gov.hmrc.nisp.models.citizen.{Address, Citizen, CitizenDetailsError, CitizenDetailsResponse, MCI_EXCLUSION, NOT_FOUND, TECHNICAL_DIFFICULTIES} import uk.gov.hmrc.play.http.logging.MdcLoggingExecutionContext._ import scala.concurrent.Future import uk.gov.hmrc.http.{BadRequestException, HeaderCarrier, NotFoundException, Upstream4xxResponse} class CitizenDetailsService @Inject()(citizenDetailsConnector: CitizenDetailsConnector) { def retrievePerson(nino: Nino)(implicit hc: HeaderCarrier): Future[Either[CitizenDetailsError, CitizenDetailsResponse]] = { citizenDetailsConnector.connectToGetPersonDetails(nino) map ( citizen => Right(citizen)) recover { case ex: Upstream4xxResponse if ex.upstreamResponseCode == Status.LOCKED => Logger.warn(s"MCI Exclusion for $nino", ex) Left(MCI_EXCLUSION) case ex: BadRequestException => Logger.error(s"Citizen Details: BadRequest for $nino", ex) Left(TECHNICAL_DIFFICULTIES) case ex: NotFoundException => Logger.error(s"Citizen Details: NotFound for $nino", ex) Left(NOT_FOUND) } } }
Example 25
Source File: MockIdentityVerificationHttp.scala From nisp-frontend with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.nisp.helpers import org.mockito.ArgumentMatchers import org.mockito.Mockito._ import org.scalatest.mock.MockitoSugar import play.api.http.Status import play.api.libs.json.Json import scala.concurrent.Future import scala.io.Source import uk.gov.hmrc.http.{ HttpGet, HttpResponse } object MockIdentityVerificationHttp extends MockitoSugar { val mockHttp = mock[HttpGet] val possibleJournies = Map( "success-journey-id" -> "test/resources/identity-verification/success.json", "incomplete-journey-id" -> "test/resources/identity-verification/incomplete.json", "failed-matching-journey-id" -> "test/resources/identity-verification/failed-matching.json", "insufficient-evidence-journey-id" -> "test/resources/identity-verification/insufficient-evidence.json", "locked-out-journey-id" -> "test/resources/identity-verification/locked-out.json", "user-aborted-journey-id" -> "test/resources/identity-verification/user-aborted.json", "timeout-journey-id" -> "test/resources/identity-verification/timeout.json", "technical-issue-journey-id" -> "test/resources/identity-verification/technical-issue.json", "precondition-failed-journey-id" -> "test/resources/identity-verification/precondition-failed.json", "invalid-journey-id" -> "test/resources/identity-verification/invalid-result.json", "invalid-fields-journey-id" -> "test/resources/identity-verification/invalid-fields.json", "failed-iv-journey-id" -> "test/resources/identity-verification/failed-iv.json" ) def mockJourneyId(journeyId: String): Unit = { val fileContents = Source.fromFile(possibleJournies(journeyId)).mkString when(mockHttp.GET[HttpResponse](ArgumentMatchers.contains(journeyId))(ArgumentMatchers.any(), ArgumentMatchers.any(),ArgumentMatchers.any())). thenReturn(Future.successful(HttpResponse(Status.OK, responseJson = Some(Json.parse(fileContents))))) } possibleJournies.keys.foreach(mockJourneyId) }
Example 26
Source File: NispFrontendControllerSpec.scala From nisp-frontend with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.nisp.controllers import org.slf4j.{Logger => Slf4JLogger} import org.mockito.Mockito.{verify, when} import org.mockito.ArgumentMatchers._ import org.scalatest.mock.MockitoSugar import org.scalatestplus.play.OneAppPerSuite import play.api.Logger import play.api.http.Status import play.api.mvc.Result import play.api.test.FakeRequest import uk.gov.hmrc.nisp.config.{ApplicationGlobal, ApplicationGlobalTrait} import uk.gov.hmrc.nisp.helpers.{MockApplicationGlobal, MockCachedStaticHtmlPartialRetriever} import uk.gov.hmrc.nisp.utils.MockTemplateRenderer import uk.gov.hmrc.play.test.UnitSpec import uk.gov.hmrc.renderer.TemplateRenderer class NispFrontendControllerSpec extends UnitSpec with MockitoSugar with OneAppPerSuite { val mockLogger: Slf4JLogger = mock[Slf4JLogger] when(mockLogger.isErrorEnabled).thenReturn(true) def controller = new NispFrontendController { override val logger = new Logger(mockLogger) val cachedStaticHtmlPartialRetriever = MockCachedStaticHtmlPartialRetriever override implicit val templateRenderer: TemplateRenderer = MockTemplateRenderer override val applicationGlobal:ApplicationGlobalTrait = MockApplicationGlobal } implicit val request = FakeRequest() "onError" should { "should log error details" in { val result: Result = controller.onError(new Exception()) verify(mockLogger).error(anyString(), any[Exception]) } "should return an Internal Server Error (500)" in { val result: Result = controller.onError(new Exception()) status(result) shouldBe Status.INTERNAL_SERVER_ERROR } } }
Example 27
Source File: CatalogControllersSpec.scala From daf with BSD 3-Clause "New" or "Revised" License | 5 votes |
import java.io.IOException import java.net.ServerSocket import akka.actor.ActorSystem import akka.stream.ActorMaterializer import catalog_manager.yaml.MetaCatalog import org.specs2.mutable.Specification import play.api.Application import play.api.http.Status import play.api.routing.Router import play.api.inject.guice.GuiceApplicationBuilder import play.api.libs.json.{JsArray, JsValue, Json} import play.api.libs.ws.WSResponse import play.api.libs.ws.ahc.AhcWSClient import play.api.test._ import it.gov.daf.catalogmanager import it.gov.daf.catalogmanager.client.Catalog_managerClient import scala.concurrent.duration.Duration import scala.concurrent.{Await, Future} class CatalogControllersSpec extends Specification { def application: Application = GuiceApplicationBuilder().build() import catalog_manager.yaml.BodyReads.MetaCatalogReads "The catalog-manager" should { "Call catalog-manager/v1/dataset-catalogs return ok status" in new WithServer(app = application, port = 9000) { WsTestClient.withClient { implicit client => val response: WSResponse = Await.result[WSResponse](client. url(s"http://localhost:9001/catalog-manager/v1/dataset-catalogs"). execute, Duration.Inf) println(response.status) response.status must be equalTo Status.OK } } "Call catalog-manager/v1/dataset-catalogs return a non empty list if" + "you have error maybe is necessaty to add data to db" in new WithServer(app = application, port = 9000) { WsTestClient.withClient { implicit client => val response: WSResponse = Await.result[WSResponse](client. url(s"http://localhost:9001/catalog-manager/v1/dataset-catalogs"). execute, Duration.Inf) println(response.status) println("ALE") println(response.body) val json: JsValue = Json.parse(response.body) json.as[JsArray].value.size must be greaterThan (0) } } "The catalog-manager" should { "Call catalog-manager/v1/dataset-catalogs/{logical_uri} return ok status" in new WithServer(app = application, port = 9000) { val logicalUri = "daf://dataset/std/standard/standard/uri_cultura/standard" val url = s"http://localhost:9001/catalog-manager/v1/dataset-catalogs/$logicalUri" println(url) WsTestClient.withClient { implicit client => val response: WSResponse = Await.result[WSResponse](client. url(url). execute, Duration.Inf) println(response.status) response.status must be equalTo Status.OK } } } "The catalog-manager" should { "Call catalog-manager/v1/dataset-catalogs/{anything} return 401" in new WithServer(app = application, port = 9000) { val logicalUri = "anything" val url = s"http://localhost:9001/catalog-manager/v1/dataset-catalogs/$logicalUri" println(url) WsTestClient.withClient { implicit client => val response: WSResponse = Await.result[WSResponse](client. url(url). execute, Duration.Inf) println(response.status) response.status must be equalTo 401 } } } } }
Example 28
Source File: resources.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.vatapi import cats.data.EitherT import cats.implicits._ import play.api.Logger import play.api.http.Status import play.api.libs.json._ import play.api.mvc.Result import play.api.mvc.Results.InternalServerError import uk.gov.hmrc.vatapi.models.{AuthorisationErrorResult, ErrorResult, Errors, GenericErrorResult, InternalServerErrorResult, JsonValidationErrorResult, ValidationErrorResult} import uk.gov.hmrc.vatapi.resources.wrappers.Response import scala.concurrent.{ExecutionContext, Future} package object resources { type BusinessResult[T] = EitherT[Future, ErrorResult, T] val GovTestScenarioHeader = "Gov-Test-Scenario" def unhandledResponse(status: Int, logger: Logger): Result = { logger.error(s"Unhandled response from DES. Status code: $status. Returning 500 to client.") InternalServerError(Json.toJson(Errors.InternalServerError("An internal server error occurred"))) } def handleErrors(errorResult: ErrorResult): VatResult = { errorResult match { case GenericErrorResult(message) => VatResult.Failure(Status.BAD_REQUEST, Errors.badRequest(message)) case JsonValidationErrorResult(errors) => VatResult.Failure(Status.BAD_REQUEST,Errors.badRequest(errors)) case ValidationErrorResult(error) => VatResult.Failure(Status.BAD_REQUEST, Errors.badRequest(error)) case AuthorisationErrorResult(error) => VatResult.Failure(Status.FORBIDDEN, error) case InternalServerErrorResult(error) => VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError(error)) } } def validateJson[T](json: JsValue)(implicit reads: Reads[T], ec: ExecutionContext): BusinessResult[T] = BusinessResult { for { errors <- json.validate[T].asEither.left } yield JsonValidationErrorResult(errors) } def validate[T](value: T)(validate: PartialFunction[T, Errors.Error])(implicit ec: ExecutionContext): BusinessResult[T] = if (validate.isDefinedAt(value)) BusinessResult.failure(ValidationErrorResult(validate(value))) else BusinessResult.success(value) def authorise[T](value: T)(auth: PartialFunction[T, Errors.Error])(implicit ec: ExecutionContext): BusinessResult[T] = if (auth.isDefinedAt(value)) BusinessResult.failure(AuthorisationErrorResult(Errors.businessError(auth(value)))) else BusinessResult.success(value) def execute[T](torun: Unit => Future[T])(implicit ec: ExecutionContext): BusinessResult[T] = BusinessResult { for { result <- torun(()) } yield Right(result) } def fromDes[R <: Response](result: BusinessResult[R]): DesBusinessResult[R] = DesBusinessResult(result) object BusinessResult { def apply[T](eventuallyErrorOrResult: Future[Either[ErrorResult, T]]): BusinessResult[T] = new EitherT(eventuallyErrorOrResult) def apply[T](errorOrResult: Either[ErrorResult, T])(implicit ec: ExecutionContext): BusinessResult[T] = EitherT.fromEither(errorOrResult) def success[T](value: T)(implicit ec: ExecutionContext): BusinessResult[T] = EitherT.fromEither(Right(value)) def failure[T](error: ErrorResult)(implicit ec: ExecutionContext): BusinessResult[T] = EitherT.fromEither(Left(error)) } }
Example 29
Source File: ObligationsResponse.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.vatapi.resources.wrappers import play.api.http.Status import uk.gov.hmrc.domain.Vrn import uk.gov.hmrc.http.HttpResponse import uk.gov.hmrc.vatapi.models.des.DesErrorCode._ import uk.gov.hmrc.vatapi.models.des.ObligationDetail import uk.gov.hmrc.vatapi.models.{DesTransformError, Obligations, _} import uk.gov.hmrc.vatapi.resources.VatResult case class ObligationsResponse(underlying: HttpResponse) extends Response { def obligations(vrn: Vrn): Either[DesTransformError, Option[Obligations]] = { def error(message: String): Either[DesTransformError, Option[Obligations]] = { logger.error(s"[ObligationsResponse][error] $message. status: ${underlying.status}") Left(new DesTransformError { val msg = message }) } def oneFound(obligation: des.Obligations): Either[DesTransformError, Option[Obligations]] = { val obligationsOrError = obligation.obligations.filter(obj => obj.obligationDetails.nonEmpty).flatMap { desObligation => desObligation.obligationDetails.map { details => DesTransformValidator[ObligationDetail, Obligation].from(details) } } obligationsOrError.find(_.isLeft) match { case Some(ex) => Left(ex.left.get) case _ if obligationsOrError.map(_.right.get).isEmpty => Right(None) case _ => Right(Some(Obligations(obligationsOrError.map(_.right.get)))) } } jsonOrError match { case Right(js) => logger.debug(s"[ObligationsResponse][desObligations] Json response body from DES : $js") js.asOpt[des.Obligations] match { case Some(obligations) => oneFound(obligations) case _ => error("The response from DES does not match the expected format") } case _ => logger.error(s"[ObligationsResponse][desObligations] Non json response from DES : ${underlying.status}") error("Non json response from DES") } } override def errorMappings: PartialFunction[Int, VatResult] = { case 400 if errorCodeIsOneOf(INVALID_IDNUMBER) => VatResult.Failure(Status.BAD_REQUEST, Errors.VrnInvalid) case 400 if errorCodeIsOneOf(INVALID_DATE_TO) => VatResult.Failure(Status.BAD_REQUEST, Errors.InvalidDateTo) case 400 if errorCodeIsOneOf(INVALID_DATE_FROM) => VatResult.Failure(Status.BAD_REQUEST, Errors.InvalidDateFrom) case 400 if errorCodeIsOneOf(INVALID_DATE_RANGE) => VatResult.Failure(Status.BAD_REQUEST, Errors.DateRangeTooLarge) case 400 if errorCodeIsOneOf(INVALID_STATUS) => VatResult.Failure(Status.BAD_REQUEST, Errors.InvalidStatus) case 400 if errorCodeIsOneOf(INVALID_IDTYPE, INVALID_REGIME, NOT_FOUND_BPKEY) => VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError) case 404 if errorCodeIsOneOf(NOT_FOUND) => VatResult.Failure(Status.NOT_FOUND, Errors.NotFound) } }
Example 30
Source File: FinancialDataResponse.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.vatapi.resources.wrappers import play.api.http.Status import play.api.libs.json.{JsError, JsSuccess, JsValue} import uk.gov.hmrc.domain.Vrn import uk.gov.hmrc.http.HttpResponse import uk.gov.hmrc.vatapi.models.des.DesErrorCode._ import uk.gov.hmrc.vatapi.models.{DesTransformError, DesTransformValidator, Errors, Liabilities, Payments, des} import uk.gov.hmrc.vatapi.resources.VatResult case class FinancialDataResponse(underlying: HttpResponse) extends Response { def getLiabilities(vrn: Vrn): Either[DesTransformError, Liabilities] = { def deserialise(js: JsValue) = js.validate[des.FinancialData] match { case JsError(errors) => Left(ParseError(s"[FinancialDataResponse][getLiabilities - deserialise] Json format from DES doesn't match the FinancialData model: $errors")) case JsSuccess(financialData, _) => DesTransformValidator[des.FinancialData, Liabilities].from(financialData) } jsonOrError match { case Right(js) => logger.debug(s"[FinancialDataResponse][getLiabilities - jsonOrError] Json response body from DES : ${js}") deserialise(js) case Left(e) => logger.error(s"[FinancialDataResponse][getLiabilities - jsonOrError] Non json response from DES : ${e.getMessage}") Left(ParseError(s"Unable to parse the response from DES as Json: $e")) } } def getPayments(vrn: Vrn): Either[DesTransformError, Payments] = { def deserialise(js: JsValue) = js.validate[des.FinancialData] match { case JsError(errors) => Left(ParseError(s"[FinancialDataResponse][getPayments - deserialise] Json format from DES doesn't match the FinancialData model: $errors")) case JsSuccess(financialData, _) => DesTransformValidator[des.FinancialData, Payments].from(financialData) } jsonOrError match { case Right(js) => logger.debug(s"[FinancialDataResponse][getPayments - jsonOrError] Json response body from DES : ${js}") deserialise(js) case Left(e) => logger.error(s"[FinancialDataResponse][getPayments - jsonOrError] Non json response from DES : ${e.getMessage}") Left(ParseError(s"Unable to parse the response from DES as Json: $e")) } } override def errorMappings: PartialFunction[Int, VatResult] = { case 400 if errorCodeIsOneOf(INVALID_IDNUMBER) => VatResult.Failure(Status.BAD_REQUEST, Errors.VrnInvalid) case 400 if errorCodeIsOneOf(INVALID_DATEFROM) => VatResult.Failure(Status.BAD_REQUEST, Errors.InvalidDateFrom) case 400 if errorCodeIsOneOf(INVALID_DATETO) => VatResult.Failure(Status.BAD_REQUEST,Errors.InvalidDateTo) case 400 if errorCodeIsOneOf(NOT_FOUND) => VatResult.Failure(Status.NOT_FOUND, Errors.NotFound) case 400 if errorCodeIsOneOf(INVALID_IDTYPE, INVALID_ONLYOPENITEMS, INVALID_REGIMETYPE, INVALID_INCLUDELOCKS, INVALID_CALCULATEACCRUEDINTEREST, INVALID_CUSTOMERPAYMENTINFORMATION ) => VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError) case 404 if errorCodeIsOneOf(NOT_FOUND) => VatResult.Failure(Status.NOT_FOUND,Errors.NotFound) case 422 if errorCodeIsOneOf(INVALID_DATA) => VatResult.Failure(Status.BAD_REQUEST,Errors.InvalidData) } }
Example 31
Source File: VatReturnResponse.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.vatapi.resources.wrappers import play.api.http.Status import play.api.libs.json.{JsError, JsSuccess, JsValue} import uk.gov.hmrc.http.HttpResponse import uk.gov.hmrc.vatapi.httpparsers.NRSData import uk.gov.hmrc.vatapi.models.des.DesErrorCode._ import uk.gov.hmrc.vatapi.models.{DesTransformError, DesTransformValidator, Errors, VatReturn, des} import uk.gov.hmrc.vatapi.resources.VatResult case class VatReturnResponse(underlying: HttpResponse) extends Response { var nrsData: NRSData = _ def vatReturnOrError: Either[DesTransformError, VatReturn] = { def deserialise(js: JsValue) = js.validate[des.VatReturn] match { case JsError(errors) => Left(ParseError(s"Json format from DES doesn't match the VatReturn model: $errors")) case JsSuccess(vatReturn, _) => DesTransformValidator[des.VatReturn, VatReturn].from(vatReturn) } jsonOrError match { case Left(e) => logger.error(s"[VatReturnResponse][vatReturnOrError] Non json response from DES : $e") Left(ParseError(s"Unable to parse the response from DES as Json: $e")) case Right(js) => deserialise(js) } } def vatSubmissionReturnOrError: Either[DesTransformError, JsValue] = { jsonOrError match { case Left(e) => logger.error(s"[VatReturnResponse][vatReturnOrError] Non json response from DES : $e") Left(ParseError(s"Unable to parse the response from DES as Json: $e")) case Right(js) => Right(js) } } def withNrsData(data: NRSData): VatReturnResponse = { nrsData = data; this } override def errorMappings: PartialFunction[Int, VatResult] = { case 400 if errorCodeIsOneOf(INVALID_VRN) => VatResult.Failure(Status.BAD_REQUEST, Errors.VrnInvalid) case 400 if errorCodeIsOneOf(INVALID_ARN) => VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError) case 400 if errorCodeIsOneOf(INVALID_ORIGINATOR_ID) => VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError) case 400 if errorCodeIsOneOf(INVALID_PAYLOAD) => VatResult.Failure(Status.BAD_REQUEST, Errors.InvalidRequest) case 400 if errorCodeIsOneOf(INVALID_PERIODKEY) => VatResult.Failure(Status.BAD_REQUEST, Errors.InvalidPeriodKey) case 400 if errorCodeIsOneOf(INVALID_SUBMISSION) => logger.info(s"[VatReturnResponse][errorMappings] Des returned error with status 400 and errorCode INVALID_SUBMISSION") VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError) case 403 if errorCodeIsOneOf(DATE_RANGE_TOO_LARGE) => VatResult.Failure(Status.FORBIDDEN, Errors.businessError(Errors.DateRangeTooLarge)) case 403 if errorCodeIsOneOf(VRN_NOT_FOUND, NOT_FOUND_VRN) => VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError) case 403 if errorCodeIsOneOf(INVALID_IDENTIFIER) => VatResult.Failure(Status.NOT_FOUND, Errors.InvalidPeriodKey) case 403 if errorCodeIsOneOf(INVALID_INPUTDATA) => VatResult.Failure(Status.FORBIDDEN, Errors.InvalidRequest) case 403 if errorCodeIsOneOf(TAX_PERIOD_NOT_ENDED) => VatResult.Failure(Status.FORBIDDEN, Errors.TaxPeriodNotEnded) case 409 if errorCodeIsOneOf(DUPLICATE_SUBMISSION) => VatResult.Failure(Status.FORBIDDEN, Errors.businessError(Errors.DuplicateVatSubmission)) } } case class ParseError(msg: String) extends DesTransformError
Example 32
Source File: Response.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.vatapi.resources.wrappers import play.api.Logger import play.api.http.Status import play.api.libs.json.JsValue import uk.gov.hmrc.http.HttpResponse import uk.gov.hmrc.vatapi.models.Errors import uk.gov.hmrc.vatapi.models.des.DesError import uk.gov.hmrc.vatapi.models.des.DesErrorCode.{DesErrorCode, _} import uk.gov.hmrc.vatapi.resources.{AuthRequest, VatResult} import uk.gov.hmrc.vatapi.utils.pagerDutyLogging.{Endpoint, PagerDutyLogging} import scala.PartialFunction.{apply => _, _} import scala.util.{Failure, Success, Try} object Response { val defaultCorrelationId = "No Correlation ID" def getCorrelationId(httpResponse: HttpResponse): String = httpResponse.header("CorrelationId").getOrElse(defaultCorrelationId) } trait Response { val logger: Logger = Logger(this.getClass) val status: Int = underlying.status def underlying: HttpResponse def filter[A](pf: PartialFunction[Int, VatResult])(implicit endpoint: Endpoint, request: AuthRequest[A]): VatResult = { val statusPrefix: Int = status / 100 statusPrefix match { case 4 | 5 => val message = s"DES error occurred. User type: ${request.authContext.affinityGroup}\n" + s"Status code: ${underlying.status}\nBody: ${underlying.body}" PagerDutyLogging.logError(endpoint.toLoggerMessage, message, statusPrefix, logger.error(_)) (pf orElse errorMappings orElse standardErrorMapping) (status) case _ => (pf andThen addCorrelationHeader) (status) } } private def addCorrelationHeader(result: VatResult) = underlying .header("CorrelationId") .fold(result)(correlationId => result.withHeaders("X-CorrelationId" -> correlationId)) def errorMappings: PartialFunction[Int, VatResult] = empty private def standardErrorMapping: PartialFunction[Int, VatResult] = { case 404 => VatResult.FailureEmptyBody(Status.NOT_FOUND, Errors.NotFound) case 500 if errorCodeIsOneOf(SERVER_ERROR) => VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError) case 503 if errorCodeIsOneOf(SERVICE_UNAVAILABLE) => VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError) case _ => VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError) } def errorCodeIsOneOf(errorCodes: DesErrorCode*): Boolean = jsonOrError match { case Right(json) => json.asOpt[DesError].exists(errorCode => errorCodes.contains(errorCode.code)) case Left(_) => false } def jsonOrError: Either[Throwable, JsValue] = { Try(underlying.json) match { case Success(null) => Left(new RuntimeException) case Success(json) => Right(json) case Failure(e) => Left(e) } } def getCorrelationId: String = Response.getCorrelationId(underlying) }
Example 33
Source File: DocumentationControllerISpec.scala From vat-api with Apache License 2.0 | 5 votes |
package config import play.api.http.Status import play.api.libs.json.{JsValue, Json} import play.api.libs.ws.WSResponse import support.IntegrationBaseSpec class DocumentationControllerISpec extends IntegrationBaseSpec { val apiDefinitionJson: JsValue = Json.parse( """ |{ | "scopes":[ | { | "key":"read:vat", | "name":"View your VAT information", | "description":"Allow read access to VAT data" | }, | { | "key":"write:vat", | "name":"Change your VAT information", | "description":"Allow write access to VAT data" | } | ], | "api":{ | "name":"VAT (MTD)", | "description":"An API for providing VAT data", | "context":"organisations/vat", | "categories":["VAT_MTD"], | "versions":[ | { | "version":"1.0", | "status":"BETA", | "endpointsEnabled":true | } | ] | } |} """.stripMargin) "GET /api/definition" should { "return a 200 with the correct response body" in { val response: WSResponse = await(buildRequest("/api/definition").get()) response.status shouldBe Status.OK Json.parse(response.body) shouldBe apiDefinitionJson } } "a documentation request" must { "return the documentation" in { val response: WSResponse = await(buildRequest("/api/conf/1.0/application.raml").get()) response.status shouldBe Status.OK response.body[String] should startWith("#%RAML 1.0") } } }
Example 34
Source File: SemanticRepositorySpecs.scala From daf-semantics with Apache License 2.0 | 5 votes |
package specs import org.junit.runner.RunWith import scala.concurrent.{ Await, Future } import scala.concurrent.duration.Duration import play.api.test._ import play.api.http.Status import play.api.Application import play.api.inject.guice.GuiceApplicationBuilder import play.api.libs.ws.WSResponse import play.api.libs.ws.ahc.AhcWSClient import org.specs2.runner.JUnitRunner import org.specs2.mutable.Specification import play.api.libs.json.Json //import it.almawave.linkeddata.kb.utils.ConfigHelper import scala.collection.JavaConversions._ import scala.collection.JavaConverters._ import play.twirl.api.Content import play.api.test.Helpers._ import play.api.libs.json.JsObject import java.io.File import play.api.http.Writeable import akka.stream.scaladsl.Source import play.api.mvc.MultipartFormData import play.api.libs.Files.TemporaryFile import java.nio.file.Files import org.asynchttpclient.AsyncHttpClient import play.api.libs.ws.WS import akka.util.ByteString import play.api.mvc.MultipartFormData.DataPart import play.api.mvc.MultipartFormData.FilePart import akka.stream.scaladsl.FileIO import play.api.libs.ws.WSClient /* * TODO: REWRITE */ @RunWith(classOf[JUnitRunner]) class SemanticRepositorySpecs extends Specification { def application: Application = GuiceApplicationBuilder().build() "The semantic repository" should { "call kb/v1/contexts to obtain a list of contexts" in { new WithServer(app = application, port = 9999) { WsTestClient.withClient { implicit client => val response: WSResponse = Await.result[WSResponse]( client.url(s"http://localhost:${port}/kb/v1/contexts").execute, Duration.Inf) response.status must be equalTo Status.OK response.json.as[Seq[JsObject]].size must be equals 0 // response.json.as[Seq[JsObject]].size must be greaterThan 0 // if pre-loaded ontologies! } } } "call kb/v1/contexts ensuring all contexts have triples" in { new WithServer(app = application, port = 9999) { WsTestClient.withClient { implicit client => val response: WSResponse = Await.result[WSResponse]( client.url(s"http://localhost:${port}/kb/v1/contexts").execute, Duration.Inf) val json_list = response.json.as[Seq[JsObject]] forall(json_list)((_) must not beNull) forall(json_list)(_.keys must contain("context", "triples")) forall(json_list)(item => (item \ "triples").get.as[Int] > 0) } } } } }
Example 35
Source File: ResourceSpec.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.vatapi.resources import org.scalatest.OptionValues import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec import play.api.http.{HeaderNames, MimeTypes, Status} import play.api.mvc.ControllerComponents import play.api.test.Helpers.stubControllerComponents import play.api.test.{DefaultAwaitTimeout, ResultExtractors} import uk.gov.hmrc.domain.Vrn import uk.gov.hmrc.vatapi.TestUtils import uk.gov.hmrc.vatapi.config.AppContext import uk.gov.hmrc.vatapi.mocks.auth.MockAuthorisationService trait ResourceSpec extends AnyWordSpec with Matchers with OptionValues with TestUtils with ResultExtractors with HeaderNames with Status with DefaultAwaitTimeout with MimeTypes with MockAuthorisationService { val vrn: Vrn = generateVrn val mockAppContext = mock[AppContext] lazy val cc: ControllerComponents = stubControllerComponents() def mockAuthAction(vrn: Vrn) = { MockAuthorisationService.authCheck(vrn) } def mockAuthActionWithNrs(vrn: Vrn) = { MockAuthorisationService.authCheckWithNrsRequirement(vrn) } }
Example 36
Source File: AuditResponseSpec.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.vatapi.models.audit import play.api.http.Status import play.api.libs.json.Json import uk.gov.hmrc.vatapi.UnitSpec import v2.models.audit.AuditError class AuditResponseSpec extends UnitSpec { private val vatReturnDeclarationJson = Json.parse( """ |{ | "periodKey":"#001", | "vatDueSales":7000, | "vatDueAcquisitions":3000, | "totalVatDue":10000, | "vatReclaimedCurrPeriod":1000, | "netVatDue":9000, | "totalValueSalesExVAT":1000, | "totalValuePurchasesExVAT":200, | "totalValueGoodsSuppliedExVAT":100, | "totalAcquisitionsExVAT":540 | } """.stripMargin) private val responseSuccess = AuditResponse(Status.OK, None, Some(vatReturnDeclarationJson)) private val responseFail = AuditResponse(Status.BAD_REQUEST, Some(Seq(AuditError("VRN_INVALID"))), None) "writes" when { "passed an audit response model with success tax calculation field" should { "produce valid json" in { val json = Json.parse( s""" |{ | "httpStatus": 200, | "payload": $vatReturnDeclarationJson |} """.stripMargin) Json.toJson(responseSuccess) shouldBe json } } "passed an audit response model with error field" should { "produce valid json" in { val json = Json.parse( s""" |{ | "httpStatus": 400, | "errors": [ | { | "errorCode": "VRN_INVALID" | } | ] |} """.stripMargin) Json.toJson(responseFail) shouldBe json } } } }
Example 37
Source File: AuditDetailSpec.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.vatapi.models.audit import play.api.http.Status import play.api.libs.json.Json import uk.gov.hmrc.vatapi.UnitSpec import v2.models.audit.AuditError class AuditDetailSpec extends UnitSpec { private val userType = "Organisation" private val agentReferenceNumber = Some("012345678") private val clientId = "123456789" private val `X-CorrelationId` = "X-123" private val vatReturnDeclarationJson = Json.parse( """ |{ | "periodKey":"#001", | "vatDueSales":7000, | "vatDueAcquisitions":3000, | "totalVatDue":10000, | "vatReclaimedCurrPeriod":1000, | "netVatDue":9000, | "totalValueSalesExVAT":1000, | "totalValuePurchasesExVAT":200, | "totalValueGoodsSuppliedExVAT":100, | "totalAcquisitionsExVAT":540 | } """.stripMargin) private val responseSuccess = AuditResponse(Status.OK, None, Some(vatReturnDeclarationJson)) private val responseFail = AuditResponse(Status.BAD_REQUEST, Some(Seq(AuditError("VRN_INVALID"))), None) "writes" when { "passed an audit detail model with success response" should { "produce valid json" in { val jsonResponse = Json.stringify(vatReturnDeclarationJson) val json = Json.parse( s""" |{ | "arn": "012345678", | "userType": "Agent", | "X-CorrelationId": "X-123", | "response": { | "httpStatus": 200, | "payload": $jsonResponse | }, | "applicationProductionClientId": "$clientId" |} """.stripMargin) val model = AuditDetail("Agent", agentReferenceNumber, `X-CorrelationId`, response = responseSuccess, clientId) Json.toJson(model) shouldBe json } } "passed an audit detail model with errors field" should { "produce valid json" in { val json = Json.parse( s""" |{ | "userType": "Organisation", | "X-CorrelationId": "X-123", | "response": { | "httpStatus": 400, | "errors": [ | { | "errorCode": "VRN_INVALID" | } | ] | }, | "applicationProductionClientId": "$clientId" |} """.stripMargin) val model = AuditDetail(userType, None, `X-CorrelationId`, responseFail, clientId) Json.toJson(model) shouldBe json } } } }
Example 38
Source File: ErrorHandler.scala From Aton with GNU General Public License v3.0 | 5 votes |
import com.google.inject.Inject import play.api.{Application, Play} import play.api.http.{DefaultHttpErrorHandler, HttpErrorHandler, Status} import play.api.mvc.{RequestHeader, Result, Results} import views.html.index import scala.concurrent.Future class ErrorHandler @Inject()(errorHandler: DefaultHttpErrorHandler) extends HttpErrorHandler { override def onClientError(request: RequestHeader, statusCode: Int, message: String): Future[Result] = { statusCode match { case clientError if statusCode > 400 && statusCode < 500 => Future.successful(Results.NotFound(index("Aton"))) case _ => Future.successful(Results.ServiceUnavailable("Unexpected error happened")) } } override def onServerError(request: RequestHeader, exception: Throwable): Future[Result] = { errorHandler.onServerError(request,exception) } }
Example 39
Source File: StatusCtrl.scala From Cortex with GNU Affero General Public License v3.0 | 5 votes |
package org.thp.cortex.controllers import scala.concurrent.ExecutionContext import play.api.Configuration import play.api.http.Status import play.api.libs.json.Json.toJsFieldJsValueWrapper import play.api.libs.json.{JsBoolean, JsString, Json} import play.api.mvc.{AbstractController, Action, AnyContent, ControllerComponents} import com.sksamuel.elastic4s.http.ElasticDsl import javax.inject.{Inject, Singleton} import org.elasticsearch.client.Node import org.thp.cortex.models.Worker import org.elastic4play.database.DBIndex import org.elastic4play.services.AuthSrv import org.elastic4play.services.auth.MultiAuthSrv @Singleton class StatusCtrl @Inject()( configuration: Configuration, authSrv: AuthSrv, dbIndex: DBIndex, components: ControllerComponents, implicit val ec: ExecutionContext ) extends AbstractController(components) with Status { private[controllers] def getVersion(c: Class[_]) = Option(c.getPackage.getImplementationVersion).getOrElse("SNAPSHOT") def get: Action[AnyContent] = Action { Ok( Json.obj( "versions" → Json.obj( "Cortex" → getVersion(classOf[Worker]), "Elastic4Play" → getVersion(classOf[AuthSrv]), "Play" → getVersion(classOf[AbstractController]), "Elastic4s" → getVersion(classOf[ElasticDsl]), "ElasticSearch client" → getVersion(classOf[Node]) ), "config" → Json.obj( "protectDownloadsWith" → configuration.get[String]("datastore.attachment.password"), "authType" → (authSrv match { case multiAuthSrv: MultiAuthSrv ⇒ multiAuthSrv.authProviders.map { a ⇒ JsString(a.name) } case _ ⇒ JsString(authSrv.name) }), "capabilities" → authSrv.capabilities.map(c ⇒ JsString(c.toString)), "ssoAutoLogin" → JsBoolean(configuration.getOptional[Boolean]("auth.sso.autologin").getOrElse(false)) ) ) ) } def health: Action[AnyContent] = TODO }
Example 40
Source File: OrganizationCtrl.scala From Cortex with GNU Affero General Public License v3.0 | 5 votes |
package org.thp.cortex.controllers import javax.inject.{Inject, Singleton} import scala.concurrent.{ExecutionContext, Future} import play.api.Logger import play.api.http.Status import play.api.mvc._ import org.thp.cortex.models.Roles import org.thp.cortex.services.{OrganizationSrv, UserSrv} import org.elastic4play.{BadRequestError, NotFoundError} import org.elastic4play.controllers.{Authenticated, Fields, FieldsBodyParser, Renderer} import org.elastic4play.models.JsonFormat.baseModelEntityWrites import org.elastic4play.services.JsonFormat.{aggReads, queryReads} import org.elastic4play.services.{UserSrv ⇒ _, _} @Singleton class OrganizationCtrl @Inject()( organizationSrv: OrganizationSrv, authSrv: AuthSrv, auxSrv: AuxSrv, userSrv: UserSrv, authenticated: Authenticated, renderer: Renderer, fieldsBodyParser: FieldsBodyParser, components: ControllerComponents, implicit val ec: ExecutionContext ) extends AbstractController(components) with Status { private[OrganizationCtrl] lazy val logger = Logger(getClass) def create: Action[Fields] = authenticated(Roles.superAdmin).async(fieldsBodyParser) { implicit request ⇒ organizationSrv .create(request.body) .map(organization ⇒ renderer.toOutput(CREATED, organization)) } def get(organizationId: String): Action[Fields] = authenticated(Roles.superAdmin, Roles.orgAdmin).async(fieldsBodyParser) { implicit request ⇒ val withStats = request.body.getBoolean("nstats").getOrElse(false) (for { userOrganizationId ← if (request.roles.contains(Roles.superAdmin)) Future.successful(organizationId) else userSrv.getOrganizationId(request.userId) if userOrganizationId == organizationId organization ← organizationSrv.get(organizationId) organizationWithStats ← auxSrv(organization, 0, withStats, removeUnaudited = false) } yield renderer.toOutput(OK, organizationWithStats)) .recoverWith { case _: NoSuchElementException ⇒ Future.failed(NotFoundError(s"organization $organizationId not found")) } } def update(organizationId: String): Action[Fields] = authenticated(Roles.superAdmin).async(fieldsBodyParser) { implicit request ⇒ if (organizationId == "cortex") Future.failed(BadRequestError("Cortex organization can't be updated")) else organizationSrv.update(organizationId, request.body).map { organization ⇒ renderer.toOutput(OK, organization) } } def delete(organizationId: String): Action[AnyContent] = authenticated(Roles.superAdmin).async { implicit request ⇒ if (organizationId == "cortex") Future.failed(BadRequestError("Cortex organization can't be removed")) else organizationSrv .delete(organizationId) .map(_ ⇒ NoContent) } def find: Action[Fields] = authenticated(Roles.superAdmin).async(fieldsBodyParser) { implicit request ⇒ val query = request.body.getValue("query").fold[QueryDef](QueryDSL.any)(_.as[QueryDef]) val range = request.body.getString("range") val sort = request.body.getStrings("sort").getOrElse(Nil) val withStats = request.body.getBoolean("nstats").getOrElse(false) val (organizations, total) = organizationSrv.find(query, range, sort) val organizationWithStats = auxSrv(organizations, 0, withStats, removeUnaudited = false) renderer.toOutput(OK, organizationWithStats, total) } def stats(): Action[Fields] = authenticated(Roles.superAdmin).async(fieldsBodyParser) { implicit request ⇒ val query = request.body.getValue("query").fold[QueryDef](QueryDSL.any)(_.as[QueryDef]) val aggs = request.body.getValue("stats").getOrElse(throw BadRequestError("Parameter \"stats\" is missing")).as[Seq[Agg]] organizationSrv.stats(query, aggs).map(s ⇒ Ok(s)) } }
Example 41
Source File: StructuredAccessControl.scala From naptime with Apache License 2.0 | 5 votes |
package org.coursera.naptime.access import org.coursera.naptime.NaptimeActionException import org.coursera.naptime.access.authenticator.Authenticator import org.coursera.naptime.access.authorizer.AuthorizeResult import org.coursera.naptime.access.authorizer.Authorizer import play.api.http.Status import play.api.mvc.RequestHeader import scala.concurrent.ExecutionContext import scala.concurrent.Future case class StructuredAccessControl[A](authenticator: Authenticator[A], authorizer: Authorizer[A]) extends HeaderAccessControl[A] { override def run(requestHeader: RequestHeader)( implicit executionContext: ExecutionContext): Future[Either[NaptimeActionException, A]] = { Authenticator.authenticateAndRecover(authenticator, requestHeader).map { decoratedOption => decoratedOption .map { either => either.right.flatMap { decorated => Authorizer.toResponse(authorizer.authorize(decorated), decorated) } } .getOrElse { StructuredAccessControl.missingResponse } } } override private[naptime] def check(authInfo: A): Either[NaptimeActionException, A] = { Authorizer.toResponse(authorizer.authorize(authInfo), authInfo) } } object StructuredAccessControl { private[access] val missingResponse = { Left( NaptimeActionException( Status.UNAUTHORIZED, Some("auth.perms"), Some("Missing authentication"))) } }
Example 42
Source File: SuccessfulOf.scala From naptime with Apache License 2.0 | 5 votes |
package org.coursera.naptime.access.combiner import org.coursera.common.concurrent.Futures import org.coursera.naptime.NaptimeActionException import org.coursera.naptime.access.HeaderAccessControl import play.api.http.Status import play.api.mvc.RequestHeader import scala.collection.immutable import scala.concurrent.ExecutionContext import scala.concurrent.Future def successfulOf[A]( controls: immutable.Seq[HeaderAccessControl[A]]): HeaderAccessControl[Set[A]] = { new HeaderAccessControl[Set[A]] { override def run(requestHeader: RequestHeader)( implicit ec: ExecutionContext): Future[Either[NaptimeActionException, Set[A]]] = { Future .traverse(controls) { control => Futures.safelyCall(control.run(requestHeader)) } .map { results => val successes = results.collect { case Right(authentication) => authentication } lazy val firstErrorOption = results.collectFirst { case Left(error) => error } if (successes.nonEmpty) { Right(successes.toSet) } else { firstErrorOption match { case Some(error) => Left(error) case None => badAccessControlsResponse } } } } override def check(authInfo: Set[A]): Either[NaptimeActionException, Set[A]] = { if (authInfo.nonEmpty) Right(authInfo) else badAccessControlsResponse } } } } object SuccessfulOf { private[combiner] val badAccessControlsResponse = { Left( NaptimeActionException( Status.UNAUTHORIZED, Some("auth.perms"), Some("Invalid access control configuration"))) } }
Example 43
Source File: ReleaseTwoIntegrationSpec.scala From self-assessment-api with Apache License 2.0 | 5 votes |
package support import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec import org.scalatestplus.play.guice.GuiceOneServerPerSuite import play.api.Application import play.api.http.{HeaderNames, MimeTypes, Status} import play.api.inject.guice.GuiceApplicationBuilder import support.functional.FunctionalSyntax import support.wiremock.WireMockSupport trait ReleaseTwoIntegrationSpec extends AnyWordSpec with GuiceOneServerPerSuite with WireMockSupport with Matchers with Status with HeaderNames with MimeTypes with FakeApplicationConfig with FunctionalSyntax { override implicit lazy val app: Application = new GuiceApplicationBuilder() .configure(fakeApplicationConfig + ("feature-switch.release-2.enabled" -> true)) .build() }