Skip to content

Commit

Permalink
HTS-1083: WIP - 1
Browse files Browse the repository at this point in the history
  • Loading branch information
sureshhmrc committed Jun 5, 2018
1 parent 0f4b38a commit ffc7c15
Show file tree
Hide file tree
Showing 10 changed files with 417 additions and 17 deletions.
26 changes: 24 additions & 2 deletions app/uk/gov/hmrc/helptosavetestadminfrontend/config/AppConfig.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,8 @@
package uk.gov.hmrc.helptosavetestadminfrontend.config

import javax.inject.{Inject, Singleton}

import play.api.{Configuration, Environment}
import play.api.Mode.Mode
import play.api.{Configuration, Environment}
import uk.gov.hmrc.play.config.ServicesConfig

@Singleton
Expand All @@ -29,4 +28,27 @@ class AppConfig @Inject()(val runModeConfiguration: Configuration, environment:
private def loadConfig(key: String) = runModeConfiguration.getString(key).getOrElse(throw new Exception(s"Missing configuration key: $key"))

lazy val assetsPrefix = loadConfig("assets.url") + loadConfig("assets.version")

val clientId: String = getString("microservice.services.oauth-frontend.client_id")
val clientSecret: String = getString("microservice.services.oauth-frontend.client_secret")

val adminFrontendUrl: String = getString("microservice.services.help-to-save-test-admin-frontend.url")

val apiUrl: String = getString("microservice.services.api.url")

val oauthURL: String = baseUrl("oauth-frontend")
val scopes = "read:help-to-save write:help-to-save"
val authorizeCallback: String = s"$adminFrontendUrl/help-to-save-test-admin-frontend/authorize-callback"
val authorizeUrl = s"$oauthURL/oauth/authorize?client_id=$clientId&response_type=code&scope=$scopes&redirect_uri=$authorizeCallback"

val authStubUrl: String = s"${baseUrl("auth-login-stub")}/auth-login-stub/gg-sign-in"

def tokenRequest(code: String): String =
s"""{
"client_secret":"$clientSecret",
"client_id":"$clientId",
"grant_type":"authorization_code",
"redirect_uri":"$authorizeCallback",
"code":"$code"
}"""
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* Copyright 2018 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 uk.gov.hmrc.helptosavetestadminfrontend.connectors

import com.google.inject.Inject
import play.api.http.Status
import play.api.libs.json.Json
import uk.gov.hmrc.helptosavetestadminfrontend.config.AppConfig
import uk.gov.hmrc.helptosavetestadminfrontend.http.WSHttp
import uk.gov.hmrc.helptosavetestadminfrontend.util.Logging
import uk.gov.hmrc.http.HeaderCarrier

import scala.concurrent.{ExecutionContext, Future}

class AuthConnector @Inject()(http: WSHttp, appConfig: AppConfig) extends Logging {

def loginAndGetToken()(implicit hc: HeaderCarrier, ec: ExecutionContext): Future[Either[String, String]] = {
http.post(appConfig.authStubUrl, Json.parse(getRequestBody())).map {
response
response.status match {
case Status.OK =>
logger.info(s"Got 200 from auth stub, response headers= ${response.allHeaders} and body=${response.body}")
Right(response.body)
case other: Int => Left(s"unexpected status during auth, got status=$other but 200 expected, response body=${response.body}")
}
}.recover {
case ex Left(s"error during auth, error=${ex.getMessage}")
}
}

def getRequestBody(): String =
s"""{
"authorityId":"htsapi",
"affinityGroup":"Individual",
"confidenceLevel":200,
"credentialStrength":"strong",
"nino":"AE123456C",
"credentialRole":"User",
"email":"[email protected]",
"redirectionUrl":"${appConfig.authorizeUrl}"
}""".stripMargin

}

Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/*
* Copyright 2018 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 uk.gov.hmrc.helptosavetestadminfrontend.controllers

import java.util.concurrent.TimeUnit

import com.google.common.cache.{CacheBuilder, CacheLoader, LoadingCache}
import com.google.inject.Inject
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.libs.json.Json
import play.api.mvc.{Action, AnyContent, Request}
import uk.gov.hmrc.helptosavetestadminfrontend.config.AppConfig
import uk.gov.hmrc.helptosavetestadminfrontend.connectors.AuthConnector
import uk.gov.hmrc.helptosavetestadminfrontend.forms.NinoForm
import uk.gov.hmrc.helptosavetestadminfrontend.http.WSHttp
import uk.gov.hmrc.helptosavetestadminfrontend.util.Logging
import uk.gov.hmrc.helptosavetestadminfrontend.views
import uk.gov.hmrc.http.HeaderCarrier

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
import scala.util.{Failure, Success, Try}

class HelpToSaveApiController @Inject()(http: WSHttp, authConnector: AuthConnector)(implicit override val appConfig: AppConfig, val messageApi: MessagesApi)
extends AdminFrontendController(messageApi, appConfig) with I18nSupport with Logging {

var tokenCache: LoadingCache[String, String] = _

def loadCache(implicit hc: HeaderCarrier, request: Request[_]): LoadingCache[String, String] = {
if (tokenCache == null) {
tokenCache =
CacheBuilder
.newBuilder
.maximumSize(1)
.expireAfterWrite(3, TimeUnit.HOURS)
.build(new CacheLoader[String, String] {
override def load(key: String): String = {
val result = Await.result(authConnector.loginAndGetToken(), Duration(1, TimeUnit.MINUTES))
result match {
case Right(token) =>
logger.info(s"Loaded access token from oauth, token=$token")
token
case Left(e) => throw new Exception(s"error during retrieving token from oauth, error=$e")
}
}
})
}

tokenCache
}

def availableEndpoints(): Action[AnyContent] = Action.async { implicit request =>
Future.successful(Ok(views.html.availableEndpoints()))
}

def getCheckEligibilityPage(): Action[AnyContent] = Action.async { implicit request =>
Try {
loadCache
tokenCache.get("token")
} match {
case Success(token) =>
logger.info(s"token exists in cache, token: $token")
Future.successful(Ok(views.html.get_check_eligibility_page(NinoForm.ninoForm)))
case Failure(e) =>
logger.warn(e.getMessage)
Future.successful(internalServerError())
}
}

def checkEligibility(): Action[AnyContent] = Action.async { implicit request =>
Future.successful(Ok("inside checkEligibility"))
}

def authorizeCallback(code: String): Action[AnyContent] = Action.async { implicit request =>
logger.info(s"inside authorizeCallback, code=$code")
http.post(s"${appConfig.oauthURL}/oauth/token", Json.parse(appConfig.tokenRequest(code)))
.map {
response =>
response.status match {
case OK =>
val accessToken = (response.json \ "access_token").as[String]
Ok(accessToken)
case other: Int =>
logger.warn(s"got $other status during get access_token, body=${response.body}")
internalServerError()
}
}.recover {
case ex
logger.warn(s"error during /oauth/token, error=${ex.getMessage}")
internalServerError()
}
}
}
32 changes: 32 additions & 0 deletions app/uk/gov/hmrc/helptosavetestadminfrontend/forms/NinoForm.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright 2018 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 uk.gov.hmrc.helptosavetestadminfrontend.forms

import play.api.data._
import play.api.data.Forms._

object NinoForm {

def ninoForm = Form(
mapping(
"nino" -> nonEmptyText
)(Nino.apply)(Nino.unapply)
)

}

case class Nino(nino: String)
73 changes: 73 additions & 0 deletions app/uk/gov/hmrc/helptosavetestadminfrontend/http/WSHttp.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* Copyright 2018 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 uk.gov.hmrc.helptosavetestadminfrontend.http

import com.google.inject.{ImplementedBy, Inject, Singleton}
import play.api.Mode.Mode
import play.api.libs.json.Writes
import play.api.{Configuration, Environment}
import uk.gov.hmrc.http._
import uk.gov.hmrc.http.hooks.HttpHook
import uk.gov.hmrc.play.audit.http.HttpAuditing
import uk.gov.hmrc.play.audit.http.connector.AuditConnector
import uk.gov.hmrc.play.config.ServicesConfig
import uk.gov.hmrc.play.http.ws.{WSGet, WSPost}

import scala.concurrent.{ExecutionContext, Future}

@ImplementedBy(classOf[WSHttpExtension])
trait WSHttp extends HttpPost with WSPost with HttpGet with WSGet {

def get(url: String, headers: Map[String, String] = Map.empty[String, String])(implicit hc: HeaderCarrier, ec: ExecutionContext): Future[HttpResponse]

def post[A](url: String,
body: A,
headers: Map[String, String] = Map.empty[String, String]
)(implicit w: Writes[A], hc: HeaderCarrier, ec: ExecutionContext): Future[HttpResponse]
}

@Singleton
class WSHttpExtension @Inject() (val auditConnector: AuditConnector,
val runModeConfiguration: Configuration,
environment: Environment)
extends WSHttp with HttpAuditing with ServicesConfig {

val mode: Mode = environment.mode

val httpReads: HttpReads[HttpResponse] = new HttpReads[HttpResponse] {
override def read(method: String, url: String, response: HttpResponse): HttpResponse = response
}

override val hooks: Seq[HttpHook] = NoneRequired

override def appName: String = getString("appName")

override def mapErrors(httpMethod: String, url: String, f: Future[HttpResponse])(implicit ec: ExecutionContext): Future[HttpResponse] = f

/**
* Returns a [[Future[HttpResponse]] without throwing exceptions if the status us not `2xx`. Needed
* to replace [[GET]] method provided by the hmrc library which will throw exceptions in such cases.
*/
def get(url: String, headers: Map[String, String] = Map.empty[String, String])(implicit hc: HeaderCarrier, ec: ExecutionContext): Future[HttpResponse] = super.GET(url)(httpReads, hc, ec)

def post[A](url: String,
body: A,
headers: Map[String, String] = Map.empty[String, String]
)(implicit w: Writes[A], hc: HeaderCarrier, ec: ExecutionContext): Future[HttpResponse] =
super.POST(url, body)(w, httpReads, hc.withExtraHeaders(headers.toSeq: _*), ec)

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
@*
* Copyright 2018 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.
*@

@import uk.gov.hmrc.helptosavetestadminfrontend.config.AppConfig
@import uk.gov.hmrc.helptosavetestadminfrontend.controllers.routes

@()(implicit request: Request[_], messages: Messages, appConfig: AppConfig)

@main_template(title = "help-to-save-test-admin-frontend", bodyClasses = None) {
<h1>Available Endpoints</h1>

<ul>
<li><a href="@routes.VerifiedEmailsController.specifyEmailsToDelete()">Delete Emails</a></li>
<li><a href="@routes.HelpToSaveApiController.getCheckEligibilityPage()">Check Eligibility</a></li>
</ul>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
@*
* Copyright 2018 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.
*@

@import uk.gov.hmrc.helptosavetestadminfrontend.config.AppConfig
@import uk.gov.hmrc.helptosavetestadminfrontend.controllers.routes
@import uk.gov.hmrc.helptosavetestadminfrontend.forms.Nino
@import uk.gov.hmrc.helptosavetestadminfrontend.views.html.helpers

@(form: Form[Nino])(implicit request: Request[_], messages: Messages, appConfig: AppConfig)

@main_template(title = "help-to-save-test-admin-frontend", bodyClasses = None) {
@helpers.form(routes.HelpToSaveApiController.checkEligibility(), 'class -> "group subsection--wide") {
@helpers.input_text(
id = "nino",
name = "nino",
label = "Enter NINO:",
errorMessage = Some(Html(""))
)

@helpers.input_text(
id = "email",
name = "email",
label = "Enter Email:",
errorMessage = Some(Html(""))
)

@helpers.submit('_buttonClass -> "nino-button", 'id → "Enter Nino") { Enter Nino }
}

}
Loading

0 comments on commit ffc7c15

Please sign in to comment.