Skip to content

Commit

Permalink
Merge pull request #112 from hmrc/GG-8234
Browse files Browse the repository at this point in the history
GG-8234 Remove deprecated elements in API definition
  • Loading branch information
ShaneTN authored Dec 12, 2024
2 parents fd00a35 + ddf9a75 commit 85435dc
Show file tree
Hide file tree
Showing 21 changed files with 182 additions and 179 deletions.
6 changes: 2 additions & 4 deletions app/config/APIAccessConfig.scala
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import com.typesafe.config.{Config, ConfigObject}

import scala.jdk.CollectionConverters.*

case class APIAccessConfig(version: String, status: String, accessType: String, endpointsEnabled: Boolean, whiteListedApplicationIds: List[String])
case class APIAccessConfig(version: String, status: String, accessType: String, endpointsEnabled: Boolean)

case class APIAccessVersions(versionConfigs: Option[ConfigObject]) {
def findAPIs(versions: List[String], config: Config): List[APIAccessConfig] = {
Expand All @@ -29,12 +29,10 @@ case class APIAccessVersions(versionConfigs: Option[ConfigObject]) {

val accessType = if (value.hasPath("type")) value.getString("type") else "PRIVATE"
val status = if (value.hasPath("status")) value.getString("status") else throw new IllegalArgumentException("Status missing")
val allowListedApplicationIds =
if (value.hasPath("allow-list.applicationIds")) Some(value.getStringList("allow-list.applicationIds").asScala.toList) else None
val endpointsEnabled = if (value.hasPath("endpointsEnabled")) value.getBoolean("endpointsEnabled") else false
val versionNumber = version.replace('_', '.')

APIAccessConfig(versionNumber, status, accessType, endpointsEnabled, allowListedApplicationIds.getOrElse(List()))
APIAccessConfig(versionNumber, status, accessType, endpointsEnabled)
}
}

Expand Down
2 changes: 1 addition & 1 deletion app/connectors/ThirdPartyDelegatedAuthorityConnector.scala
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class ThirdPartyDelegatedAuthorityConnector @Inject() (appContext: AppContext, h
httpClient
.get(url"$serviceUrl/delegated-authority")
.setHeader("access-token" -> accessToken)
.execute(readRaw, ec)
.execute(using readRaw, ec)
.map { response =>
if (response.status == Status.NOT_FOUND) {
Set[String]()
Expand Down
43 changes: 43 additions & 0 deletions app/controllers/ErrorResponse.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* 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 controllers

import play.mvc.Http.Status.*
import play.api.libs.json.*
import play.api.mvc.Result
import play.api.mvc.Results.Status

/** Please use the constructors provided in the companion object and not the main constructor as these responses are expected to contain specific
* wording.
*/
case class ErrorResponse private (httpStatusCode: Int, errorCode: String, message: String) {
def toResult: Result = Status(httpStatusCode)(Json.toJson(this))
}

object ErrorResponse {
implicit val writes: Writes[ErrorResponse] = (e: ErrorResponse) => Json.obj("code" -> e.errorCode, "message" -> e.message)

def badGateway(msg: String = "Bad gateway"): ErrorResponse = ErrorResponse(BAD_GATEWAY, "BAD_GATEWAY", msg)
def unauthorized(msg: String = "Bearer token is missing or not authorized"): ErrorResponse = ErrorResponse(UNAUTHORIZED, "UNAUTHORIZED", msg)
def badRequest(msg: String = "Bad request"): ErrorResponse = ErrorResponse(BAD_REQUEST, "BAD_REQUEST", msg)
def badRequest(errors: Seq[(JsPath, Seq[JsonValidationError])]): ErrorResponse = badRequest(JsError.toJson(errors).as[String])
val acceptHeaderInvalid: ErrorResponse = ErrorResponse(NOT_ACCEPTABLE, "ACCEPT_HEADER_INVALID", "The accept header is missing or invalid")
val notFound: ErrorResponse = ErrorResponse(NOT_FOUND, "NOT_FOUND", "Resource was not found")
val unauthorizedLowCL: ErrorResponse = ErrorResponse(UNAUTHORIZED, "LOW_CONFIDENCE_LEVEL", "Confidence Level on account does not allow access")
val internalServerError: ErrorResponse = ErrorResponse(INTERNAL_SERVER_ERROR, "INTERNAL_SERVER_ERROR", "Internal server error")
val preferencesSettingsError: ErrorResponse = ErrorResponse(INTERNAL_SERVER_ERROR, "PREFERENCE_SETTINGS_ERROR", "Failed to set preferences")
}
49 changes: 0 additions & 49 deletions app/controllers/ErrorResponses.scala

This file was deleted.

3 changes: 1 addition & 2 deletions app/controllers/HeaderValidator.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@

package controllers

import play.api.libs.json.Json
import play.api.mvc.*

import scala.concurrent.{ExecutionContext, Future}
Expand Down Expand Up @@ -44,7 +43,7 @@ trait HeaderValidator extends Results {
block: (Request[A]) => Future[Result]
): Future[Result] =
if (rules(request.headers.get("Accept"))) block(request)
else Future.successful(Status(ErrorAcceptHeaderInvalid.httpStatusCode)(Json.toJson[ErrorResponse](ErrorAcceptHeaderInvalid)))
else Future.successful(ErrorResponse.acceptHeaderInvalid.toResult)

override def parser: BodyParser[AnyContent] = outer.parser

Expand Down
10 changes: 5 additions & 5 deletions app/controllers/UserInfoController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,11 @@ trait UserInfoController extends BackendBaseController with HeaderValidator {

Ok(json)
} recover {
case Upstream4xxResponse(UER(_, 401, _, _)) => Unauthorized(Json.toJson(ErrorUnauthorized()))
case Upstream4xxResponse(UER(msg4xx, _, _, _)) => BadGateway(Json.toJson(ErrorBadGateway(msg4xx)))
case Upstream5xxResponse(UER(msg5xx, _, _, _)) => BadGateway(Json.toJson(ErrorBadGateway(msg5xx)))
case bex: BadRequestException => BadRequest(Json.toJson(ErrorBadRequest(bex.getMessage)))
case uex: UnauthorizedException => Unauthorized(Json.toJson(ErrorUnauthorized(uex.getMessage)))
case Upstream4xxResponse(UER(_, 401, _, _)) => ErrorResponse.unauthorized().toResult
case Upstream4xxResponse(UER(msg4xx, _, _, _)) => ErrorResponse.badGateway(msg4xx).toResult
case Upstream5xxResponse(UER(msg5xx, _, _, _)) => ErrorResponse.badGateway(msg5xx).toResult
case bex: BadRequestException => ErrorResponse.badRequest(bex.getMessage).toResult
case uex: UnauthorizedException => ErrorResponse.unauthorized(uex.getMessage).toResult
}
}
}
Expand Down
29 changes: 0 additions & 29 deletions app/controllers/package.scala

This file was deleted.

8 changes: 7 additions & 1 deletion app/domain/APIDefinition.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,10 @@

package domain

case class APIAccess(`type`: String, allowlistedApplicationIds: Option[Seq[String]])
import play.api.libs.json.{Json, OFormat}

case class APIAccess(`type`: String)

object APIAccess {
implicit val format: OFormat[APIAccess] = Json.format[APIAccess]
}
6 changes: 6 additions & 0 deletions app/domain/GovernmentGatewayDetails.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package domain

import play.api.libs.json.{Json, OFormat}

case class GovernmentGatewayDetails(
user_id: Option[String],
roles: Option[Seq[String]],
Expand All @@ -29,3 +31,7 @@ case class GovernmentGatewayDetails(
profile_uri: Option[String],
group_profile_uri: Option[String]
)

object GovernmentGatewayDetails {
implicit val format: OFormat[GovernmentGatewayDetails] = Json.format[GovernmentGatewayDetails]
}
10 changes: 9 additions & 1 deletion app/domain/UserDetails.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@

package domain

import java.time.LocalDate
import play.api.libs.json.{Json, OFormat}
import uk.gov.hmrc.auth.core.retrieve.{GatewayInformation, MdtpInformation}

import java.time.LocalDate

case class UserDetails(
authProviderId: Option[String] = None,
authProviderType: Option[String] = None,
Expand All @@ -39,3 +41,9 @@ case class UserDetails(
profile: Option[String],
groupProfile: Option[String]
)

object UserDetails {
private implicit val giFormat: OFormat[GatewayInformation] = Json.format[GatewayInformation]
private implicit val miFormat: OFormat[MdtpInformation] = Json.format[MdtpInformation]
implicit val format: OFormat[UserDetails] = Json.format[UserDetails]
}
28 changes: 27 additions & 1 deletion app/domain/UserInfo.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,24 @@

package domain

import play.api.libs.json.{Format, Json, OFormat, Reads}

import java.time.LocalDate
import uk.gov.hmrc.auth.core.Enrolment
import uk.gov.hmrc.auth.core.{Enrolment, EnrolmentIdentifier}
import uk.gov.hmrc.auth.core.retrieve.{ItmpAddress, ItmpName}

case class Address(formatted: String, postal_code: Option[String], country: Option[String], country_code: Option[String])

object Address {
implicit val format: OFormat[Address] = Json.format[Address]
}

case class Mdtp(device_id: String, session_id: String)

object Mdtp {
implicit val format: OFormat[Mdtp] = Json.format[Mdtp]
}

case class UserInfo(given_name: Option[String] = None,
family_name: Option[String] = None,
middle_name: Option[String] = None,
Expand All @@ -38,8 +48,24 @@ case class UserInfo(given_name: Option[String] = None,
group_profile_url: Option[String] = None
)

object UserInfo {
/* We re-define our own simple Format for Enrolment because the one provided but the library one
renames a field ("key" to "enrolment") in a way which disagrees with the UserInfo schema */
private implicit val enrFormat: OFormat[Enrolment] = {
implicit val idFormat: Format[EnrolmentIdentifier] = Json.format[EnrolmentIdentifier]
Json.format[Enrolment]
}
implicit val format: OFormat[UserInfo] = Json.format[UserInfo]
}

case class UserInformation(profile: Option[UserProfile], address: Option[Address], uk_gov_nino: Option[String])

case class UserProfile(given_name: Option[String], family_name: Option[String], middle_name: Option[String], birthdate: Option[LocalDate])

case class DesUserInfo(name: Option[ItmpName], dateOfBirth: Option[LocalDate], address: Option[ItmpAddress])

object DesUserInfo {
private implicit val inFormat: Format[ItmpName] = Json.format[ItmpName]
private implicit val iaFormat: Format[ItmpAddress] = Json.format[ItmpAddress]
implicit val reads: Format[DesUserInfo] = Json.format[DesUserInfo]
}
40 changes: 0 additions & 40 deletions app/domain/package.scala

This file was deleted.

11 changes: 5 additions & 6 deletions app/filters/MicroserviceAuthFilter.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,17 @@

package filters

import javax.inject.{Inject, Singleton}
import connectors.AuthConnector
import controllers.ErrorResponse
import org.apache.pekko.stream.Materializer
import play.api.Configuration
import play.api.libs.json.Json
import play.api.mvc.{Filter, RequestHeader, Result, Results}
import play.api.routing.Router
import uk.gov.hmrc.auth.core.{AuthorisationException, AuthorisedFunctions}
import connectors.AuthConnector
import controllers.ErrorUnauthorized
import org.apache.pekko.stream.Materializer
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.play.http.HeaderCarrierConverter

import javax.inject.{Inject, Singleton}
import scala.concurrent.{ExecutionContext, Future}

@Singleton
Expand All @@ -46,7 +45,7 @@ class MicroserviceAuthFilter @Inject() (configuration: Configuration, val authCo
authorised() {
next(rh)
} recoverWith { case e: AuthorisationException =>
Future.successful(Unauthorized(Json.toJson(ErrorUnauthorized())))
Future.successful(ErrorResponse.unauthorized().toResult)
}
case _ => next(rh)
}
Expand Down
11 changes: 5 additions & 6 deletions app/handlers/ErrorHandler.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,14 @@

package handlers

import javax.inject.{Inject, Singleton}
import com.google.inject.Provider
import controllers.ErrorResponse
import play.api.http.DefaultHttpErrorHandler
import play.api.libs.json.Json
import play.api.mvc.Results.Status
import play.api.mvc.{RequestHeader, Result}
import play.api.routing.Router
import play.api.{Configuration, Environment, OptionalSourceMapper}
import controllers.{ErrorBadGateway, ErrorUnauthorized}

import javax.inject.{Inject, Singleton}
import scala.concurrent.{ExecutionContext, Future}

@Singleton
Expand All @@ -39,8 +38,8 @@ class ErrorHandler @Inject() (
override def onServerError(request: RequestHeader, exception: Throwable): Future[Result] = {
super.onServerError(request, exception) map (res => {
res.header.status match {
case 401 => Status(ErrorUnauthorized().httpStatusCode)(Json.toJson(ErrorUnauthorized()))
case _ => Status(ErrorBadGateway().httpStatusCode)(Json.toJson(ErrorBadGateway(exception.getMessage)))
case 401 => ErrorResponse.unauthorized().toResult
case _ => ErrorResponse.badGateway(exception.getMessage).toResult
}
})
}
Expand Down
Loading

0 comments on commit 85435dc

Please sign in to comment.