play.api.i18n.Messages Scala Examples

The following examples show how to use play.api.i18n.Messages. 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: PreferencesFrontendService.scala    From pertax-frontend   with Apache License 2.0 6 votes vote down vote up
package services

import com.kenshoo.play.metrics.Metrics
import config.ConfigDecorator
import controllers.auth.requests.UserRequest
import com.google.inject.{Inject, Singleton}
import metrics.HasMetrics
import models.{ActivatePaperlessActivatedResponse, ActivatePaperlessNotAllowedResponse, ActivatePaperlessRequiresUserActionResponse, ActivatePaperlessResponse}
import play.api.Mode.Mode
import play.api.i18n.{I18nSupport, Messages, MessagesApi}
import play.api.libs.json.{JsObject, Json}
import play.api.{Configuration, Environment, Logger}
import uk.gov.hmrc.play.bootstrap.http.DefaultHttpClient
import uk.gov.hmrc.crypto.PlainText
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import uk.gov.hmrc.play.bootstrap.filters.frontend.crypto.SessionCookieCrypto
import uk.gov.hmrc.play.partials.HeaderCarrierForPartialsConverter
import util.Tools

import scala.concurrent.{ExecutionContext, Future}

@Singleton
class PreferencesFrontendService @Inject()(
  environment: Environment,
  runModeConfiguration: Configuration,
  val simpleHttp: DefaultHttpClient,
  val messagesApi: MessagesApi,
  val metrics: Metrics,
  val configDecorator: ConfigDecorator,
  val sessionCookieCrypto: SessionCookieCrypto,
  val tools: Tools,
  servicesConfig: ServicesConfig)(implicit ec: ExecutionContext)
    extends HeaderCarrierForPartialsConverter with HasMetrics with I18nSupport {

  val mode: Mode = environment.mode
  val preferencesFrontendUrl = servicesConfig.baseUrl("preferences-frontend")

  override def crypto: String => String = cookie => cookie
  def getPaperlessPreference()(implicit request: UserRequest[_]): Future[ActivatePaperlessResponse] = {

    def absoluteUrl = configDecorator.pertaxFrontendHost + request.uri

    def activatePaperless: Future[ActivatePaperlessResponse] =
      withMetricsTimer("get-activate-paperless") { timer =>
        val url =
          s"$preferencesFrontendUrl/paperless/activate?returnUrl=${tools.encryptAndEncode(absoluteUrl)}&returnLinkText=${tools
            .encryptAndEncode(Messages("label.continue"))}" //TODO remove ref to Messages
        simpleHttp.PUT[JsObject, ActivatePaperlessResponse](url, Json.obj("active" -> true)) map {

          case ActivatePaperlessActivatedResponse =>
            timer.completeTimerAndIncrementSuccessCounter()
            ActivatePaperlessActivatedResponse

          case response: ActivatePaperlessRequiresUserActionResponse =>
            timer.completeTimerAndIncrementSuccessCounter()
            response

          case ActivatePaperlessNotAllowedResponse =>
            timer.completeTimerAndIncrementFailedCounter()
            ActivatePaperlessNotAllowedResponse
        } recover {
          case e =>
            timer.completeTimerAndIncrementFailedCounter()
            Logger.warn("Error getting paperless preference record from preferences-frontend-service", e)
            ActivatePaperlessNotAllowedResponse
        }
      }

    if (request.isGovernmentGateway) {
      activatePaperless
    } else {
      Future.successful(ActivatePaperlessNotAllowedResponse)
    }
  }

} 
Example 2
Source File: RegistrationController.scala    From play-silhouette-postgres-async-seed   with Apache License 2.0 5 votes vote down vote up
package controllers

import com.mohiva.play.silhouette.api.{ LoginEvent, LoginInfo, SignUpEvent }
import com.mohiva.play.silhouette.impl.providers.{ CommonSocialProfile, CredentialsProvider }
import models.user.{ RegistrationData, UserForms }
import play.api.i18n.{ Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.mvc.AnyContent
import services.user.AuthenticationEnvironment

import scala.concurrent.Future

@javax.inject.Singleton
class RegistrationController @javax.inject.Inject() (
    override val messagesApi: MessagesApi,
    override val env: AuthenticationEnvironment
) extends BaseController {

  def registrationForm = withSession { implicit request =>
    Future.successful(Ok(views.html.register(request.identity, UserForms.registrationForm)))
  }

  def register = withSession { implicit request =>
    UserForms.registrationForm.bindFromRequest.fold(
      form => Future.successful(BadRequest(views.html.register(request.identity, form))),
      data => {
        env.identityService.retrieve(LoginInfo(CredentialsProvider.ID, data.email)).flatMap {
          case Some(user) => Future.successful {
            Ok(views.html.register(request.identity, UserForms.registrationForm.fill(data))).flashing("error" -> "That email address is already taken.")
          }
          case None => env.identityService.retrieve(data.username) flatMap {
            case Some(user) => Future.successful {
              Ok(views.html.register(request.identity, UserForms.registrationForm.fill(data))).flashing("error" -> "That username is already taken.")
            }
            case None => saveProfile(data)
          }
        }
      }
    )
  }

  private[this] def saveProfile(data: RegistrationData)(implicit request: SecuredRequest[AnyContent]) = {
    if (request.identity.profiles.exists(_.providerID == "credentials")) {
      throw new IllegalStateException("You're already registered.") // TODO Fix?
    }

    val loginInfo = LoginInfo(CredentialsProvider.ID, data.email)
    val authInfo = env.hasher.hash(data.password)
    val user = request.identity.copy(
      username = if (data.username.isEmpty) { request.identity.username } else { Some(data.username) },
      profiles = request.identity.profiles :+ loginInfo
    )
    val profile = CommonSocialProfile(
      loginInfo = loginInfo,
      email = Some(data.email)
    )
    val r = Redirect(controllers.routes.HomeController.index())
    for {
      avatar <- env.avatarService.retrieveURL(data.email)
      profile <- env.userService.create(user, profile.copy(avatarURL = avatar.orElse(Some("default"))))
      u <- env.userService.save(user, update = true)
      authInfo <- env.authInfoService.save(loginInfo, authInfo)
      authenticator <- env.authenticatorService.create(loginInfo)
      value <- env.authenticatorService.init(authenticator)
      result <- env.authenticatorService.embed(value, r)
    } yield {
      env.eventBus.publish(SignUpEvent(u, request, request2Messages))
      env.eventBus.publish(LoginEvent(u, request, request2Messages))
      result
    }
  }
} 
Example 3
Source File: SocialAuthController.scala    From play-silhouette-reactivemongo-seed   with Apache License 2.0 5 votes vote down vote up
package controllers

import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.exceptions.ProviderException
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.impl.providers._
import models.services.UserService
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.{ Action, Controller }
import utils.auth.DefaultEnv

import scala.concurrent.Future


  def authenticate(provider: String) = Action.async { implicit request =>
    (socialProviderRegistry.get[SocialProvider](provider) match {
      case Some(p: SocialProvider with CommonSocialProfileBuilder) =>
        p.authenticate().flatMap {
          case Left(result) => Future.successful(result)
          case Right(authInfo) => for {
            profile <- p.retrieveProfile(authInfo)
            user <- userService.save(profile)
            authInfo <- authInfoRepository.save(profile.loginInfo, authInfo)
            authenticator <- silhouette.env.authenticatorService.create(profile.loginInfo)
            value <- silhouette.env.authenticatorService.init(authenticator)
            result <- silhouette.env.authenticatorService.embed(value, Redirect(routes.ApplicationController.index()))
          } yield {
            silhouette.env.eventBus.publish(LoginEvent(user, request))
            result
          }
        }
      case _ => Future.failed(new ProviderException(s"Cannot authenticate with unexpected social provider $provider"))
    }).recover {
      case e: ProviderException =>
        logger.error("Unexpected provider error", e)
        Redirect(routes.SignInController.view()).flashing("error" -> Messages("could.not.authenticate"))
    }
  }
} 
Example 4
Source File: ChangePasswordController.scala    From play-silhouette-reactivemongo-seed   with Apache License 2.0 5 votes vote down vote up
package controllers

import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.exceptions.ProviderException
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.util.{ Credentials, PasswordHasherRegistry, PasswordInfo }
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import forms.ChangePasswordForm
import models.services.UserService
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.Controller
import utils.auth.{ DefaultEnv, WithProvider }

import scala.concurrent.Future


  def submit = silhouette.SecuredAction(WithProvider[DefaultEnv#A](CredentialsProvider.ID)).async { implicit request =>
    ChangePasswordForm.form.bindFromRequest.fold(
      form => Future.successful(BadRequest(views.html.changePassword(form, request.identity))),
      password => {
        val (currentPassword, newPassword) = password
        val credentials = Credentials(request.identity.email.getOrElse(""), currentPassword)
        credentialsProvider.authenticate(credentials).flatMap { loginInfo =>
          val passwordInfo = passwordHasherRegistry.current.hash(newPassword)
          authInfoRepository.update[PasswordInfo](loginInfo, passwordInfo).map { _ =>
            Redirect(routes.ChangePasswordController.view()).flashing("success" -> Messages("password.changed"))
          }
        }.recover {
          case e: ProviderException =>
            Redirect(routes.ChangePasswordController.view()).flashing("error" -> Messages("current.password.invalid"))
        }
      }
    )
  }
} 
Example 5
Source File: SignInController.scala    From play-silhouette-reactivemongo-seed   with Apache License 2.0 5 votes vote down vote up
package controllers

import javax.inject.Inject

import com.mohiva.play.silhouette.api.Authenticator.Implicits._
import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.exceptions.ProviderException
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.util.{ Clock, Credentials }
import com.mohiva.play.silhouette.impl.exceptions.IdentityNotFoundException
import com.mohiva.play.silhouette.impl.providers._
import forms.SignInForm
import models.services.UserService
import net.ceedubs.ficus.Ficus._
import play.api.Configuration
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.Controller
import utils.auth.DefaultEnv

import scala.concurrent.Future
import scala.concurrent.duration._
import scala.language.postfixOps


  def submit = silhouette.UnsecuredAction.async { implicit request =>
    SignInForm.form.bindFromRequest.fold(
      form => Future.successful(BadRequest(views.html.signIn(form, socialProviderRegistry))),
      data => {
        val credentials = Credentials(data.email, data.password)
        credentialsProvider.authenticate(credentials).flatMap { loginInfo =>
          val result = Redirect(routes.ApplicationController.index())
          userService.retrieve(loginInfo).flatMap {
            case Some(user) if !user.activated =>
              Future.successful(Ok(views.html.activateAccount(data.email)))
            case Some(user) =>
              val c = configuration.underlying
              silhouette.env.authenticatorService.create(loginInfo).map {
                case authenticator if data.rememberMe =>
                  authenticator.copy(
                    expirationDateTime = clock.now + c.as[FiniteDuration]("silhouette.authenticator.rememberMe.authenticatorExpiry"),
                    idleTimeout = c.getAs[FiniteDuration]("silhouette.authenticator.rememberMe.authenticatorIdleTimeout"),
                    cookieMaxAge = c.getAs[FiniteDuration]("silhouette.authenticator.rememberMe.cookieMaxAge")
                  )
                case authenticator => authenticator
              }.flatMap { authenticator =>
                silhouette.env.eventBus.publish(LoginEvent(user, request))
                silhouette.env.authenticatorService.init(authenticator).flatMap { v =>
                  silhouette.env.authenticatorService.embed(v, result)
                }
              }
            case None => Future.failed(new IdentityNotFoundException("Couldn't find user"))
          }
        }.recover {
          case e: ProviderException =>
            Redirect(routes.SignInController.view()).flashing("error" -> Messages("invalid.credentials"))
        }
      }
    )
  }
} 
Example 6
Source File: ResetPasswordController.scala    From play-silhouette-reactivemongo-seed   with Apache License 2.0 5 votes vote down vote up
package controllers

import java.util.UUID
import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.util.{ PasswordHasherRegistry, PasswordInfo }
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import forms.ResetPasswordForm
import models.services.{ AuthTokenService, UserService }
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.Controller
import utils.auth.DefaultEnv

import scala.concurrent.Future


  def submit(token: UUID) = silhouette.UnsecuredAction.async { implicit request =>
    authTokenService.validate(token).flatMap {
      case Some(authToken) =>
        ResetPasswordForm.form.bindFromRequest.fold(
          form => Future.successful(BadRequest(views.html.resetPassword(form, token))),
          password => userService.retrieve(authToken.userID).flatMap {
            case Some(user) if user.loginInfo.providerID == CredentialsProvider.ID =>
              val passwordInfo = passwordHasherRegistry.current.hash(password)
              authInfoRepository.update[PasswordInfo](user.loginInfo, passwordInfo).map { _ =>
                Redirect(routes.SignInController.view()).flashing("success" -> Messages("password.reset"))
              }
            case _ => Future.successful(Redirect(routes.SignInController.view()).flashing("error" -> Messages("invalid.reset.link")))
          }
        )
      case None => Future.successful(Redirect(routes.SignInController.view()).flashing("error" -> Messages("invalid.reset.link")))
    }
  }
} 
Example 7
Source File: ActivateAccountController.scala    From play-silhouette-reactivemongo-seed   with Apache License 2.0 5 votes vote down vote up
package controllers

import java.net.URLDecoder
import java.util.UUID
import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import models.services.{ AuthTokenService, UserService }
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.mailer.{ Email, MailerClient }
import play.api.mvc.Controller
import utils.auth.DefaultEnv

import scala.concurrent.Future
import scala.language.postfixOps


  def activate(token: UUID) = silhouette.UnsecuredAction.async { implicit request =>
    authTokenService.validate(token).flatMap {
      case Some(authToken) => userService.retrieve(authToken.userID).flatMap {
        case Some(user) if user.loginInfo.providerID == CredentialsProvider.ID =>
          userService.save(user.copy(activated = true)).map { _ =>
            Redirect(routes.SignInController.view()).flashing("success" -> Messages("account.activated"))
          }
        case _ => Future.successful(Redirect(routes.SignInController.view()).flashing("error" -> Messages("invalid.activation.link")))
      }
      case None => Future.successful(Redirect(routes.SignInController.view()).flashing("error" -> Messages("invalid.activation.link")))
    }
  }
} 
Example 8
Source File: ForgotPasswordController.scala    From play-silhouette-reactivemongo-seed   with Apache License 2.0 5 votes vote down vote up
package controllers

import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import forms.ForgotPasswordForm
import models.services.{ AuthTokenService, UserService }
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.mailer.{ Email, MailerClient }
import play.api.mvc.Controller
import utils.auth.DefaultEnv

import scala.concurrent.Future


  def submit = silhouette.UnsecuredAction.async { implicit request =>
    ForgotPasswordForm.form.bindFromRequest.fold(
      form => Future.successful(BadRequest(views.html.forgotPassword(form))),
      email => {
        val loginInfo = LoginInfo(CredentialsProvider.ID, email)
        val result = Redirect(routes.SignInController.view()).flashing("info" -> Messages("reset.email.sent"))
        userService.retrieve(loginInfo).flatMap {
          case Some(user) if user.email.isDefined =>
            authTokenService.create(user.userID).map { authToken =>
              val url = routes.ResetPasswordController.view(authToken.id).absoluteURL()

              mailerClient.send(Email(
                subject = Messages("email.reset.password.subject"),
                from = Messages("email.from"),
                to = Seq(email),
                bodyText = Some(views.txt.emails.resetPassword(user, url).body),
                bodyHtml = Some(views.html.emails.resetPassword(user, url).body)
              ))
              result
            }
          case None => Future.successful(result)
        }
      }
    )
  }
} 
Example 9
Source File: Strings.scala    From play-ui   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.views.formatting

import org.apache.commons.lang3.text.WordUtils
import play.api.i18n.Messages

object Strings {

  def sentence(value: String) = value.toLowerCase

  def sentenceStart(value: String) =
    value.substring(0, 1).toUpperCase() + sentence(value).substring(1)

  def capitalise(value: String) = WordUtils.capitalizeFully(value)

  def hyphenate(value: String) = value.split(" ").map(sentence(_)).mkString("-")

  def joinList(values: Traversable[String], separator: String) = values.mkString(separator)

  def optionalValue(value: Option[String], defaultMessageKey: String, isSentence: Boolean = false)(
    implicit messages: Messages) =
    value match {
      case Some(v) => v
      case None => {
        val message = Messages(defaultMessageKey)
        if (isSentence) sentence(message) else message
      }
    }
} 
Example 10
Source File: ChangePasswordController.scala    From silhouette-vuejs-app   with Apache License 2.0 5 votes vote down vote up
package controllers

import javax.inject.Inject
import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.actions.SecuredRequest
import com.mohiva.play.silhouette.api.exceptions.ProviderException
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.util.{Credentials, PasswordHasherRegistry, PasswordInfo}
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import forms.ChangePasswordForm
import play.api.i18n.{I18nSupport, Messages}
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, AnyContent, ControllerComponents}
import utils.auth.{DefaultEnv, HasSignUpMethod}

import scala.concurrent.{ExecutionContext, Future}


  def submit = silhouette.SecuredAction(hasSignUpMethod[DefaultEnv#A](CredentialsProvider.ID)).async {
    implicit request: SecuredRequest[DefaultEnv, AnyContent] =>
      ChangePasswordForm.form.bindFromRequest.fold(
        form => Future.successful(BadRequest),
        password => {
          val (currentPassword, newPassword) = password
          val credentials = Credentials(request.identity.email.getOrElse(""), currentPassword)
          credentialsProvider.authenticate(credentials).flatMap { loginInfo =>
            val passwordInfo = passwordHasherRegistry.current.hash(newPassword)
            authInfoRepository.update[PasswordInfo](loginInfo, passwordInfo).map { _ =>
              Ok(Json.obj("success" -> Messages("password.changed")))
            }
          }.recover {
            case _: ProviderException =>
              BadRequest(Json.obj("message" -> Messages("current.password.invalid")))
          }
        }
      )
  }
} 
Example 11
Source File: Mailer.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.utils

import javax.inject.Inject
import akka.Done
import akka.actor.ActorSystem
import org.hatdex.hat.api.service.RemoteExecutionContext
import org.hatdex.hat.authentication.models.HatUser
import org.hatdex.hat.phata.views
import org.hatdex.hat.resourceManagement.HatServer
import play.api.i18n.{ Lang, Messages, MessagesApi }
import play.api.libs.mailer.{ Email, MailerClient }
import play.api.mvc.RequestHeader
import play.api.{ Configuration, UsefulException }
import play.twirl.api.Html

import scala.concurrent.{ ExecutionContext, Future }

trait Mailer {
  protected val configuration: Configuration
  protected val system: ActorSystem
  protected val mailerClient: MailerClient

  import scala.language.implicitConversions

  implicit def html2String(html: Html): String = html.toString

  def serverErrorNotify(request: RequestHeader, exception: UsefulException)(implicit m: Messages): Done

  def serverExceptionNotify(request: RequestHeader, exception: Throwable)(implicit m: Messages): Done

  def sendEmail(recipients: String*)(from: String, subject: String, bodyHtml: String, bodyText: String)(implicit ec: ExecutionContext): Future[Done] = {
    Future(mailerClient.send(Email(subject, from, recipients, Some(bodyText), Some(bodyHtml))))
      .map(_ => Done)
  }
}

trait HatMailer extends Mailer {
  def serverErrorNotify(request: RequestHeader, exception: UsefulException)(implicit m: Messages): Done
  def serverExceptionNotify(request: RequestHeader, exception: Throwable)(implicit m: Messages): Done
  def passwordReset(email: String, user: HatUser, resetLink: String)(implicit m: Messages, server: HatServer): Done
  def passwordChanged(email: String, user: HatUser)(implicit m: Messages, server: HatServer): Done

  def claimHat(email: String, claimLink: String, maybePartnerDetails: Option[(String, String)])(implicit m: MessagesApi, l: Lang, server: HatServer): Done
}

class HatMailerImpl @Inject() (
    val configuration: Configuration,
    val system: ActorSystem,
    val mailerClient: MailerClient)(implicit ec: RemoteExecutionContext) extends HatMailer {
  private val emailFrom = configuration.get[String]("play.mailer.from")
  private val adminEmails = configuration.get[Seq[String]]("exchange.admin")

  def serverErrorNotify(request: RequestHeader, exception: UsefulException)(implicit m: Messages): Done = {
    sendEmail(adminEmails: _*)(
      from = emailFrom,
      subject = s"HAT server ${request.host} error #${exception.id}",
      bodyHtml = views.html.mails.emailServerError(request, exception),
      bodyText = views.html.mails.emailServerError(request, exception).toString())
    Done
  }

  def serverExceptionNotify(request: RequestHeader, exception: Throwable)(implicit m: Messages): Done = {
    sendEmail(adminEmails: _*)(
      from = emailFrom,
      subject = s"HAT server ${request.host} error: ${exception.getMessage} for ${request.path + request.rawQueryString}",
      bodyHtml = views.html.mails.emailServerThrowable(request, exception),
      bodyText = views.html.mails.emailServerThrowable(request, exception).toString())
    Done
  }

  def passwordReset(email: String, user: HatUser, resetLink: String)(implicit m: Messages, server: HatServer): Done = {
    sendEmail(email)(
      from = emailFrom,
      subject = s"HAT ${server.domain} - reset your password",
      bodyHtml = views.html.mails.emailPasswordReset(user, server.domain, resetLink),
      bodyText = views.txt.mails.emailPasswordReset(user, server.domain, resetLink).toString())
    Done
  }

  def passwordChanged(email: String, user: HatUser)(implicit m: Messages, server: HatServer): Done = {
    sendEmail(email)(
      from = emailFrom,
      subject = s"HAT ${server.domain} - password changed",
      bodyHtml = views.html.mails.emailPasswordChanged(user, server.domain),
      bodyText = views.txt.mails.emailPasswordChanged(user, server.domain).toString())
    Done
  }

  def claimHat(email: String, claimLink: String, maybePartnerDetails: Option[(String, String)])(implicit m: MessagesApi, l: Lang, server: HatServer): Done = {
    sendEmail(email)(
      from = "[email protected]",
      subject = m("email.hatclaim.subject", maybePartnerDetails.map(_._1).getOrElse("")),
      bodyHtml = views.html.mails.emailHatClaim(server.domain, claimLink, maybePartnerDetails),
      bodyText = views.txt.mails.emailHatClaim(server.domain, claimLink, maybePartnerDetails.map(_._1)).toString())
    Done
  }
} 
Example 12
Source File: TimeSpec.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.views.formatting

import javax.inject.Inject

import org.scalatestplus.play.OneAppPerSuite
import uk.gov.hmrc.play.test.UnitSpec
import play.api.Play.current
import play.api.i18n.Messages.Implicits._
import play.api.i18n.{I18nSupport, Lang, Messages, MessagesApi}

class TimeSpec extends UnitSpec with OneAppPerSuite {
  val messagesApi = app.injector.instanceOf[MessagesApi]
  implicit val messages = new Messages(new Lang("en"), messagesApi)

  "years" should {
    "return 1 year when there is 1 year"  in {
      Time.years(1)(messages) shouldBe "1 year"
    }
    "return 5 years when there is 5 years" in {
      Time.years(5)(messages) shouldBe "5 years"
    }
    "return 0 years when there is 0 years" in {
      Time.years(0)(messages) shouldBe "0 years"
    }
    "return -1 year when there is -1 year" in {
      Time.years(-1)(messages) shouldBe "-1 year"
    }

  }
} 
Example 13
Source File: PasswordReset.scala    From cave   with MIT License 5 votes vote down vote up
package controllers

import play.api.Logger
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.Messages
import play.api.mvc._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.control.NonFatal

class PasswordReset extends AbstractCaveController {

  val startResetPasswordForm = Form(
    "email" -> email
  )

  val confirmResetPasswordForm = Form(
    tuple(
      "password1" -> text,
      "password2" -> text
    ) verifying(Messages("cave.login.signup.passwordDoesntMatch"), fields => fields match {
      case (password1: String, password2: String) => password1 == password2
    })
  )

  def startResetPassword = Action { implicit request =>
    Ok(views.html.loginscreen.startResetPassword(startResetPasswordForm))
  }

  def handleStartResetPassword = Action.async { implicit request =>
    withCaveClient { client =>
      startResetPasswordForm.bindFromRequest().fold(
        formWithErrors => Future.successful(BadRequest(views.html.loginscreen.startResetPassword(formWithErrors))),
        email => {
          client.Users.postForgotPassword(email) map {
            _ => Redirect(routes.Authentication.login).flashing("success" -> Messages("cave.login.passwordReset.checkYourEmail", email))
          } recover {
            case NonFatal(e) =>
              Logger.error(s"Password reset error for $email", e)
              Redirect(routes.Authentication.login).flashing("error" -> Messages("cave.login.passwordReset.error"))
          }
        }
      )
    }
  }

  def resetPassword(mailToken: String) = Action { implicit request =>
    Ok(views.html.loginscreen.resetPasswordPage(confirmResetPasswordForm, mailToken))
  }

  def handleResetPassword(mailToken: String) = Action.async { implicit request =>
    withCaveClient { client =>
      confirmResetPasswordForm.bindFromRequest().fold(
        formWithErrors => Future.successful(BadRequest(views.html.loginscreen.resetPasswordPage(formWithErrors, mailToken))),
        values => {
          client.Users.postResetPassword(values._1, mailToken) map {
            _ => debug(s"Password changed")
              Redirect(routes.Authentication.login).flashing("success" -> Messages("cave.login.password.reset.success"))
          } recover {
            case NonFatal(e) =>
              Logger.error("Password change error", e)
              Redirect(routes.Authentication.login).flashing("error" -> Messages("cave.login.passwordReset.error"))
          }
        }
      )
    }
  }
} 
Example 14
Source File: PasswordChange.scala    From cave   with MIT License 5 votes vote down vote up
package controllers

import com.gilt.cavellc.errors.FailedRequest
import play.api.Logger
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.Messages

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.control.NonFatal

class PasswordChange extends AbstractCaveController {

  val passwordChange = Form(
    tuple(
      "newPassword.password1" -> text,
      "newPassword.password2" -> text
    ) verifying(Messages("cave.login.signup.passwordDoesntMatch"), fields => fields match {
      case (password1: String, password2: String) => password1 == password2
    })
  )

  def page = caveAsyncAction { implicit request =>
    Future.successful(Ok(views.html.loginscreen.passwordChange(passwordChange)))
  }

  def handlePasswordChange = caveAsyncAction { implicit request =>
    withCaveClient { client =>
      passwordChange.bindFromRequest().fold(
        formWithErrors => Future.successful(BadRequest(views.html.loginscreen.passwordChange(formWithErrors))),
        values =>
          client.Users.patchInfo(None, None, Some(values._1)) map {
            case user => Redirect(routes.UserProfile.profile()).flashing("success" -> s"${user.firstName}, your password has been changed")
          } recover {
            case error: FailedRequest if error.responseCode == FORBIDDEN =>
              Logger.debug("Your API session token has expired. Please login again.", error)
              Redirect(routes.Authentication.login).flashing("error" -> Messages("cave.login.sessionTokenExpired"))
            case NonFatal(e) =>
              Logger.error("Unable to change password", e)
              InternalServerError(views.html.errorpages.errorPage(Messages("cave.errors.5xx.passwordChange")))
          }
      )
    }
  }
} 
Example 15
Source File: UserProfile.scala    From cave   with MIT License 5 votes vote down vote up
package controllers

import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.Messages

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class UserProfile extends AbstractCaveController {

  val changeDetails = Form(
    mapping(
      "firstName" -> nonEmptyText,
      "lastName" -> nonEmptyText
    )(UserProfileChange.apply)(UserProfileChange.unapply)
  )

  def update = caveAsyncAction { implicit request =>
    withCaveClient { client =>
      changeDetails.bindFromRequest().fold(
        formWithErrors => Future.successful(Redirect(routes.UserProfile.profile).flashing("error" -> buildFormValidationErrorMessage(formWithErrors))),
        change =>
          client.Users.patchInfo(Some(change.firstName), Some(change.lastName), None) map {
            case user => Redirect(routes.UserProfile.profile).flashing("success" -> Messages("cave.profile.changeDetails.modal.success")).
              withSession(request.session + ("userName" -> s"${user.firstName} ${user.lastName}"))
          }
      )
    }
  }

  def profile = caveAsyncAction { implicit request =>
    withCaveClient { client =>
      client.Users.getInfo().map {
        case Some(user) => Ok(views.html.profile.profile(user, userToken, changeDetails.fill(UserProfileChange(user.firstName, user.lastName))))
        case None => InternalServerError("Unable to get user information")
      }
    }
  }
}

case class UserProfileChange(firstName: String, lastName: String) 
Example 16
Source File: Teams.scala    From cave   with MIT License 5 votes vote down vote up
package controllers

import com.gilt.cavellc.Client
import com.gilt.cavellc.models.{Member, Organization, Role, Team}
import controllers.helpers.{CreateToken, AddUserData}
import controllers.helpers.CaveForms._
import play.api.Logger
import play.api.i18n.Messages

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

case class TeamData(team: Team, role: Role, members: Seq[Member])

class Teams extends AbstractCaveController {

  def team(organizationName: String, teamName: String) = caveAsyncAction { implicit request =>
    withCaveClient { client =>

      val data = for {
        userOrganizations <- client.Users.getOrganizations()
        organization <- getOrganization(organizationName, client, userOrganizations)
        userTeams <- getUserTeams(userOrganizations, client)
        roleInOrganization <- Future.successful(userOrganizations.filter(_.name == organizationName).head.role)
        roleInTeam <- getRoleInTeam(organizationName, teamName, userTeams, roleInOrganization)
        teamsInOrganization <- getTeamsInOrganization(organizationName, roleInOrganization, client)
        team <- getSelectedTeam(organizationName, teamName, client, roleInTeam)
        membersInTeam <- getMembers(organizationName, teamName, client, organization, roleInTeam, team)
      } yield (organization, team, roleInTeam, membersInTeam.sortBy(_.user.firstName), userOrganizations.sortBy(_.name), userTeams.sortBy(_.userTeam.name), roleInOrganization)

      data map {
        case (Some(org), Some(team), roleInTeam, membersInTeam, userOrganizations, userTeams, roleInOrganization) =>
          val menuData = SideMenuData(userOrganizations, userTeams, Some(org), Some(team), Some(roleInOrganization))
          val teamData = TeamData(team, roleInTeam, membersInTeam)
          val addUserFormWithOrgAndTeam = addUserForm.fill(AddUserData(EMPTY_STRING, organizationName, teamName, EMPTY_STRING))
          val createTokenFormWithOrg = createTokenForm.fill(CreateToken(org.name, Some(team.name), EMPTY_STRING))

          Ok(views.html.teams.team(menuData, teamData, addUserFormWithOrgAndTeam, createTokenFormWithOrg))

        case _ =>
          Logger.warn(s"Team not found $teamName @ $organizationName")
          InternalServerError(views.html.errorpages.errorPage(Messages("cave.errors.5xx.general")))
      }
    }
  }

  private[controllers] def getMembers(organizationName: String, teamName: String, client: Client, organization: Option[Organization], role: Role, team: Option[Team]): Future[Seq[Member]] = {
    if (organization.isDefined && team.isDefined && !Seq(Role.Viewer, Role.Team).contains(role))
      client.Teams.getOrganizationsAndUsersByOrganizationAndTeam(organizationName, teamName).map(_.sortBy(_.user.firstName))
    else
      Future.successful(List.empty)
  }

  private[controllers] def getSelectedTeam(organizationName: String, teamName: String, client: Client, role: Role): Future[Option[Team]] = {
    if (!Seq(Role.Viewer, Role.Team).contains(role))
      client.Teams.getOrganizationsByOrganizationAndTeam(organizationName, teamName)
    else
      Future.successful(Some(Team(teamName, Seq.empty)))
  }
} 
Example 17
Source File: Tokens.scala    From cave   with MIT License 5 votes vote down vote up
package controllers

import controllers.helpers.CaveForms._
import controllers.helpers.{DeleteToken, CreateToken}
import play.api.Logger
import play.api.i18n.Messages
import play.api.mvc.{AnyContent, Request, Result}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class Tokens extends AbstractCaveController {
  def create = caveAsyncAction { implicit request =>
    createTokenForm.bindFromRequest().fold(handleFormError, handleCreateToken)
  }

  def delete = caveAsyncAction { implicit request =>
    deleteTokenForm.bindFromRequest().fold(handleFormError, handleDeleteToken)
  }

  private def handleDeleteToken(token: DeleteToken)(implicit request: Request[AnyContent]): Future[Result] = {
    token.teamName match {
      case Some(team) => deleteTeamToken(token, team)
      case _ => deleteOrganizationToken(token)
    }
  }

  private def handleCreateToken(token: CreateToken)(implicit request: Request[AnyContent]): Future[Result] = {
    token.teamName match {
      case Some(team) => createTeamToken(token, team)
      case _ => createOrganizationToken(token)
    }
  }

  private def deleteOrganizationToken(token: DeleteToken)
                                     (implicit request: Request[AnyContent]): Future[Result] = withCaveClient { client =>
    client.Tokens.deleteOrganizationsByOrganizationAndId(token.orgName, token.tokenId) map { result =>
      Logger.debug(s"Deleted organization token $token")
      Redirect(routes.Organizations.organization(token.orgName)).flashing("success" -> Messages("cave.tokens.delete.success"))
    }
  }

  private def createOrganizationToken(token: CreateToken)
                                     (implicit request: Request[AnyContent]): Future[Result] = withCaveClient { client =>
    client.Tokens.postOrganizationsByOrganization(token.orgName, token.description) map { result =>
      Logger.debug(s"Created new organization token $token")
      Redirect(routes.Organizations.organization(token.orgName)).flashing("success" -> Messages("cave.tokens.created.success"))
    }
  }

  private def deleteTeamToken(token: DeleteToken, team: String)
                             (implicit request: Request[AnyContent]): Future[Result] = withCaveClient { client =>
    client.Tokens.deleteOrganizationsAndTeamsByOrganizationAndTeamAndId(token.orgName, team, token.tokenId) map { result =>
      Logger.debug(s"Deleted team token $token")
      Redirect(routes.Teams.team(token.orgName, token.teamName.getOrElse(""))).flashing("success" -> Messages("cave.tokens.delete.success"))
    }
  }

  private def createTeamToken(token: CreateToken, team: String)
                             (implicit request: Request[AnyContent]): Future[Result] = withCaveClient { client =>
    client.Tokens.postOrganizationsAndTeamsByOrganizationAndTeam(token.orgName, team, token.description) map { result =>
      Logger.debug(s"Created new team token $token")
      Redirect(routes.Teams.team(token.orgName, token.teamName.getOrElse(""))).flashing("success" -> Messages("cave.tokens.created.success"))
    }
  }
} 
Example 18
Source File: Registration.scala    From cave   with MIT License 5 votes vote down vote up
package controllers

import play.api.Logger
import play.api.data.Form
import play.api.i18n.Messages
import play.api.mvc._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import play.api.data.Forms._

import scala.util.control.NonFatal

case class SignUpFormData(firstName: String, lastName: String, password1: String, password2: String)

class Registration extends AbstractCaveController {

  val startSignUpForm = Form(
    "email" -> email
  )

  val confirmSignUpForm = Form(
    mapping(
      "firstName" -> text,
      "lastName" -> text,
      "password1" -> text,
      "password2" -> text
    )(SignUpFormData.apply)(SignUpFormData.unapply)
      verifying(Messages("cave.login.signup.passwordDoesntMatch"), fields => fields match {
      case data: SignUpFormData => data.password1 == data.password2
    })
  )

  def startSignUp = Action { implicit request =>
    Ok(views.html.loginscreen.startSignUp(startSignUpForm))
  }

  def handleStartSignUp = Action.async { implicit request =>
    withCaveClient { client =>
      startSignUpForm.bindFromRequest().fold(
        formWithErrors => Future.successful(BadRequest(views.html.loginscreen.startSignUp(formWithErrors))),
        email => {
          client.Users.postRegister(email) map {
            _ => Redirect(routes.Authentication.login).flashing("success" -> Messages("cave.login.signup.checkYourEmail", email))
          } recover {
            case NonFatal(e) =>
              Logger.error("New user registration error", e)
              Redirect(routes.Authentication.login).flashing("error" -> Messages("cave.login.signup.error"))
          }
        }
      )
    }
  }

  def signUp(mailToken: String) = Action { implicit request =>
    Ok(views.html.loginscreen.signUp(confirmSignUpForm, mailToken))
  }

  def handleSignUp(mailToken: String) = Action.async { implicit request =>
    withCaveClient { client =>
      confirmSignUpForm.bindFromRequest().fold(
        formWithErrors => Future.successful(BadRequest(views.html.loginscreen.signUp(formWithErrors, mailToken))),
        formData => {
          client.Users.postConfirm(formData.firstName, formData.lastName, formData.password1, mailToken) map {
            _ => Redirect(routes.Authentication.login).flashing("success" -> Messages("cave.login.signup.youCanLoginNow", email))
          } recover {
            case NonFatal(e) =>
              Logger.error("Registration confirmation error", e)
              Redirect(routes.Authentication.login).flashing("error" -> Messages("cave.login.signup.error"))
          }
        }
      )
    }
  }
}

object Registration extends Registration 
Example 19
Source File: Authentication.scala    From cave   with MIT License 5 votes vote down vote up
package controllers

import com.gilt.cavellc.errors.FailedRequest
import play.api.Logger
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.Messages
import play.api.mvc._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.control.NonFatal

class Authentication extends AbstractCaveController {

  val loginForm = Form(mapping("username" -> email, "password" -> text, "landingUrl" -> text)
    (UserLogin.apply)(UserLogin.unapply)
  )

  def login = Action { implicit request =>
    val loginFormWithLandingPage = loginForm.fill(UserLogin(EMPTY_STRING, EMPTY_STRING, request.flash.get("requestedUrl").getOrElse("/")))
    Ok(views.html.loginscreen.signIn(loginFormWithLandingPage))
  }

  def logout = Action.async { implicit request =>
    Future.successful(Redirect(routes.Authentication.login()).withNewSession.flashing(
      "success" -> "You've been logged out"
    ))
  }

  def authenticate = Action.async { implicit request =>
    withCaveClient { client =>
      loginForm.bindFromRequest().fold(
        formWithErrors => Future.successful(BadRequest(views.html.loginscreen.signIn(formWithErrors))),
        loginForm => client.Users.postLogin(loginForm.email, loginForm.password) flatMap {
          case user: com.gilt.cavellc.models.Auth =>
            withExplicitTokenClient(user.token) { signedClient =>
              signedClient.Users.getInfo().flatMap {
                case Some(apiUser) =>
                  Logger.debug(s"Login Succeeded for ${loginForm.email}")
                  val landingUrl: String = if (loginForm.landingUrl.nonEmpty) loginForm.landingUrl else routes.Application.index().url
                  Logger.debug(s"landing url ${loginForm.landingUrl}")
                  Future.successful(Redirect(landingUrl).withSession(
                    "sessionToken" -> user.token,
                    "userName" -> s"${apiUser.firstName} ${apiUser.lastName}"
                  ))
                case _ =>
                  Logger.error(s"Unable to find user details for user: ${loginForm.email}")
                  Future.successful(InternalServerError(views.html.errorpages.errorPage(Messages("cave.login.login.internalError"))))
              }
            }
        } recover {
          case error: FailedRequest if error.responseCode == BAD_REQUEST =>
            Logger.debug(s"Incorrect username or password for user ${loginForm.email}", error)
            Redirect(routes.Authentication.login()).flashing("error" -> Messages("cave.login.login.incorrectUsernameOrPassword"))
          case NonFatal(e) =>
            Logger.error(s"Unable to authenticate user: ${loginForm.email}", e)
            InternalServerError(views.html.errorpages.errorPage(Messages("cave.login.login.internalError")))
        }
      )
    }
  }
}

object Authentication extends Authentication

case class UserLogin(email: String, password: String, landingUrl: String) 
Example 20
Source File: ChangePasswordController.scala    From play-silhouette-4.0-slick-postgres-seed   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.exceptions.ProviderException
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.util.{ Credentials, PasswordHasherRegistry, PasswordInfo }
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import controllers.{ WebJarAssets, auth }
import forms.auth.ChangePasswordForm
import models.services.UserService
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.{ Action, AnyContent, Controller }
import utils.auth.{ DefaultEnv, WithProvider }

import scala.concurrent.Future


  def submit: Action[AnyContent] = silhouette.SecuredAction(WithProvider[DefaultEnv#A](CredentialsProvider.ID)).async { implicit request =>
    ChangePasswordForm.form.bindFromRequest.fold(
      form => Future.successful(BadRequest(views.html.auth.changePassword(form, request.identity))),
      password => {
        val (currentPassword, newPassword) = password
        val credentials = Credentials(request.identity.email.getOrElse(""), currentPassword)
        credentialsProvider.authenticate(credentials).flatMap { loginInfo =>
          val passwordInfo = passwordHasherRegistry.current.hash(newPassword)
          authInfoRepository.update[PasswordInfo](loginInfo, passwordInfo).map { _ =>
            Redirect(auth.routes.ChangePasswordController.view()).flashing("success" -> Messages("password.changed"))
          }
        }.recover {
          case e: ProviderException =>
            Redirect(auth.routes.ChangePasswordController.view()).flashing("error" -> Messages("current.password.invalid"))
        }
      }
    )
  }
} 
Example 21
Source File: RendersErrors.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package error

import config.ConfigDecorator
import controllers.auth.requests.UserRequest
import play.api.http.Status.{BAD_REQUEST, NOT_FOUND}
import play.api.i18n.Messages
import play.api.mvc._
import uk.gov.hmrc.renderer.TemplateRenderer
import util.LocalPartialRetriever

import scala.concurrent.Future

trait RendersErrors extends Results {

  implicit def templateRenderer: TemplateRenderer

  def futureError(statusCode: Int)(
    implicit request: UserRequest[_],
    configDecorator: ConfigDecorator,
    partialRetriever: LocalPartialRetriever,
    messages: Messages): Future[Result] =
    Future.successful(error(statusCode))

  def error(statusCode: Int)(
    implicit request: UserRequest[_],
    configDecorator: ConfigDecorator,
    partialRetriever: LocalPartialRetriever,
    messages: Messages): Result = {

    val errorKey = statusCode match {
      case BAD_REQUEST => "badRequest400"
      case NOT_FOUND   => "pageNotFound404"
      case _           => "InternalServerError500"
    }
    Status(statusCode)(
      views.html.error(
        s"global.error.$errorKey.title",
        Some(s"global.error.$errorKey.heading"),
        List(s"global.error.$errorKey.message")))
  }

  def unauthenticatedFutureError(statusCode: Int)(
    implicit request: Request[_],
    configDecorator: ConfigDecorator,
    partialRetriever: LocalPartialRetriever,
    messages: Messages): Future[Result] =
    Future.successful(unauthenticatedError(statusCode))

  def unauthenticatedError(statusCode: Int)(
    implicit request: Request[_],
    configDecorator: ConfigDecorator,
    partialRetriever: LocalPartialRetriever,
    messages: Messages): Result = {

    val errorKey = statusCode match {
      case BAD_REQUEST => "badRequest400"
      case NOT_FOUND   => "pageNotFound404"
      case _           => "InternalServerError500"
    }

    Status(statusCode)(
      views.html.unauthenticatedError(
        s"global.error.$errorKey.title",
        Some(s"global.error.$errorKey.heading"),
        Some(s"global.error.$errorKey.message")))

  }

  def notFoundFutureError(
    implicit request: UserRequest[_],
    configDecorator: ConfigDecorator,
    partialRetriever: LocalPartialRetriever,
    messages: Messages): Future[Result] =
    Future.successful(NotFound(views.html.page_not_found_template()))

} 
Example 22
Source File: GenericErrors.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package error

import config.ConfigDecorator
import controllers.auth.requests.UserRequest
import play.api.Play
import play.api.i18n.Messages
import play.api.mvc.Result
import play.api.mvc.Results.{BadRequest, InternalServerError}
import uk.gov.hmrc.renderer.TemplateRenderer
import util.LocalPartialRetriever

object GenericErrors {

  implicit val templateRenderer: TemplateRenderer = Play.current.injector.instanceOf[TemplateRenderer]

  def badRequest(
    implicit request: UserRequest[_],
    configDecorator: ConfigDecorator,
    partialRetriever: LocalPartialRetriever,
    messages: Messages): Result =
    BadRequest(
      views.html.error(
        "global.error.BadRequest.title",
        Some("global.error.BadRequest.title"),
        List("global.error.BadRequest.message1", "global.error.BadRequest.message2")))

  def internalServerError(
    implicit request: UserRequest[_],
    configDecorator: ConfigDecorator,
    partialRetriever: LocalPartialRetriever,
    messages: Messages): Result =
    InternalServerError(
      views.html.error(
        "global.error.InternalServerError500.title",
        Some("global.error.InternalServerError500.title"),
        List("global.error.InternalServerError500.message")))
} 
Example 23
Source File: UpdateAddressResponse.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import config.ConfigDecorator
import controllers.auth.requests.UserRequest
import error.GenericErrors
import play.api.i18n.Messages
import play.api.mvc.Result
import uk.gov.hmrc.http.HttpResponse
import util.LocalPartialRetriever

sealed trait UpdateAddressResponse {
  def response(successResponseBlock: () => Result)(
    implicit request: UserRequest[_],
    configDecorator: ConfigDecorator,
    partialRetriever: LocalPartialRetriever,
    messages: Messages): Result =
    this match {
      case UpdateAddressBadRequestResponse    => GenericErrors.badRequest
      case UpdateAddressUnexpectedResponse(_) => GenericErrors.internalServerError
      case UpdateAddressErrorResponse(_)      => GenericErrors.internalServerError
      case UpdateAddressSuccessResponse       => successResponseBlock()
    }
}
case object UpdateAddressSuccessResponse extends UpdateAddressResponse
case object UpdateAddressBadRequestResponse extends UpdateAddressResponse
case class UpdateAddressUnexpectedResponse(r: HttpResponse) extends UpdateAddressResponse
case class UpdateAddressErrorResponse(cause: Exception) extends UpdateAddressResponse 
Example 24
Source File: MessageController.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers

import com.google.inject.Inject
import config.ConfigDecorator
import controllers.auth._
import error.RendersErrors
import models.Breadcrumb
import play.api.i18n.Messages
import play.api.mvc.{Action, AnyContent, MessagesControllerComponents}
import play.twirl.api.Html
import services.partials.MessageFrontendService
import uk.gov.hmrc.play.partials.HtmlPartial
import uk.gov.hmrc.renderer.{ActiveTabMessages, TemplateRenderer}
import util.LocalPartialRetriever
import views.html.message.{MessageDetailView, MessageInboxView}

import scala.concurrent.ExecutionContext

class MessageController @Inject()(
  val messageFrontendService: MessageFrontendService,
  authJourney: AuthJourney,
  withActiveTabAction: WithActiveTabAction,
  withBreadcrumbAction: WithBreadcrumbAction,
  cc: MessagesControllerComponents,
  messageInboxView: MessageInboxView,
  messageDetailView: MessageDetailView)(
  implicit val partialRetriever: LocalPartialRetriever,
  val configDecorator: ConfigDecorator,
  val templateRenderer: TemplateRenderer,
  ec: ExecutionContext)
    extends PertaxBaseController(cc) with RendersErrors {

  def messageBreadcrumb: Breadcrumb =
    "label.all_messages" -> routes.MessageController.messageList().url ::
      baseBreadcrumb

  def messageList: Action[AnyContent] =
    (authJourney.authWithPersonalDetails andThen withActiveTabAction.addActiveTab(ActiveTabMessages) andThen withBreadcrumbAction
      .addBreadcrumb(baseBreadcrumb)).async { implicit request =>
      messageFrontendService.getMessageListPartial map { p =>
        Ok(
          messageInboxView(
            messageListPartial = p successfulContentOrElse Html(
              Messages("label.sorry_theres_been_a_technical_problem_retrieving_your_messages")))
        )
      }
    }

  def messageDetail(messageToken: String): Action[AnyContent] =
    (authJourney.authWithPersonalDetails andThen withActiveTabAction.addActiveTab(ActiveTabMessages) andThen withBreadcrumbAction
      .addBreadcrumb(messageBreadcrumb)).async { implicit request =>
      messageFrontendService.getMessageDetailPartial(messageToken).map {
        case HtmlPartial.Success(Some(title), content) =>
          Ok(messageDetailView(message = content, title = title))
        case HtmlPartial.Success(None, content) =>
          Ok(messageDetailView(message = content, title = Messages("label.message")))
        case HtmlPartial.Failure(_, _) =>
          Ok(
            messageDetailView(
              message = Html(Messages("label.sorry_theres_been_a_techinal_problem_retrieving_your_message")),
              title = Messages("label.message")
            )
          )
      }
    }
} 
Example 25
Source File: PaperlessPreferencesController.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers

import com.google.inject.Inject
import config.ConfigDecorator
import controllers.auth._
import controllers.auth.requests.UserRequest
import play.api.Mode.Mode
import play.api.i18n.{Messages, MessagesApi}
import play.api.mvc.{Action, AnyContent, MessagesControllerComponents}
import services.partials.PreferencesFrontendPartialService
import play.api.mvc.{Action, AnyContent}
import play.api.{Configuration, Environment}
import uk.gov.hmrc.renderer.{ActiveTabMessages, TemplateRenderer}
import util.{LocalPartialRetriever, Tools}

import scala.concurrent.{ExecutionContext, Future}

class PaperlessPreferencesController @Inject()(
  val preferencesFrontendPartialService: PreferencesFrontendPartialService,
  authJourney: AuthJourney,
  withActiveTabAction: WithActiveTabAction,
  withBreadcrumbAction: WithBreadcrumbAction,
  cc: MessagesControllerComponents,
  tools: Tools)(
  implicit partialRetriever: LocalPartialRetriever,
  configDecorator: ConfigDecorator,
  templateRenderer: TemplateRenderer,
  ec: ExecutionContext)
    extends PertaxBaseController(cc) {

  def managePreferences: Action[AnyContent] =
    (authJourney.authWithPersonalDetails andThen withActiveTabAction
      .addActiveTab(ActiveTabMessages) andThen withBreadcrumbAction.addBreadcrumb(baseBreadcrumb)).async {
      implicit request: UserRequest[_] =>
        if (request.isVerify) {
          Future.successful(
            BadRequest(
              views.html.error(
                "global.error.BadRequest.title",
                Some("global.error.BadRequest.heading"),
                List("global.error.BadRequest.message"))))
        } else {
          Future.successful(
            Redirect(
              getManagePreferencesUrl(configDecorator.pertaxFrontendHomeUrl, Messages("label.back_to_account_home"))))
        }
    }

  private def getManagePreferencesUrl(returnUrl: String, returnLinkText: String): String =
    s"${configDecorator.preferencesFrontendService}/paperless/check-settings?returnUrl=${tools.encryptAndEncode(returnUrl)}&returnLinkText=${tools
      .encryptAndEncode(returnLinkText)}"
} 
Example 26
Source File: HomeCardGenerator.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.controllershelpers

import config.ConfigDecorator
import controllers.auth.requests.UserRequest
import com.google.inject.{Inject, Singleton}
import models._
import play.api.i18n.Messages
import play.api.mvc.AnyContent
import play.twirl.api.{Html, HtmlFormat}
import util.DateTimeTools.previousAndCurrentTaxYear
import viewmodels.TaxCalculationViewModel
import views.html.cards.home._

@Singleton
class HomeCardGenerator @Inject()(
  payAsYouEarnView: PayAsYouEarnView,
  taxCalculationView: TaxCalculationView,
  selfAssessmentView: SelfAssessmentView,
  nationalInsuranceView: NationalInsuranceView,
  taxCreditsView: TaxCreditsView,
  childBenefitView: ChildBenefitView,
  marriageAllowanceView: MarriageAllowanceView,
  statePensionView: StatePensionView
)(implicit configDecorator: ConfigDecorator) {

  def getIncomeCards(
    taxComponentsState: TaxComponentsState,
    taxCalculationStateCyMinusOne: Option[TaxYearReconciliation],
    taxCalculationStateCyMinusTwo: Option[TaxYearReconciliation],
    saActionNeeded: SelfAssessmentUserType,
    currentTaxYear: Int)(implicit request: UserRequest[AnyContent], messages: Messages): Seq[Html] =
    List(
      getPayAsYouEarnCard(taxComponentsState),
      getTaxCalculationCard(taxCalculationStateCyMinusOne),
      getTaxCalculationCard(taxCalculationStateCyMinusTwo),
      getSelfAssessmentCard(saActionNeeded, currentTaxYear + 1),
      getNationalInsuranceCard()
    ).flatten

  def getBenefitCards(taxComponents: Option[TaxComponents])(implicit messages: Messages): Seq[Html] =
    List(
      getTaxCreditsCard(configDecorator.taxCreditsPaymentLinkEnabled),
      getChildBenefitCard(),
      getMarriageAllowanceCard(taxComponents)
    ).flatten

  def getPensionCards()(implicit messages: Messages): Seq[Html] =
    List(
      getStatePensionCard()
    ).flatten

  def getPayAsYouEarnCard(taxComponentsState: TaxComponentsState)(
    implicit request: UserRequest[_],
    messages: Messages): Option[HtmlFormat.Appendable] =
    request.nino.flatMap { _ =>
      taxComponentsState match {
        case TaxComponentsNotAvailableState => None
        case _                              => Some(payAsYouEarnView(configDecorator))
      }
    }

  def getTaxCalculationCard(taxYearReconciliations: Option[TaxYearReconciliation])(
    implicit messages: Messages): Option[HtmlFormat.Appendable] =
    taxYearReconciliations
      .flatMap(TaxCalculationViewModel.fromTaxYearReconciliation)
      .map(taxCalculationView(_))

  def getSelfAssessmentCard(saActionNeeded: SelfAssessmentUserType, nextDeadlineTaxYear: Int)(
    implicit request: UserRequest[AnyContent],
    messages: Messages): Option[HtmlFormat.Appendable] =
    if (!request.isVerify) {
      saActionNeeded match {
        case NonFilerSelfAssessmentUser => None
        case saWithActionNeeded =>
          Some(selfAssessmentView(saWithActionNeeded, previousAndCurrentTaxYear, nextDeadlineTaxYear.toString))
      }
    } else {
      None
    }

  def getNationalInsuranceCard()(implicit messages: Messages): Some[HtmlFormat.Appendable] =
    Some(nationalInsuranceView())

  def getTaxCreditsCard(showTaxCreditsPaymentLink: Boolean)(implicit messages: Messages): Some[HtmlFormat.Appendable] =
    Some(taxCreditsView(showTaxCreditsPaymentLink))

  def getChildBenefitCard()(implicit messages: Messages): Some[HtmlFormat.Appendable] =
    Some(childBenefitView())

  def getMarriageAllowanceCard(taxComponents: Option[TaxComponents])(
    implicit messages: Messages): Some[HtmlFormat.Appendable] =
    Some(marriageAllowanceView(taxComponents))

  def getStatePensionCard()(implicit messages: Messages): Some[HtmlFormat.Appendable] =
    Some(statePensionView())
} 
Example 27
Source File: TaxCalculationViewSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package views.html.cards

import config.ConfigDecorator
import org.jsoup.nodes.Document
import org.scalatest.Assertion
import play.api.i18n.Messages
import viewmodels.Message.text
import viewmodels.{Heading, TaxCalculationViewModel, TaxYears, UnderpaidUrl}
import views.html.ViewSpec
import views.html.cards.home.TaxCalculationView

import scala.collection.JavaConverters._

class TaxCalculationViewSpec extends ViewSpec {

  val taxCalculation = injected[TaxCalculationView]

  implicit val configDecorator: ConfigDecorator = injected[ConfigDecorator]

  def hasLink(document: Document, content: String, href: String)(implicit messages: Messages): Assertion =
    document.getElementsMatchingText(content).eachAttr("href").asScala should contain(href)

  "TaxCalculation card" should {

    val previousTaxYear = 2017

    val doc =
      asDocument(
        taxCalculation(TaxCalculationViewModel(
          TaxYears(previousTaxYear, previousTaxYear + 1),
          Heading(
            text("label.you_do_not_owe_any_more_tax", previousTaxYear.toString, previousTaxYear + 1 toString),
            UnderpaidUrl(previousTaxYear)
          ),
          List(text("label.you_have_no_payments_to_make_to_hmrc")),
          Nil
        )).toString)

    "render the given heading correctly" in {

      doc.text() should include(
        Messages("label.you_do_not_owe_any_more_tax", previousTaxYear.toString, previousTaxYear + 1 toString)
      )
    }

    "render the given url correctly" in {

      hasLink(
        doc,
        Messages("label.you_do_not_owe_any_more_tax", previousTaxYear.toString, previousTaxYear + 1 toString),
        configDecorator.underpaidUrl(previousTaxYear)
      )
    }

    "render the given content correctly" in {

      doc.text() should include(Messages("label.you_have_no_payments_to_make_to_hmrc"))
    }
  }
} 
Example 28
Source File: SocialAuthController.scala    From play-silhouette-4.0-slick-postgres-seed   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.exceptions.ProviderException
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.impl.providers._
import controllers.{ WebJarAssets, auth, pages }
import models.services.UserService
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.{ Action, AnyContent, Controller }
import utils.auth.DefaultEnv

import scala.concurrent.Future


  def authenticate(provider: String): Action[AnyContent] = Action.async { implicit request =>
    (socialProviderRegistry.get[SocialProvider](provider) match {
      case Some(p: SocialProvider with CommonSocialProfileBuilder) =>
        p.authenticate().flatMap {
          case Left(result) => Future.successful(result)
          case Right(authInfo) => for {
            profile <- p.retrieveProfile(authInfo)
            user <- userService.save(profile)
            authInfo <- authInfoRepository.save(profile.loginInfo, authInfo)
            authenticator <- silhouette.env.authenticatorService.create(profile.loginInfo)
            value <- silhouette.env.authenticatorService.init(authenticator)
            result <- silhouette.env.authenticatorService.embed(value, Redirect(pages.routes.ApplicationController.index()))
          } yield {
            silhouette.env.eventBus.publish(LoginEvent(user, request))
            result
          }
        }
      case _ => Future.failed(new ProviderException(s"Cannot authenticate with unexpected social provider $provider"))
    }).recover {
      case e: ProviderException =>
        logger.error("Unexpected provider error", e)
        Redirect(auth.routes.SignInController.view()).flashing("error" -> Messages("could.not.authenticate"))
    }
  }
} 
Example 29
Source File: MockTemplateRenderer.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.utils

import org.scalatest.mock.MockitoSugar
import play.api.Mode.Mode
import play.api.i18n.Messages
import play.api.{Configuration, Play}
import play.twirl.api.Html
import uk.gov.hmrc.nisp.config.{LocalTemplateRenderer, WsAllMethods}

import scala.concurrent.duration._

object MockTemplateRenderer extends LocalTemplateRenderer {
  override lazy val templateServiceBaseUrl = "http://example.com/template/mustache"
  override val refreshAfter = 10 minutes
  override val wsHttp = MockitoSugar.mock[WsAllMethods]

  override def renderDefaultTemplate(path:String, content: Html, extraArgs: Map[String, Any])(implicit messages: Messages) = {
    Html(
      "<title>" + extraArgs("pageTitle") + "</title>"
        + "<sidebar>"+extraArgs("sidebar")+"</sidebar>"
        + "<navLinks>"+extraArgs("navLinks")+"</navLinks>"
        + displayUrBanner(extraArgs) +
        "<mainContentHeader>" +extraArgs("mainContentHeader")+ "</mainContentHeader>"
        + content)
  }

    def displayUrBanner(extraArgs: Map[String, Any]): String ={
      if(extraArgs.contains("fullWidthBannerTitle")){
        "<div id=full-width-banner>" + "<div class = \"full-width-banner__title\">" + extraArgs("fullWidthBannerTitle") + "</div>" + "<div id = fullWidthBannerLink>" + extraArgs("fullWidthBannerLink") +  "</div>"+ "<div>" + extraArgs("fullWidthBannerText")+ "</div>"+ "<div id = fullWidthBannerDismissText>"+extraArgs("fullWidthBannerDismissText")+"</div>"
      }
      else ""
    }

  override protected def mode: Mode = Play.current.mode
  override protected def runModeConfiguration: Configuration = Play.current.configuration
} 
Example 30
Source File: SignInController.scala    From play-silhouette-4.0-slick-postgres-seed   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import javax.inject.Inject

import com.mohiva.play.silhouette.api.Authenticator.Implicits._
import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.exceptions.ProviderException
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.util.{ Clock, Credentials }
import com.mohiva.play.silhouette.impl.exceptions.IdentityNotFoundException
import com.mohiva.play.silhouette.impl.providers._
import controllers.{ WebJarAssets, auth, pages }
import forms.auth.SignInForm
import models.services.UserService
import net.ceedubs.ficus.Ficus._
import play.api.Configuration
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.{ Action, AnyContent, Controller }
import utils.auth.DefaultEnv

import scala.concurrent.Future
import scala.concurrent.duration._
import scala.language.postfixOps


  def submit: Action[AnyContent] = silhouette.UnsecuredAction.async { implicit request =>
    SignInForm.form.bindFromRequest.fold(
      form => Future.successful(BadRequest(views.html.auth.signIn(form, socialProviderRegistry))),
      data => {
        val credentials = Credentials(data.email, data.password)
        credentialsProvider.authenticate(credentials).flatMap { loginInfo =>
          val result = Redirect(pages.routes.ApplicationController.index())
          userService.retrieve(loginInfo).flatMap {
            case Some(user) if !user.activated =>
              Future.successful(Ok(views.html.auth.activateAccount(data.email)))
            case Some(user) =>
              val c = configuration.underlying
              silhouette.env.authenticatorService.create(loginInfo).map {
                case authenticator if data.rememberMe =>
                  authenticator.copy(
                    expirationDateTime = clock.now + c.as[FiniteDuration]("silhouette.authenticator.rememberMe.authenticatorExpiry"),
                    idleTimeout = c.getAs[FiniteDuration]("silhouette.authenticator.rememberMe.authenticatorIdleTimeout"),
                    cookieMaxAge = c.getAs[FiniteDuration]("silhouette.authenticator.rememberMe.cookieMaxAge")
                  )
                case authenticator => authenticator
              }.flatMap { authenticator =>
                silhouette.env.eventBus.publish(LoginEvent(user, request))
                silhouette.env.authenticatorService.init(authenticator).flatMap { v =>
                  silhouette.env.authenticatorService.embed(v, result)
                }
              }
            case None => Future.failed(new IdentityNotFoundException("Couldn't find user"))
          }
        }.recover {
          case e: ProviderException =>
            Redirect(auth.routes.SignInController.view()).flashing("error" -> Messages("invalid.credentials"))
        }
      }
    )
  }
} 
Example 31
Source File: ResetPasswordController.scala    From play-silhouette-4.0-slick-postgres-seed   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import java.util.UUID
import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.util.{ PasswordHasherRegistry, PasswordInfo }
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import controllers.{ WebJarAssets, auth }
import forms.auth.ResetPasswordForm
import models.services.{ AuthTokenService, UserService }
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.{ Action, AnyContent, Controller }
import utils.auth.DefaultEnv

import scala.concurrent.Future


  def submit(token: UUID): Action[AnyContent] = silhouette.UnsecuredAction.async { implicit request =>
    authTokenService.validate(token).flatMap {
      case Some(authToken) =>
        ResetPasswordForm.form.bindFromRequest.fold(
          form => Future.successful(BadRequest(views.html.auth.resetPassword(form, token))),
          password => userService.retrieve(authToken.userID).flatMap {
            case Some(user) if user.loginInfo.providerID == CredentialsProvider.ID =>
              val passwordInfo = passwordHasherRegistry.current.hash(password)
              authInfoRepository.update[PasswordInfo](user.loginInfo, passwordInfo).map { _ =>
                Redirect(auth.routes.SignInController.view()).flashing("success" -> Messages("password.reset"))
              }
            case _ => Future.successful(Redirect(auth.routes.SignInController.view()).flashing("error" -> Messages("invalid.reset.link")))
          }
        )
      case None => Future.successful(Redirect(auth.routes.SignInController.view()).flashing("error" -> Messages("invalid.reset.link")))
    }
  }
} 
Example 32
Source File: SignUpController.scala    From play-silhouette-4.0-slick-postgres-seed   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import java.util.UUID
import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.services.AvatarService
import com.mohiva.play.silhouette.api.util.PasswordHasherRegistry
import com.mohiva.play.silhouette.impl.providers._
import controllers.{ WebJarAssets, auth }
import forms.auth.SignUpForm
import models.User
import models.services.{ AuthTokenService, UserService }
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.mailer.{ Email, MailerClient }
import play.api.mvc.{ Action, AnyContent, Controller }
import utils.auth.DefaultEnv

import scala.concurrent.Future


  def submit: Action[AnyContent] = silhouette.UnsecuredAction.async { implicit request =>
    SignUpForm.form.bindFromRequest.fold(
      form => Future.successful(BadRequest(views.html.auth.signUp(form))),
      data => {
        val result = Redirect(auth.routes.SignUpController.view()).flashing("info" -> Messages("sign.up.email.sent", data.email))
        val loginInfo = LoginInfo(CredentialsProvider.ID, data.email)
        userService.retrieve(loginInfo).flatMap {
          case Some(user) =>
            val url = auth.routes.SignInController.view().absoluteURL()
            mailerClient.send(Email(
              subject = Messages("email.already.signed.up.subject"),
              from = Messages("email.from"),
              to = Seq(data.email),
              bodyText = Some(views.txt.emails.alreadySignedUp(user, url).body),
              bodyHtml = Some(views.html.emails.alreadySignedUp(user, url).body)
            ))

            Future.successful(result)
          case None =>
            val authInfo = passwordHasherRegistry.current.hash(data.password)
            val user = User(
              userID = UUID.randomUUID(),
              loginInfo = loginInfo,
              firstName = Some(data.firstName),
              lastName = Some(data.lastName),
              fullName = Some(data.firstName + " " + data.lastName),
              email = Some(data.email),
              avatarURL = None,
              activated = false
            )
            for {
              avatar <- avatarService.retrieveURL(data.email)
              user <- userService.save(user.copy(avatarURL = avatar))
              authInfo <- authInfoRepository.add(loginInfo, authInfo)
              authToken <- authTokenService.create(user.userID)
            } yield {
              val url = auth.routes.ActivateAccountController.activate(authToken.id).absoluteURL()
              mailerClient.send(Email(
                subject = Messages("email.sign.up.subject"),
                from = Messages("email.from"),
                to = Seq(data.email),
                bodyText = Some(views.txt.emails.signUp(user, url).body),
                bodyHtml = Some(views.html.emails.signUp(user, url).body)
              ))

              silhouette.env.eventBus.publish(SignUpEvent(user, request))
              result
            }
        }
      }
    )
  }
} 
Example 33
Source File: ActivateAccountController.scala    From play-silhouette-4.0-slick-postgres-seed   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import java.net.URLDecoder
import java.util.UUID
import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import controllers.{ WebJarAssets, auth }
import models.services.{ AuthTokenService, UserService }
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.mailer.{ Email, MailerClient }
import play.api.mvc.{ Action, AnyContent, Controller }
import utils.auth.DefaultEnv

import scala.concurrent.Future
import scala.language.postfixOps


  def activate(token: UUID): Action[AnyContent] = silhouette.UnsecuredAction.async { implicit request =>
    authTokenService.validate(token).flatMap {
      case Some(authToken) => userService.retrieve(authToken.userID).flatMap {
        case Some(user) if user.loginInfo.providerID == CredentialsProvider.ID =>
          userService.save(user.copy(activated = true)).map { _ =>
            Redirect(auth.routes.SignInController.view()).flashing("success" -> Messages("account.activated"))
          }
        case _ => Future.successful(Redirect(auth.routes.SignInController.view()).flashing("error" -> Messages("invalid.activation.link")))
      }
      case None => Future.successful(Redirect(auth.routes.SignInController.view()).flashing("error" -> Messages("invalid.activation.link")))
    }
  }
} 
Example 34
Source File: ForgotPasswordController.scala    From play-silhouette-4.0-slick-postgres-seed   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import controllers.{ WebJarAssets, auth }
import forms.auth.ForgotPasswordForm
import models.services.{ AuthTokenService, UserService }
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.mailer.{ Email, MailerClient }
import play.api.mvc.{ Action, AnyContent, Controller }
import utils.auth.DefaultEnv

import scala.concurrent.Future


  def submit: Action[AnyContent] = silhouette.UnsecuredAction.async { implicit request =>
    ForgotPasswordForm.form.bindFromRequest.fold(
      form => Future.successful(BadRequest(views.html.auth.forgotPassword(form))),
      email => {
        val loginInfo = LoginInfo(CredentialsProvider.ID, email)
        val result = Redirect(auth.routes.SignInController.view()).flashing("info" -> Messages("reset.email.sent"))
        userService.retrieve(loginInfo).flatMap {
          case Some(user) if user.email.isDefined =>
            authTokenService.create(user.userID).map { authToken =>
              val url = auth.routes.ResetPasswordController.view(authToken.id).absoluteURL()

              mailerClient.send(Email(
                subject = Messages("email.reset.password.subject"),
                from = Messages("email.from"),
                to = Seq(email),
                bodyText = Some(views.txt.emails.resetPassword(user, url).body),
                bodyHtml = Some(views.html.emails.resetPassword(user, url).body)
              ))
              result
            }
          case None => Future.successful(result)
        }
      }
    )
  }
} 
Example 35
Source File: NispBreadcrumb.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.utils

import play.api.i18n.Messages
import play.api.mvc.Request
import uk.gov.hmrc.nisp.config.ApplicationConfig
import uk.gov.hmrc.nisp.controllers.routes
import uk.gov.hmrc.play.breadcrumb.model.{Breadcrumb, BreadcrumbItem}

object NispBreadcrumb extends NispBreadcrumb {
  override lazy val applicationConfig = ApplicationConfig
}

trait NispBreadcrumb{

  val applicationConfig: ApplicationConfig

  def initialBreadCrumbList(implicit messages: Messages) = List((messages("nisp.breadcrumb.account"), applicationConfig.pertaxFrontendUrl))

  lazy val mainContentHeaderPartialUrl = applicationConfig.breadcrumbPartialUrl

   def buildBreadCrumb(implicit request: Request[_], messages: Messages): Breadcrumb = {
    val links = Map(
      "account" -> (Messages("nisp.breadcrumb.pension"), routes.StatePensionController.show().url),
      "nirecord" -> (Messages("nisp.breadcrumb.nirecord"), routes.NIRecordController.showFull().url),
      "voluntarycontribs" -> (Messages("nisp.breadcrumb.nirecord.voluntaryContrib"), routes.NIRecordController.showVoluntaryContributions().url),
      "gapsandhowtocheck" -> (Messages("nisp.breadcrumb.nirecord.gapsandhowtocheck"), routes.NIRecordController.showGapsAndHowToCheckThem().url),
      "exclusion" -> (Messages("nisp.breadcrumb.excluded"), routes.ExclusionController.showSP().url),
      "exclusionni" -> (Messages("nisp.breadcrumb.excluded"), routes.ExclusionController.showNI().url),
      "cope" -> (Messages("nisp.breadcrumb.cope"), routes.StatePensionController.showCope().url)
    )

    val items: List[Option[(String, String)]] = request.path.split("/").filter(!_.isEmpty).map(links.get).toList
    val breacrumList = initialBreadCrumbList ::: items.flatten

    val bcItems: Seq[BreadcrumbItem] = breacrumList.map( { case(label, url) => BreadcrumbItem(label, url) })
    Breadcrumb(bcItems.toVector)
  }

} 
Example 36
Source File: ApplicationGlobal.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.config

import com.typesafe.config.Config
import net.ceedubs.ficus.Ficus._
import play.api.Mode.Mode
import play.api.i18n.{I18nSupport, Messages, MessagesApi}
import play.api.mvc.Request
import play.api.{Application, Configuration, Play}
import play.twirl.api.Html
import uk.gov.hmrc.crypto.ApplicationCrypto
import uk.gov.hmrc.nisp.config.wiring.NispAuditConnector
import uk.gov.hmrc.nisp.controllers.NispFrontendController
import uk.gov.hmrc.nisp.controllers.partial.PartialRetriever
import uk.gov.hmrc.play.config.{AppName, ControllerConfig, RunMode}
import uk.gov.hmrc.play.frontend.bootstrap.DefaultFrontendGlobal
import uk.gov.hmrc.play.frontend.filters.{FrontendAuditFilter, FrontendLoggingFilter, MicroserviceFilterSupport}

object ApplicationGlobal extends ApplicationGlobalTrait {
  override protected def mode: Mode = Play.current.mode
  override protected def runModeConfiguration: Configuration = Play.current.configuration
  override def messagesApi = Play.current.injector.instanceOf[MessagesApi]
}

trait ApplicationGlobalTrait extends DefaultFrontendGlobal with RunMode with PartialRetriever with NispFrontendController with I18nSupport {

  implicit lazy val app:Application = Play.current

  override val auditConnector = NispAuditConnector
  override val loggingFilter = NispLoggingFilter
  override val frontendAuditFilter = NispFrontendAuditFilter

  override def onStart(app: Application) {
    super.onStart(app)
    new ApplicationCrypto(Play.current.configuration.underlying).verifyConfiguration()
  }

  override def internalServerErrorTemplate(implicit request: Request[_]): Html =
    uk.gov.hmrc.nisp.views.html.service_error_500()

  override def standardErrorTemplate(pageTitle: String, heading: String, message: String)(implicit request: Request[_]): Html =
    uk.gov.hmrc.nisp.views.html.global_error(pageTitle, heading, message)

  override def notFoundTemplate(implicit request: Request[_]): Html = {
    uk.gov.hmrc.nisp.views.html.page_not_found_template()
  }

  override def microserviceMetricsConfig(implicit app: Application): Option[Configuration] = app.configuration.getConfig(s"microservice.metrics")
}

object ControllerConfiguration extends ControllerConfig {
  lazy val controllerConfigs = Play.current.configuration.underlying.as[Config]("controllers")
}

object NispLoggingFilter extends FrontendLoggingFilter with MicroserviceFilterSupport {
  override def controllerNeedsLogging(controllerName: String): Boolean = ControllerConfiguration.paramsForController(controllerName).needsLogging
}

object NispFrontendAuditFilter extends FrontendAuditFilter with RunMode with AppName with MicroserviceFilterSupport {
  override lazy val maskedFormFields = Seq.empty
  override lazy val applicationPort = None
  override lazy val auditConnector = NispAuditConnector
  override def controllerNeedsAuditing(controllerName: String): Boolean = ControllerConfiguration.paramsForController(controllerName).needsAuditing
  override protected def mode: Mode = Play.current.mode
  override protected def runModeConfiguration: Configuration = Play.current.configuration
  override protected def appNameConfiguration: Configuration = Play.current.configuration
} 
Example 37
Source File: ViewUtils.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package views.util

import config.ConfigDecorator
import play.api.i18n.Messages
import util.LanguageHelper
import viewmodels._

object ViewUtils {

  def fromMessage(message: Message)(implicit messages: Messages): String =
    message match {
      case Text(key, args)     => messages(key, args.map(fromMessage): _*)
      case Date(date, default) => LanguageHelper.langUtils.Dates.formatDate(date, default)
      case Literal(value)      => value
    }

  def fromUrl(url: Url)(implicit configDecorator: ConfigDecorator): String =
    url match {
      case MakePaymentUrl            => configDecorator.makePaymentUrl
      case TaxPaidUrl                => configDecorator.taxPaidUrl
      case UnderpaidUrl(year)        => configDecorator.underpaidUrl(year)
      case UnderpaidReasonsUrl(year) => configDecorator.underpaidUrlReasons(year)
      case OverpaidUrl(year)         => configDecorator.overpaidUrl(year)
      case OverpaidReasonsUrl(year)  => configDecorator.overpaidUrlReasons(year)
      case RightAmountUrl(year)      => configDecorator.rightAmountUrl(year)
      case NotCalculatedUrl(year)    => configDecorator.notCalculatedUrl(year)
      case NotEmployedUrl(year)      => configDecorator.notEmployedUrl(year)
      case Empty                     => ""
    }
}