Skip to content

Commit

Permalink
added userDetails
Browse files Browse the repository at this point in the history
  • Loading branch information
RobertLaverick committed Dec 5, 2024
1 parent 6bd2634 commit 8bf5236
Show file tree
Hide file tree
Showing 20 changed files with 105 additions and 79 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@ import play.api.libs.json.Json
import play.api.mvc._
import uk.gov.hmrc.auth.core.AffinityGroup.Organisation
import uk.gov.hmrc.auth.core._
import uk.gov.hmrc.auth.core.retrieve.v2.Retrievals.{affinityGroup, allEnrolments, credentials, internalId}
import uk.gov.hmrc.auth.core.retrieve.v2.Retrievals.{affinityGroup, allEnrolments, credentials, groupIdentifier, internalId}
import uk.gov.hmrc.auth.core.retrieve.~
import uk.gov.hmrc.excisemovementcontrolsystemapi.models.auditing.UserDetails
import uk.gov.hmrc.excisemovementcontrolsystemapi.models.auth.{EnrolmentKey, EnrolmentRequest}
import uk.gov.hmrc.excisemovementcontrolsystemapi.models.{ErrorResponse => EMCSErrorResponse}
import uk.gov.hmrc.excisemovementcontrolsystemapi.utils.DateTimeService
Expand All @@ -47,7 +48,7 @@ class AuthActionImpl @Inject() (
with AuthAction
with Logging {

private val fetch = allEnrolments and affinityGroup and credentials and internalId
private val fetch = allEnrolments and affinityGroup and credentials and internalId and groupIdentifier

protected def executionContext: ExecutionContext = ec

Expand Down Expand Up @@ -98,14 +99,14 @@ class AuthActionImpl @Inject() (
): Future[Either[ErrorResponse, EnrolmentRequest[A]]] =
authorised(Enrolment(EnrolmentKey.EMCS_ENROLMENT))
.retrieve(fetch) {
case enrolments ~ Some(Organisation) ~ Some(credentials) ~ Some(internalId) =>
Future.successful(checkErns(enrolments, internalId))
case _ ~ None ~ _ ~ _ => handleAuthError("Could not retrieve affinity group from Auth")
case _ ~ Some(affinityGroup) ~ _ ~ _ if affinityGroup != Organisation =>
case enrolments ~ Some(Organisation) ~ Some(credentials) ~ Some(internalId) ~ Some(groupIdentifier) =>
Future.successful(checkErns(enrolments, UserDetails(internalId, groupIdentifier)))
case _ ~ None ~ _ ~ _ ~ _ => handleAuthError("Could not retrieve affinity group from Auth")
case _ ~ Some(affinityGroup) ~ _ ~ _ ~ _ if affinityGroup != Organisation =>
handleAuthError(s"Invalid affinity group $affinityGroup from Auth")
case _ ~ _ ~ None ~ _ => handleAuthError("Could not retrieve credentials from Auth")
case _ ~ _ ~ _ ~ None => handleAuthError("Could not retrieve internalId from Auth")
case _ => handleAuthError("Invalid enrolment parameter from Auth")
case _ ~ _ ~ None ~ _ ~ _ => handleAuthError("Could not retrieve credentials from Auth")
case _ ~ _ ~ _ ~ None ~ _ => handleAuthError("Could not retrieve internalId from Auth")
case _ => handleAuthError("Invalid enrolment parameter from Auth")
}
.recover {
case error: AuthorisationException =>
Expand All @@ -124,15 +125,15 @@ class AuthActionImpl @Inject() (

private def checkErns[A](
enrolments: Enrolments,
internalId: String
userDetails: UserDetails
)(implicit request: Request[A]): Either[ErrorResponse, EnrolmentRequest[A]] = {
val erns = getAllErnsForEmcsEnrolment(enrolments)

if (erns.isEmpty) {
logger.warn(s"Could not find ${EnrolmentKey.ERN}")
Left(ErrorResponse(FORBIDDEN, s"Could not find ${EnrolmentKey.ERN}"))
} else {
Right(EnrolmentRequest(request, erns, internalId))
Right(EnrolmentRequest(request, erns, userDetails))
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ class ParseXmlActionImpl @Inject() (
val messageType = xmlBody.head.label
Try(ieMessageFactory.createFromXml(messageType, xmlBody)) match {
case Success(value) =>
Future.successful(Right(ParsedXmlRequest(request, value, request.erns, request.internalId)))
Future.successful(Right(ParsedXmlRequest(request, value, request.erns, request.userDetails)))

case Failure(exception: ParserFailure) =>
logger.warn(s"[ParseXmlActionImpl] - Not valid $messageType")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ object AuditEventFactory extends Auditing {
submittedToCore,
message.messageIdentifier,
Some(correlationId),
UserDetails("", "", "", "", ""),
request.userDetails,
NonEmptySeq(request.erns.head, request.erns.tail.toList),
message.toJsObject
)
Expand Down Expand Up @@ -91,7 +91,7 @@ object AuditEventFactory extends Auditing {
submittedToCore,
message.messageIdentifier,
Some(correlationId),
UserDetails("", "", "", "", ""),
request.userDetails,
NonEmptySeq(request.erns.head, request.erns.tail.toList),
message.toJsObject
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,35 +18,19 @@ package uk.gov.hmrc.excisemovementcontrolsystemapi.models.auditing

import cats.data.NonEmptySeq
import play.api.libs.json.{JsObject, Json}
import uk.gov.hmrc.excisemovementcontrolsystemapi.utils.CommonFormats._
import uk.gov.hmrc.excisemovementcontrolsystemapi.utils.CommonFormats

trait EventAuditEvent {} //Should this be here vs using the abstract class?

case class UserDetails(
gatewayId: String,
name: String,
email: String,
affinityGroup: String,
credentialRole: String
) {}
groupIdentifier: String
)

object UserDetails {
object UserDetails extends CommonFormats {
implicit val format = Json.format[UserDetails]
}

case class ThirdPartyApplication(
id: String,
clientId: String,
gatewayId: String,
nameResponsibleIndividual: String,
emailResponsibleIndividual: String,
organisationUrl: Option[String]
) {}

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

case class MessageSubmittedDetails(
messageTypeCode: String,
messageType: String,
Expand All @@ -63,6 +47,6 @@ case class MessageSubmittedDetails(
messageDetails: JsObject
) extends EventAuditEvent

object MessageSubmittedDetails {
object MessageSubmittedDetails extends CommonFormats {
implicit val format = Json.format[MessageSubmittedDetails]
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,17 @@
package uk.gov.hmrc.excisemovementcontrolsystemapi.models.auth

import play.api.mvc.{Request, WrappedRequest}
import uk.gov.hmrc.excisemovementcontrolsystemapi.models.auditing.UserDetails
import uk.gov.hmrc.excisemovementcontrolsystemapi.models.messages.IEMessage

case class EnrolmentRequest[A](request: Request[A], erns: Set[String], internalId: String)
case class EnrolmentRequest[A](request: Request[A], erns: Set[String], userDetails: UserDetails)
extends WrappedRequest[A](request)

case class ParsedXmlRequest[A](
request: EnrolmentRequest[A],
ieMessage: IEMessage,
erns: Set[String],
internalId: String
userDetails: UserDetails
) extends WrappedRequest[A](request) {

def headersAsMap: Map[String, String] =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ class DraftExciseMovementControllerSpec
when(appConfig.pushNotificationsEnabled).thenReturn(true)
when(dateTimeService.timestamp()).thenReturn(timestamp)
when(auditService.auditMessage(any[IEMessage])(any)).thenReturn(EitherT.fromEither(Right(())))
when(auditService.messageSubmitted(any, any, any, any, any)(any)).thenReturn(EitherT.fromEither(Right(())))
when(ernSubmissionRepository.save(any)).thenReturn(Future.successful(Done))
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ class SubmitMessageControllerSpec
when(messageValidation.validateSubmittedMessage(any, any, any)).thenReturn(Right(consignorId))
when(dateTimeService.timestamp()).thenReturn(timestamp)
when(auditService.auditMessage(any[IEMessage])(any)).thenReturn(EitherT.fromEither(Right(())))
when(auditService.auditMessage(any[IEMessage], any)(any)).thenReturn(EitherT.fromEither(Right(())))
when(auditService.messageSubmitted(any, any, any, any, any)(any)).thenReturn(EitherT.fromEither(Right(())))
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import play.api.libs.json.Json
import play.api.mvc.Results.{Forbidden, Unauthorized}
import play.api.mvc.{BodyParsers, Results}
import play.api.test.FakeRequest
import play.api.test.Helpers.{GET, await, defaultAwaitTimeout}
import play.api.test.Helpers.{GET, await, contentAsJson, contentAsString, defaultAwaitTimeout}
import uk.gov.hmrc.auth.core.AffinityGroup.{Agent, Individual}
import uk.gov.hmrc.auth.core._
import uk.gov.hmrc.excisemovementcontrolsystemapi.fixture.AuthTestSupport
Expand Down Expand Up @@ -133,7 +133,7 @@ class AuthActionSpec extends PlaySpec with AuthTestSupport with BeforeAndAfterEa
withUnAuthorizedInternalId()

val result = await(authenticator.invokeBlock(FakeRequest(), block))

println(result)
result mustBe Unauthorized(
Json.toJson(
ErrorResponse(
Expand All @@ -149,7 +149,8 @@ class AuthActionSpec extends PlaySpec with AuthTestSupport with BeforeAndAfterEa
authorizeWithAffinityGroup(Some(Individual))

val result = await(authenticator.invokeBlock(FakeRequest(), block))

println(result)
println(contentAsJson(Future.successful(result)))
result mustBe Unauthorized(
Json.toJson(
ErrorResponse(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import play.api.mvc.Results.BadRequest
import play.api.test.FakeRequest
import play.api.test.Helpers.stubControllerComponents
import uk.gov.hmrc.excisemovementcontrolsystemapi.models.ErrorResponse
import uk.gov.hmrc.excisemovementcontrolsystemapi.models.auditing.UserDetails
import uk.gov.hmrc.excisemovementcontrolsystemapi.models.auth.EnrolmentRequest
import uk.gov.hmrc.excisemovementcontrolsystemapi.models.preValidateTrader.request._
import uk.gov.hmrc.excisemovementcontrolsystemapi.utils.DateTimeService
Expand Down Expand Up @@ -67,7 +68,8 @@ class ParseJsonActionSpec extends PlaySpec with ScalaFutures with EitherValues {

"refine" should {
"return a ParsedPreValidateTraderRequest" in {
val enrolmentRequest = EnrolmentRequest(FakeRequest().withBody(Json.parse(exampleJson)), Set("ern"), "123")
val enrolmentRequest =
EnrolmentRequest(FakeRequest().withBody(Json.parse(exampleJson)), Set("ern"), UserDetails("123", "abc"))

val result = parseJsonAction.refine(enrolmentRequest).futureValue

Expand All @@ -76,7 +78,7 @@ class ParseJsonActionSpec extends PlaySpec with ScalaFutures with EitherValues {

"return an error" when {
"no json was sent" in {
val enrolmentRequest = EnrolmentRequest(FakeRequest().withBody(""), Set("ern"), "123")
val enrolmentRequest = EnrolmentRequest(FakeRequest().withBody(""), Set("ern"), UserDetails("123", "abc"))

val result = parseJsonAction.refine(enrolmentRequest).futureValue

Expand All @@ -87,7 +89,8 @@ class ParseJsonActionSpec extends PlaySpec with ScalaFutures with EitherValues {
"JSON parsing exception" in {

val exampleJson = "{\"exciseTraderValidationRequest\": 123 }"
val enrolmentRequest = EnrolmentRequest(FakeRequest().withBody(Json.parse(exampleJson)), Set("ern"), "123")
val enrolmentRequest =
EnrolmentRequest(FakeRequest().withBody(Json.parse(exampleJson)), Set("ern"), UserDetails("123", "abc"))

val result = parseJsonAction.refine(enrolmentRequest).futureValue

Expand All @@ -105,7 +108,11 @@ class ParseJsonActionSpec extends PlaySpec with ScalaFutures with EitherValues {
"refineETDS" should {
"return a ParsedPreValidateTraderETDSRequest" in {
val enrolmentRequest =
EnrolmentRequest(FakeRequest().withBody(Json.toJson(getPreValidateTraderRequest)), Set("ern"), "123")
EnrolmentRequest(
FakeRequest().withBody(Json.toJson(getPreValidateTraderRequest)),
Set("ern"),
UserDetails("123", "abc")
)

val result = parseJsonAction.refineETDS(enrolmentRequest).futureValue

Expand All @@ -114,7 +121,7 @@ class ParseJsonActionSpec extends PlaySpec with ScalaFutures with EitherValues {

"return an error" when {
"no json was sent" in {
val enrolmentRequest = EnrolmentRequest(FakeRequest().withBody(""), Set("ern"), "123")
val enrolmentRequest = EnrolmentRequest(FakeRequest().withBody(""), Set("ern"), UserDetails("123", "abc"))

val result = parseJsonAction.refineETDS(enrolmentRequest).futureValue

Expand All @@ -125,7 +132,8 @@ class ParseJsonActionSpec extends PlaySpec with ScalaFutures with EitherValues {
"JSON parsing exception" in {

val exampleJson = "{\"someInvalidJson\": 123 }"
val enrolmentRequest = EnrolmentRequest(FakeRequest().withBody(Json.parse(exampleJson)), Set("ern"), "123")
val enrolmentRequest =
EnrolmentRequest(FakeRequest().withBody(Json.parse(exampleJson)), Set("ern"), UserDetails("123", "abc"))

val result = parseJsonAction.refineETDS(enrolmentRequest).futureValue

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import play.api.test.Helpers.stubControllerComponents
import scalaxb.ParserFailure
import uk.gov.hmrc.excisemovementcontrolsystemapi.factories.{IEMessageFactory, IEMessageFactoryException}
import uk.gov.hmrc.excisemovementcontrolsystemapi.models.ErrorResponse
import uk.gov.hmrc.excisemovementcontrolsystemapi.models.auditing.UserDetails
import uk.gov.hmrc.excisemovementcontrolsystemapi.models.auth.{EnrolmentRequest, ParsedXmlRequest}
import uk.gov.hmrc.excisemovementcontrolsystemapi.models.messages.IEMessage
import uk.gov.hmrc.excisemovementcontrolsystemapi.utils.DateTimeService
Expand Down Expand Up @@ -68,16 +69,17 @@ class ParseXmlActionSpec extends PlaySpec with ScalaFutures with EitherValues wi

"refine" should {
"return a ParsedXmlRequest" in {
val enrolmentRequest = EnrolmentRequest(FakeRequest().withBody(xml.XML.loadString(xmlStr)), Set("ern"), "123")
val enrolmentRequest =
EnrolmentRequest(FakeRequest().withBody(xml.XML.loadString(xmlStr)), Set("ern"), UserDetails("123", "abc"))

val result = parserXmlAction.refine(enrolmentRequest).futureValue

result mustBe Right(ParsedXmlRequest(enrolmentRequest, message, Set("ern"), "123"))
result mustBe Right(ParsedXmlRequest(enrolmentRequest, message, Set("ern"), UserDetails("123", "abc")))
}

"return an error" when {
"no xml format was sent" in {
val enrolmentRequest = EnrolmentRequest(FakeRequest().withBody(xmlStr), Set("ern"), "123")
val enrolmentRequest = EnrolmentRequest(FakeRequest().withBody(xmlStr), Set("ern"), UserDetails("123", "abc"))

val result = parserXmlAction.refine(enrolmentRequest).futureValue

Expand All @@ -89,7 +91,8 @@ class ParseXmlActionSpec extends PlaySpec with ScalaFutures with EitherValues wi

"a parser error that can be simplified" in {
when(messageFactory.createFromXml(any, any)).thenThrow(new ParserFailure(scalaxbExceptionMessage))
val enrolmentRequest = EnrolmentRequest(FakeRequest().withBody(xml.XML.loadString(xmlStr)), Set("ern"), "123")
val enrolmentRequest =
EnrolmentRequest(FakeRequest().withBody(xml.XML.loadString(xmlStr)), Set("ern"), UserDetails("123", "abc"))

val result = parserXmlAction.refine(enrolmentRequest).futureValue

Expand All @@ -107,7 +110,8 @@ class ParseXmlActionSpec extends PlaySpec with ScalaFutures with EitherValues wi
"Error while parsing <urn:DateOfDispatch xmlns:urn=\"urn:publicid:-:EC:DGTAXUD:EMCS:PHASE4:IE815:V3.13\" xmlns:urn1=\"urn:publicid:-:EC:DGTAXUD:EMCS:PHASE4:TMS:V3.13\">lrnGBWKQOZ8OMCWS1</urn:DateOfDispatch>: java.lang.IllegalArgumentException: lrnGBWKQOZ8OMCWS1"

when(messageFactory.createFromXml(any, any)).thenThrow(new ParserFailure(parserError))
val enrolmentRequest = EnrolmentRequest(FakeRequest().withBody(xml.XML.loadString(xmlStr)), Set("ern"), "123")
val enrolmentRequest =
EnrolmentRequest(FakeRequest().withBody(xml.XML.loadString(xmlStr)), Set("ern"), UserDetails("123", "abc"))

val result = parserXmlAction.refine(enrolmentRequest).futureValue

Expand All @@ -119,7 +123,8 @@ class ParseXmlActionSpec extends PlaySpec with ScalaFutures with EitherValues wi
"IEMessageFactory exception" in {
when(messageFactory.createFromXml(any, any))
.thenThrow(new IEMessageFactoryException("Error doing message factory things"))
val enrolmentRequest = EnrolmentRequest(FakeRequest().withBody(xml.XML.loadString(xmlStr)), Set("ern"), "123")
val enrolmentRequest =
EnrolmentRequest(FakeRequest().withBody(xml.XML.loadString(xmlStr)), Set("ern"), UserDetails("123", "abc"))

val result = parserXmlAction.refine(enrolmentRequest).futureValue

Expand All @@ -129,7 +134,8 @@ class ParseXmlActionSpec extends PlaySpec with ScalaFutures with EitherValues wi

"some generic exception" in {
when(messageFactory.createFromXml(any, any)).thenThrow(new Exception(scalaxbExceptionMessage))
val enrolmentRequest = EnrolmentRequest(FakeRequest().withBody(xml.XML.loadString(xmlStr)), Set("ern"), "123")
val enrolmentRequest =
EnrolmentRequest(FakeRequest().withBody(xml.XML.loadString(xmlStr)), Set("ern"), UserDetails("123", "abc"))

val result = parserXmlAction.refine(enrolmentRequest).futureValue

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import play.api.mvc.Results.{BadRequest, Ok}
import play.api.test.FakeRequest
import play.api.test.Helpers.{await, defaultAwaitTimeout}
import uk.gov.hmrc.excisemovementcontrolsystemapi.models.ErrorResponse
import uk.gov.hmrc.excisemovementcontrolsystemapi.models.auditing.UserDetails
import uk.gov.hmrc.excisemovementcontrolsystemapi.models.auth._
import uk.gov.hmrc.excisemovementcontrolsystemapi.utils.DateTimeService
import uk.gov.hmrc.play.bootstrap.tools.Stubs.stubMessagesControllerComponents
Expand All @@ -47,7 +48,7 @@ class ValidateErnParameterActionSpec extends PlaySpec {
"filter passes successfully" when {

val erns = Set("GBWK002281023", "GBWK002181023", "GBWK002281022")
val request = EnrolmentRequest(FakeRequest(), erns, "123")
val request = EnrolmentRequest(FakeRequest(), erns, UserDetails("123", "abc"))

val checkResponseMatchesRequestBlock = (actual: EnrolmentRequest[_]) => {
actual mustBe request
Expand All @@ -73,7 +74,7 @@ class ValidateErnParameterActionSpec extends PlaySpec {
"an error" when {
"ERN in parameter is not supplied in the auth" in {

val request = EnrolmentRequest(FakeRequest(), Set("12356", "234567"), "123")
val request = EnrolmentRequest(FakeRequest(), Set("12356", "234567"), UserDetails("123", "abc"))

val result = await(sut.apply(Some("GBWK002181023")).invokeBlock(request, defaultBlock))

Expand Down
Loading

0 comments on commit 8bf5236

Please sign in to comment.