Skip to content

Commit

Permalink
Merge pull request #53 from hmrc/auth
Browse files Browse the repository at this point in the history
Auth action to use enrolments
  • Loading branch information
ChrisCookOC authored May 14, 2024
2 parents 2baa434 + a201da5 commit 9108d00
Show file tree
Hide file tree
Showing 10 changed files with 70 additions and 110 deletions.
5 changes: 4 additions & 1 deletion app/config/FrontendAppConfig.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@
package config

import com.google.inject.{Inject, Singleton}
import models.EnrolmentConfig
import play.api.Configuration
import play.api.i18n.Lang
import play.api.mvc.RequestHeader

import uk.gov.hmrc.http.StringContextOps
@Singleton
class FrontendAppConfig @Inject() (configuration: Configuration) {
Expand Down Expand Up @@ -53,4 +53,7 @@ class FrontendAppConfig @Inject() (configuration: Configuration) {
val countdown: Int = configuration.get[Int]("timeout-dialog.countdown")

val cacheTtl: Int = configuration.get[Int]("mongodb.timeToLiveInSeconds")

val tgpEnrolmentIdentifier: EnrolmentConfig = configuration.get[EnrolmentConfig]("enrolment-config")

}
47 changes: 22 additions & 25 deletions app/controllers/actions/IdentifierAction.scala
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,13 @@ import com.google.inject.Inject
import config.FrontendAppConfig
import controllers.routes
import models.requests.IdentifierRequest
import play.api.Logging
import play.api.mvc.Results._
import play.api.mvc._
import uk.gov.hmrc.auth.core._
import uk.gov.hmrc.auth.core.retrieve.v2.Retrievals
import uk.gov.hmrc.http.{HeaderCarrier, UnauthorizedException}
import uk.gov.hmrc.auth.core.retrieve.~
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.play.http.HeaderCarrierConverter

import scala.concurrent.{ExecutionContext, Future}
Expand All @@ -36,39 +38,34 @@ class AuthenticatedIdentifierAction @Inject()(
config: FrontendAppConfig,
val parser: BodyParsers.Default
)
(implicit val executionContext: ExecutionContext) extends IdentifierAction with AuthorisedFunctions {
(implicit val executionContext: ExecutionContext)
extends IdentifierAction
with AuthorisedFunctions
with Logging {

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

implicit val hc: HeaderCarrier = HeaderCarrierConverter.fromRequestAndSession(request, request.session)

authorised().retrieve(Retrievals.internalId) {
_.map {
internalId => block(IdentifierRequest(request, internalId))
}.getOrElse(throw new UnauthorizedException("Unable to retrieve internal Id"))
} recover {
val predicates = Enrolment(config.tgpEnrolmentIdentifier.key) and (AffinityGroup.Organisation or AffinityGroup.Individual)

authorised(predicates)
.retrieve(Retrievals.internalId and Retrievals.authorisedEnrolments) {
case Some(internalId) ~ authorisedEnrolments =>
authorisedEnrolments
.getEnrolment(config.tgpEnrolmentIdentifier.key)
.flatMap(_.getIdentifier(config.tgpEnrolmentIdentifier.identifier)) match {
case Some(enrolment) =>
block(IdentifierRequest(request, internalId, enrolment.value))
case None => throw InsufficientEnrolments("Unable to retrieve Enrolment")
}
} recover {
case _: NoActiveSession =>
logger.info(s"No Active Session. Redirect to $config.loginContinueUrl")
Redirect(config.loginUrl, Map("continue" -> Seq(config.loginContinueUrl)))
case _: AuthorisationException =>
logger.info("Authorisation failure: No enrolments found for TGP. Redirecting to UnauthorisedController")
Redirect(routes.UnauthorisedController.onPageLoad)
}
}
}

class SessionIdentifierAction @Inject()(
val parser: BodyParsers.Default
)
(implicit val executionContext: ExecutionContext) extends IdentifierAction {

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

implicit val hc: HeaderCarrier = HeaderCarrierConverter.fromRequestAndSession(request, request.session)

hc.sessionId match {
case Some(session) =>
block(IdentifierRequest(request, session.value))
case None =>
Future.successful(Redirect(routes.JourneyRecoveryController.onPageLoad()))
}
}
}
32 changes: 32 additions & 0 deletions app/models/EnrolmentConfig.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright 2024 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package models

import play.api.{ConfigLoader, Configuration}

case class EnrolmentConfig(key: String, identifier: String)

object EnrolmentConfig {

implicit lazy val configLoader: ConfigLoader[EnrolmentConfig] = ConfigLoader { config => prefix =>
val enrolmentConfig = Configuration(config).get[Configuration](prefix)
val key = enrolmentConfig.get[String]("enrolment-key")
val id = enrolmentConfig.get[String]("enrolment-identifier")

EnrolmentConfig(key, id)
}
}
2 changes: 1 addition & 1 deletion app/models/requests/IdentifierRequest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@ package models.requests

import play.api.mvc.{Request, WrappedRequest}

case class IdentifierRequest[A] (request: Request[A], userId: String) extends WrappedRequest[A](request)
case class IdentifierRequest[A] (request: Request[A], userId: String, eori: String) extends WrappedRequest[A](request)
2 changes: 1 addition & 1 deletion app/views/UnauthorisedView.scala.html
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,5 @@
<h1 class="govuk-heading-xl">@messages("unauthorised.heading")</h1>

<p class="govuk-body">@messages("unauthorised.p1")</p>
<p class="govuk-body">@messages("unauthorised.p2.part1") <a href="controllers.auth.routes.AuthController.signOut.url" class="govuk-link" >@messages("unauthorised.p2.linkText")</a> @messages("unauthorised.p2.part2")</p>
<p class="govuk-body">@messages("unauthorised.p2.part1") <a href="@controllers.auth.routes.AuthController.signOut.url" class="govuk-link" >@messages("unauthorised.p2.linkText")</a> @messages("unauthorised.p2.part2")</p>
}
5 changes: 5 additions & 0 deletions conf/application.conf
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,8 @@ tracking-consent-frontend {
features {
welsh-translation: true
}

enrolment-config {
enrolment-key = "HMRC-CUS-ORG"
enrolment-identifier = "EORINumber"
}
4 changes: 2 additions & 2 deletions test/controllers/actions/AuthActionSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import base.SpecBase
import com.google.inject.Inject
import config.FrontendAppConfig
import controllers.routes
import play.api.mvc.{BodyParsers, Results}
import play.api.mvc.{Action, AnyContent, BodyParsers, Results}
import play.api.test.FakeRequest
import play.api.test.Helpers._
import uk.gov.hmrc.auth.core._
Expand All @@ -34,7 +34,7 @@ import scala.concurrent.{ExecutionContext, Future}
class AuthActionSpec extends SpecBase {

class Harness(authAction: IdentifierAction) {
def onPageLoad() = authAction { _ => Results.Ok }
def onPageLoad(): Action[AnyContent] = authAction { _ => Results.Ok }
}

"Auth Action" - {
Expand Down
4 changes: 2 additions & 2 deletions test/controllers/actions/DataRetrievalActionSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ class DataRetrievalActionSpec extends SpecBase with MockitoSugar {
when(sessionRepository.get("id")) thenReturn Future(None)
val action = new Harness(sessionRepository)

val result = action.callTransform(IdentifierRequest(FakeRequest(), "id")).futureValue
val result = action.callTransform(IdentifierRequest(FakeRequest(), "id", "eori")).futureValue

result.userAnswers must not be defined
}
Expand All @@ -57,7 +57,7 @@ class DataRetrievalActionSpec extends SpecBase with MockitoSugar {
when(sessionRepository.get("id")) thenReturn Future(Some(UserAnswers("id")))
val action = new Harness(sessionRepository)

val result = action.callTransform(new IdentifierRequest(FakeRequest(), "id")).futureValue
val result = action.callTransform(new IdentifierRequest(FakeRequest(), "id", "eori")).futureValue

result.userAnswers mustBe defined
}
Expand Down
2 changes: 1 addition & 1 deletion test/controllers/actions/FakeIdentifierAction.scala
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import scala.concurrent.{ExecutionContext, Future}
class FakeIdentifierAction @Inject()(bodyParsers: PlayBodyParsers) extends IdentifierAction {

override def invokeBlock[A](request: Request[A], block: IdentifierRequest[A] => Future[Result]): Future[Result] =
block(IdentifierRequest(request, "id"))
block(IdentifierRequest(request, "id", "eori"))

override def parser: BodyParser[AnyContent] =
bodyParsers.default
Expand Down
77 changes: 0 additions & 77 deletions test/controllers/actions/SessionActionSpec.scala

This file was deleted.

0 comments on commit 9108d00

Please sign in to comment.