play.api.i18n.MessagesApi Scala Examples

The following examples show how to use play.api.i18n.MessagesApi. 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: ComputerController.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers.api

import com.google.inject.Inject
import dao.{ComputerDAO, UserDAO}
import play.Logger
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.libs.json.Json
import play.api.mvc.{Action, Controller}
import services.state.ActionCompleted
import services.{ComputerService, LaboratoryService, SSHOrderService}
import views.html._

import scala.concurrent.ExecutionContext.Implicits.global


class ComputerController @Inject()(computerService: ComputerService, computerDAO: ComputerDAO, sSHOrderService: SSHOrderService, val messagesApi: MessagesApi) extends Controller with I18nSupport {

  def shutdown(ip: String) = Action.async {
    implicit request =>
      computerDAO.get(ip).map {
        case Some(computer) if sSHOrderService.shutdown(computer)("Scheduled Checker")==ActionCompleted => Ok(Json.parse(
          """
            {
               "answer":"shutted down"
            }
          """))
        case _ => NotFound(Json.parse(
          """
            {
               "answer":"not found"
            }
          """))
      }
  }
} 
Example 3
Source File: PasswordSettingsController.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.my.settings

import com.mohiva.play.silhouette.api.Silhouette
import controllers.{ HasConfig, HasUserService, Security }
import javax.inject.Inject
import services.user.UserService
import services.user.Roles._
import play.api.Configuration
import play.api.data.Form
import play.api.data.Forms._
import play.api.data.validation._
import play.api.i18n.{ I18nSupport, MessagesApi }
import play.api.mvc.{AbstractController, ControllerComponents}
import scala.concurrent.{ ExecutionContext, Future }

case class PasswordSettingsData(currentPassword: String, newPassword: String, verifyPassword: String)

class PasswordSettingsController @Inject() (
    val components: ControllerComponents,
    val config: Configuration,
    val users: UserService,
    val silhouette: Silhouette[Security.Env],
    implicit val ctx: ExecutionContext
  ) extends AbstractController(components) with HasConfig with HasUserService with I18nSupport {

  private val matchingPasswords: Constraint[PasswordSettingsData] = Constraint("constraints.valid") { d =>
    if (d.newPassword == d.verifyPassword) Valid else Invalid("Passwords must match")
  }

  val passwordSettingsForm = Form(
    mapping(
      "current" -> nonEmptyText,
      "new" -> nonEmptyText,
      "verify" -> nonEmptyText
    )(PasswordSettingsData.apply)(PasswordSettingsData.unapply).verifying(matchingPasswords)
  )

  def index() = silhouette.SecuredAction { implicit request =>
    Ok(views.html.my.settings.password(passwordSettingsForm, request.identity))
  }

  def updatePassword() = silhouette.SecuredAction.async { implicit request =>
    passwordSettingsForm.bindFromRequest.fold(
      formWithErrors =>
        Future.successful(BadRequest(views.html.my.settings.password(formWithErrors, request.identity))),

      f => {
        users.updatePassword(request.identity.username, f.currentPassword, f.newPassword)
          .map { _ match {
            case Right(_) =>
              Redirect(routes.PasswordSettingsController.index).flashing("success" -> "Your password has been updated.")
            case Left(errorMessage) =>
              Redirect(routes.PasswordSettingsController.index).flashing("error" -> errorMessage)
          }}.recover { case t:Throwable => {
            t.printStackTrace()
            Redirect(routes.PasswordSettingsController.index).flashing("error" -> "There was an error while updating your password.")
          }}
      }
    )
  }

} 
Example 4
Source File: LaboratoryController.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers

import com.google.inject.Inject
import model.Role
import play.api.Environment
import play.api.i18n.MessagesApi
import play.api.libs.json.Json
import play.api.mvc.{Action, AnyContent}
import services.{LaboratoryService, UserService}

import scala.concurrent.ExecutionContext


class LaboratoryController @Inject()(laboratoryService: LaboratoryService, val messagesApi: MessagesApi)(implicit userService: UserService, environment: Environment, executionContext: ExecutionContext) extends ControllerWithNoAuthRequired {

  def getAll: Action[AnyContent] = Action.async { implicit request=>
    laboratoryService.listAll.map(result => {
      Ok(Json.toJson(result))
    })
  }

  def get(id: Long) = AsyncStack { implicit request =>
    implicit val (username: Option[String], isAdmin: Boolean) = loggedIn match {
      case Some(user) => (Some(user.username), user.role == Role.Administrator)
      case _ => (None, false)
    }
    laboratoryService.get(id).map {
      case Some((laboratoryObject, roomsWithComputers)) => Ok(Json.toJson((laboratoryObject, roomsWithComputers)))
      case _ => NotImplemented//index(messagesApi("laboratory.notFound"),notImplemented(messagesApi("laboratory.notFound"))))
    }
  }

} 
Example 5
Source File: SuggestionController.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers

import java.sql.Timestamp
import java.util.Calendar

import com.google.inject.Inject
import model.form.SuggestionForm
import model.{Role, Suggestion}
import play.api.Environment
import play.api.i18n.MessagesApi
import services.{SuggestionService, UserService, state}
import views.html._

import scala.concurrent.{ExecutionContext, Future}


class SuggestionController @Inject()(suggestionService: SuggestionService, val messagesApi: MessagesApi)(implicit userService: UserService, executionContext: ExecutionContext, environment: Environment) extends ControllerWithNoAuthRequired {
  def home = AsyncStack { implicit request =>
    implicit val (username: Option[String], isAdmin: Boolean) = loggedIn match {
      case Some(user) => (Some(user.username), user.role == Role.Administrator)
      case _ => (None, false)
    }
    if (isAdmin) {
      suggestionService.listAll.map { suggestions =>
        Ok//(index(messagesApi("suggestion"), suggestionHome(SuggestionForm.form, suggestions)))
      }
    } else {
      Future.successful(Ok)//(index(messagesApi("suggestion"), suggestionHome(SuggestionForm.form, Seq.empty[Suggestion]))))
    }


  }

  def add = AsyncStack() { implicit request =>
    implicit val (username: Option[String], isAdmin: Boolean) = loggedIn match {
      case Some(user) => (Some(user.username), user.role == Role.Administrator)
      case _ => (None, false)
    }
    SuggestionForm.form.bindFromRequest().fold(
      errorForm => Future.successful(Ok(errorForm.toString)),
      data => {
        val text = data.suggestion
        val suggestion = Suggestion(0, text, now, username)
        suggestionService.add(suggestion).map {
          case state.ActionCompleted => Redirect(routes.SuggestionController.home())
          case _ => BadRequest
        }
      }
    )
  }

  private def now = new Timestamp(Calendar.getInstance().getTime.getTime)
} 
Example 6
Source File: HomeController.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers

import akka.actor.{ActorRef, ActorSystem}
import com.google.inject.name.Named
import com.google.inject.{Inject, Singleton}
import dao.{DatabaseInitializer, LaboratoryDAO, UserDAO}
import model.{Role, User}
import play.api.{Environment, Logger}
import play.api.i18n.MessagesApi
import services.{LaboratoryService, UserService}
import views.html._

import scala.concurrent.{Await, ExecutionContext}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._


@Singleton
class HomeController @Inject()(databaseInitializer: DatabaseInitializer, laboratoryService : LaboratoryService, @Named("computerChecker") computerChecker: ActorRef, actorSystem: ActorSystem)(implicit userService: UserService, executionContext: ExecutionContext, environment: Environment) extends ControllerWithNoAuthRequired {
  val logger = Logger("HomeController")

  play.Logger.debug("Configuring Computer Checker...")
  actorSystem.scheduler.schedule(0.microseconds,5.minutes, computerChecker,"Execute")
  play.Logger.debug("Computer Checker configured.")

  logger.debug("Initializing database")
  Await.result(databaseInitializer.initialize(), 2.seconds)
  logger.debug("Database initialized")

  def home = AsyncStack { implicit request =>
    play.Logger.debug("Logged user: " + loggedIn)
    implicit val (username: Option[String], isAdmin: Boolean) = loggedIn match {
      case Some(User(usernameString, password, Some(name), role)) => (Some(name), role == Role.Administrator)
      case Some(User(usernameString, password, None, role)) => (Some(usernameString), role == Role.Administrator)
      case _ => (None, false)
    }
    logger.debug("PeticiĆ³n de listar todos los laboratorios con el siguiente request recibida " + request)
    logger.debug("User: " + username + ", is admin: " + isAdmin)
    laboratoryService.listAll.map { _ =>
      Ok(index("Aton"))
    }
  }

  def about = StackAction { implicit request =>
    implicit val (username: Option[String], isAdmin: Boolean) = loggedIn match {
      case Some(User(usernameString, password, Some(name), role)) => (Some(name), role == Role.Administrator)
      case Some(User(usernameString, password, None, role)) => (Some(usernameString), role == Role.Administrator)
      case _ => (None, false)
    }

    Ok//(index(messagesApi("about"),views.html.about()))
  }
} 
Example 7
Source File: LaboratoryControllerSuccessfulSpec.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers.admin

import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import org.mockito.Matchers.any
import org.mockito.Mockito.when
import com.google.inject.ImplementedBy
import com.google.inject.Inject
import jp.t2v.lab.play2.auth.test.Helpers.AuthFakeRequest
import model.Laboratory
import model.Role
import model.User
import model.form.LaboratoryForm
import model.form.data.LaboratoryFormData
import model.json.{LaboratoryJson, LoginJson}
import play.api.Environment
import play.api.i18n.MessagesApi
import play.api.libs.json.Json
import play.api.test.FakeRequest
import play.test.WithApplication
import services.LaboratoryService
import services.RoomService
import services.UserService
import services.impl.LaboratoryServiceImpl
import services.state
import services.state.ActionState
import test.ControllerTest


class LaboratoryControllerSuccessfulSpec extends LaboratoryControllerSpec {
  val labService: LaboratoryService = mockLaboratoryService(state.ActionCompleted)
  // Controller to be tested, with the dependencies
  lazy val controller = new LaboratoryController(labService, messagesApi)(userService, executionContext, environment)

  "Laboratory Controller on successful operations" should {
    "return Ok <200> status on receiving an edited laboratory" in {
      import laboratory._
      val laboratoryData = LaboratoryFormData(name, location, administration)
      val laboratoryForm = LaboratoryForm.form.fill(laboratoryData)
      val result = controller.update.apply {
        FakeRequest()
          .withLoggedIn(controller)(loggedInUser)
          .withJsonBody(Json.toJson(laboratory))
      }
      assertFutureResultStatus(result, 200)
    }

    "return Ok <200> status on deleting a laboratory" in {
      val result = controller.delete(laboratory.id).apply {
        FakeRequest()
          .withLoggedIn(controller)(LoginJson("admin", "adminaton"))
      }
      assertFutureResultStatus(result, 200)
    }

    "return Ok <200> status on adding a new laboratory" in {
      import laboratory._
      val laboratoryData = LaboratoryJson(name, location, administration)
      val result = controller.add.apply {
        FakeRequest()
          .withLoggedIn(controller)(loggedInUser)
          .withJsonBody(Json.toJson(laboratoryData))
      }
      assertFutureResultStatus(result, 200)
    }

    "return Ok <200> status when listing all laboratories" in pending
    "return laboratory list json when listing all laboratories" in pending
  }
} 
Example 8
Source File: LoginControllerSpec.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers

import model.json.LoginJson
import model.{Computer, Role, User}
import org.mockito.Matchers._
import org.mockito.Mockito._
import play.api.Environment
import play.api.i18n.MessagesApi
import services.state.ActionState
import services.{UserService, state}
import test.ControllerTest

import scala.concurrent.{ExecutionContext, Future}


  def mockUserService(actionState: ActionState): UserService = {
    // Mock the computer service
    lazy val userService = mock[UserService]

    val user = if(actionState == state.ActionCompleted){
      Some(userToBeUsed)
    } else {
      None
    }

    // This state will be used for methods that don't have other states that ActionCompleted and Failed
    val alternativeState = if(actionState!=state.ActionCompleted){
      state.Failed
    } else {
      actionState
    }

    when(userService.checkAndGet(any[LoginJson])) thenReturn(Future.successful(user))
    when(userService.checkAndGet(any[String],any[String])) thenReturn(Future.successful(user))
    when(userService.add(any[User])) thenReturn(Future.successful(actionState))
    when(userService.get(any[String])) thenReturn(Future.successful(user))
    when(userService.listAll) thenReturn(Future.successful(userList))

    userService
  }
} 
Example 9
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 10
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 11
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 12
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 13
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 14
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 15
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 16
Source File: WFConsumerController.scala    From Scala-Reactive-Programming   with MIT License 5 votes vote down vote up
package controllers

import javax.inject.Inject
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc.{Action, AnyContent}
import com.packt.publishing.wf.api.WFService
import com.packt.publishing.wf.consumer.api.WFConsumerService
import com.packt.publishing.wf.consumer.api.models.WeatherForcasting
import play.api.libs.json.{Format, Json}
import scala.concurrent.ExecutionContext

class WFConsumerController @Inject()(val messagesApi: MessagesApi, wfService: WFService, wfConsumerService: WFConsumerService)(implicit ec: ExecutionContext)
  extends WFAbstractController(messagesApi, wfService, wfConsumerService) with I18nSupport {

  def weather(): Action[AnyContent] = Action.async { implicit request =>
    wfConsumerService.findTopTenWFData().invoke().map {
      (result: Seq[WeatherForcasting]) => Ok(Json.toJson(result))
    }
  }

  def weatherOne(): Action[AnyContent] = Action.async { implicit request =>
    wfConsumerService.findOneWFData().invoke().map {
      (result: WeatherForcasting) => Ok(Json.toJson(result))
    }
  }

  def latestWeather(): Action[AnyContent] = Action.async { implicit request =>
    wfConsumerService.latestWF().invoke().map {
      (result:WeatherForcasting) => Ok(Json.toJson(result))
    }
  }

} 
Example 17
Source File: WFController.scala    From Scala-Reactive-Programming   with MIT License 5 votes vote down vote up
package controllers

import javax.inject.Inject
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc.{Action, AnyContent}
import scala.concurrent.{ExecutionContext, Future}
import com.packt.publishing.wf.api.WFService
import com.packt.publishing.wf.api.model.WFMessage
import com.packt.publishing.wf.consumer.api.WFConsumerService
import models.WFForm._

class WFController @Inject()(val messagesApi: MessagesApi, wfService: WFService, wfConsumerService: WFConsumerService)(implicit ec: ExecutionContext)
  extends WFAbstractController(messagesApi, wfService, wfConsumerService) with I18nSupport {

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

  def changeWF(): Action[AnyContent] = Action.async { implicit request =>
    wfForm.bindFromRequest.fold(
      badForm => Future {
        BadRequest(views.html.wf(badForm))
      },
      validForm => {
        for {
          result <- wfService.wfTemperature(validForm.city, validForm.temperature)
                             .invoke(WFMessage(validForm.city, validForm.temperature))
        }
          yield {
            Ok("WeatherForecast saved to data store successfully.")
          }
      }
    )
  }

} 
Example 18
Source File: WFConsumerController.scala    From Scala-Reactive-Programming   with MIT License 5 votes vote down vote up
package controllers

import javax.inject.Inject
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc.{Action, AnyContent}
import com.packt.publishing.wf.api.WFService
import com.packt.publishing.wf.consumer.api.WFConsumerService
import com.packt.publishing.wf.consumer.api.models.WeatherForcasting
import play.api.libs.json.{Format, Json}
import scala.concurrent.ExecutionContext

class WFConsumerController @Inject()(val messagesApi: MessagesApi, wfService: WFService, wfConsumerService: WFConsumerService)(implicit ec: ExecutionContext)
  extends WFAbstractController(messagesApi, wfService, wfConsumerService) with I18nSupport {

  def weather(): Action[AnyContent] = Action.async { implicit request =>
    wfConsumerService.findTopTenWFData().invoke().map {
      (result: Seq[WeatherForcasting]) => Ok(Json.toJson(result))
    }
  }

  def weatherOne(): Action[AnyContent] = Action.async { implicit request =>
    wfConsumerService.findOneWFData().invoke().map {
      (result: WeatherForcasting) => Ok(Json.toJson(result))
    }
  }

  def latestWeather(): Action[AnyContent] = Action.async { implicit request =>
    wfConsumerService.latestWF().invoke().map {
      (result:WeatherForcasting) => Ok(Json.toJson(result))
    }
  }

} 
Example 19
Source File: WFController.scala    From Scala-Reactive-Programming   with MIT License 5 votes vote down vote up
package controllers

import javax.inject.Inject
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc.{Action, AnyContent}
import scala.concurrent.{ExecutionContext, Future}
import com.packt.publishing.wf.api.WFService
import com.packt.publishing.wf.api.model.WFMessage
import com.packt.publishing.wf.consumer.api.WFConsumerService
import models.WFForm._

class WFController @Inject()(val messagesApi: MessagesApi, wfService: WFService, wfConsumerService: WFConsumerService)(implicit ec: ExecutionContext)
  extends WFAbstractController(messagesApi, wfService, wfConsumerService) with I18nSupport {

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

  def changeMessage(): Action[AnyContent] = Action.async { implicit request =>
    wfForm.bindFromRequest.fold(
      badForm => Future {
        BadRequest(views.html.wf(badForm))
      },
      validForm => {
        for {
          result <- wfService.wfTemperature(validForm.city, validForm.temperature)
                             .invoke(WFMessage(validForm.city, validForm.temperature))
        }
          yield {
            Ok("WeatherForecast saved to data store successfully.")
          }
      }
    )
  }

} 
Example 20
Source File: AuthenticationController.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.exceptions.ProviderException
import com.mohiva.play.silhouette.api.{ LoginEvent, LogoutEvent }
import com.mohiva.play.silhouette.impl.exceptions.IdentityNotFoundException
import com.mohiva.play.silhouette.impl.providers.{ CommonSocialProfile, CommonSocialProfileBuilder, SocialProvider }
import models.user.{ User, UserForms }
import play.api.i18n.MessagesApi
import services.user.AuthenticationEnvironment
import play.api.libs.concurrent.Execution.Implicits.defaultContext

import scala.concurrent.Future

@javax.inject.Singleton
class AuthenticationController @javax.inject.Inject() (
    override val messagesApi: MessagesApi,
    override val env: AuthenticationEnvironment
) extends BaseController {
  def signInForm = withSession { implicit request =>
    Future.successful(Ok(views.html.signin(request.identity, UserForms.signInForm)))
  }

  def authenticateCredentials = withSession { implicit request =>
    UserForms.signInForm.bindFromRequest.fold(
      form => Future.successful(BadRequest(views.html.signin(request.identity, form))),
      credentials => env.credentials.authenticate(credentials).flatMap { loginInfo =>
        val result = Redirect(controllers.routes.HomeController.index())
        env.identityService.retrieve(loginInfo).flatMap {
          case Some(user) => env.authenticatorService.create(loginInfo).flatMap { authenticator =>
            env.eventBus.publish(LoginEvent(user, request, request2Messages))
            env.authenticatorService.init(authenticator).flatMap(v => env.authenticatorService.embed(v, result))
          }
          case None => Future.failed(new IdentityNotFoundException("Couldn't find user."))
        }
      }.recover {
        case e: ProviderException =>
          Redirect(controllers.routes.AuthenticationController.signInForm()).flashing(("error", "Invalid credentials."))
      }
    )
  }

  def authenticateSocial(provider: String) = withSession { implicit request =>
    (env.providersMap.get(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 <- env.userService.create(mergeUser(request.identity, profile), profile)
            authInfo <- env.authInfoService.save(profile.loginInfo, authInfo)
            authenticator <- env.authenticatorService.create(profile.loginInfo)
            value <- env.authenticatorService.init(authenticator)
            result <- env.authenticatorService.embed(value, Redirect(controllers.routes.HomeController.index()))
          } yield {
            env.eventBus.publish(LoginEvent(user, request, request2Messages))
            result
          }
        }
      case _ => Future.failed(new ProviderException("Invalid provider [" + provider + "]."))
    }).recover {
      case e: ProviderException =>
        logger.error("Unexpected provider error", e)
        Redirect(routes.AuthenticationController.signInForm()).flashing(("error", "Service error with provider [" + provider + "]."))
    }
  }

  def signOut = SecuredAction.async { implicit request =>
    val result = Redirect(controllers.routes.HomeController.index())
    env.eventBus.publish(LogoutEvent(request.identity, request, request2Messages))
    env.authenticatorService.discard(request.authenticator, result).map(x => result)
  }

  private[this] def mergeUser(user: User, profile: CommonSocialProfile) = {
    user.copy(
      username = if (profile.firstName.isDefined && user.username.isEmpty) { profile.firstName } else { user.username }
    )
  }
} 
Example 21
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 22
Source File: ExtendedController.scala    From bay-scalajs.g8   with Apache License 2.0 5 votes vote down vote up
package controllers

import cats.data.EitherT
import play.api.data.Form
import play.api.mvc.Controller
import play.api.mvc.Request
import play.api.mvc.Result
import shared.utils.Codecs
import shared.utils.Implicits
import cats.syntax.either._
import play.api.i18n.MessagesApi
import services.Services

import scala.concurrent.ExecutionContext
import scala.concurrent.Future


trait ExtendedController extends Controller with Implicits with Codecs {
  val services: Services
  implicit val ec: ExecutionContext

  type HttpResult[A] = EitherT[Future, Result, A]

  // Constructors for our result type
  object HttpResult {

    def point[A](a: A): HttpResult[A] =
      EitherT[Future, Result, A](Future.successful(Right(a)))

    def fromFuture[A](fa: Future[A]): HttpResult[A] =
      EitherT[Future, Result, A](fa.map(Right(_)))

    def fromEither[A](va: Either[Result, A]): HttpResult[A] =
      EitherT[Future, Result, A](Future.successful(va))

    def fromEither[A, B](failure: B => Result)(va: Either[B, A]): HttpResult[A] =
      EitherT[Future, Result, A](Future.successful(va.leftMap(failure)))

    def fromOption[A](failure: Result)(oa: Option[A]): HttpResult[A] =
      EitherT[Future, Result, A](Future.successful(oa.toRight(failure)))

    def fromFOption[A](failure: Result)(foa: Future[Option[A]]): HttpResult[A] =
      EitherT[Future, Result, A](foa.map(_.toRight(failure)))

    def fromFEither[A, B](failure: B => Result)(fva: Future[Either[B, A]]): HttpResult[A] =
      EitherT[Future, Result, A](fva.map(_.leftMap(failure)))

    def fromForm[FormType](failure: Form[FormType] => Result)(form: Form[FormType])(
        implicit request: Request[_]): HttpResult[FormType] =
      EitherT[Future, Result, FormType](
        form.bindFromRequest.fold(errorForm => Left(failure(errorForm)).asFuture,
                                  formEntity => Right(formEntity).asFuture))
  }

  def constructResult(result: HttpResult[Result]): Future[Result] = result.value.map(_.merge)

  implicit class ExtResult(e: Result) {

    def pureResult: HttpResult[Result] =
      EitherT[Future, Result, Result](Future.successful(Right(e)))
  }

  implicit class EnrichedOps[T](t: T) {
    def |>[R](f: T => R): R = f(t)
  }

  def messagesApi: MessagesApi = services.messagesApi
} 
Example 23
Source File: CustomSecuredErrorHandler.scala    From gospeak   with Apache License 2.0 5 votes vote down vote up
package gospeak.web.auth.services

import com.mohiva.play.silhouette.api.actions.SecuredErrorHandler
import gospeak.web.api.domain.utils.ErrorResult
import gospeak.web.auth.routes.AuthCtrl
import gospeak.web.pages.user.routes.UserCtrl
import gospeak.web.utils.HttpUtils
import play.api.http.Status
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.libs.json.Json
import play.api.mvc.Results._
import play.api.mvc.{RequestHeader, Result}

import scala.concurrent.Future

class CustomSecuredErrorHandler(val messagesApi: MessagesApi) extends SecuredErrorHandler with I18nSupport {
  override def onNotAuthenticated(implicit req: RequestHeader): Future[Result] = {
    val message = "Unauthorized: please login"
    if (req.uri.startsWith("/api")) {
      Future.successful(Unauthorized(Json.toJson(ErrorResult(Status.UNAUTHORIZED, message, execMs = 0))))
    } else {
      Future.successful(Redirect(AuthCtrl.login(Some(req.uri))).flashing("warning" -> message))
    }
  }

  override def onNotAuthorized(implicit req: RequestHeader): Future[Result] = {
    val message = "Forbidden: it seems you lack some rights here"
    if (req.uri.startsWith("/api")) {
      Future.successful(Unauthorized(Json.toJson(ErrorResult(Status.FORBIDDEN, message, execMs = 0))))
    } else {
      val next = Redirect(HttpUtils.getReferer(req.headers).getOrElse(UserCtrl.index().path()))
      Future.successful(next.flashing("error" -> message))
    }
  }
} 
Example 24
Source File: ErrorHandler.scala    From asura   with MIT License 5 votes vote down vote up
package asura.play.hook

import asura.common.exceptions.ErrorMessages
import asura.common.exceptions.ErrorMessages.ErrorMessageException
import asura.common.model.{ApiCode, ApiRes, ApiResError}
import asura.common.util.{LogUtils, StringUtils}
import asura.play.api.BaseApi.OkApiRes
import javax.inject.{Inject, Singleton}
import org.slf4j.LoggerFactory
import play.api.http.HttpErrorHandler
import play.api.i18n.{Langs, MessagesApi}
import play.api.mvc.{RequestHeader, Result}

import scala.concurrent.Future

@Singleton
class ErrorHandler @Inject()(messagesApi: MessagesApi, langs: Langs) extends HttpErrorHandler with ErrorMessages {

  lazy val logger = LoggerFactory.getLogger(classOf[ErrorHandler])

  override def onClientError(request: RequestHeader, statusCode: Int, message: String): Future[Result] = {
    val msg = s""""${request.method} ${request.uri}" ${statusCode} ${if (StringUtils.isNotEmpty(message)) message else ""}"""
    Future.successful(OkApiRes(ApiResError(msg)))
  }

  override def onServerError(request: RequestHeader, exception: Throwable): Future[Result] = {
    val logStack = LogUtils.stackTraceToString(exception)
    logger.warn(logStack)
    val requestLocal = request.headers.get("Local")
    implicit val lang = if (requestLocal.nonEmpty) {
      langs.availables.find(_.code == requestLocal.get).getOrElse(langs.availables.head)
    } else {
      langs.availables.head
    }
    exception match {
      case errMsgException: ErrorMessageException =>
        val errMsg = messagesApi(errMsgException.error.name, errMsgException.error.errMsg)
        Future.successful(OkApiRes(ApiRes(code = ApiCode.ERROR, msg = errMsg, data = logStack)))
      case _ =>
        val message = if (StringUtils.isNotEmpty(exception.getMessage)) {
          exception.getMessage
        } else {
          messagesApi(error_ServerError.name)
        }
        Future.successful(OkApiRes(ApiRes(code = ApiCode.ERROR, msg = message, data = logStack)))
    }
  }
} 
Example 25
Source File: RestoreController.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.my.settings

import akka.actor.ActorSystem
import com.mohiva.play.silhouette.api.Silhouette
import controllers.{HasUserService, HasConfig, Security }
import controllers.document.{BackupReader, HasBackupValidation}
import java.io.File
import javax.inject.Inject
import services.annotation.AnnotationService
import services.document.DocumentService
import services.user.Roles._
import services.user.UserService
import play.api.{Configuration, Logger}
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc.{AbstractController, ControllerComponents}
import scala.concurrent.{ExecutionContext, Future}
import storage.db.DB
import transform.tiling.TilingService

class RestoreController @Inject() (
  val components: ControllerComponents,
  val config: Configuration,
  val users: UserService,
  val silhouette: Silhouette[Security.Env],
  implicit val annotations: AnnotationService,
  implicit val db: DB,
  implicit val documents: DocumentService,
  implicit val tiling: TilingService,
  implicit val ctx: ExecutionContext,
  implicit val system: ActorSystem
) extends AbstractController(components) 
    with HasUserService 
    with HasConfig
    with I18nSupport
    with BackupReader {
  
  def index() = silhouette.SecuredAction { implicit request =>
    Ok(views.html.my.settings.restore(request.identity))
  }

  def restore() = silhouette.SecuredAction.async { implicit request =>
    request.body.asMultipartFormData.map { tempfile =>
      tempfile.file("backup") match {
       
        case Some(filepart) =>
          // Forces the owner of the backup to the currently logged in user
          restoreBackup(
            filepart.ref.path.toFile,
            runAsAdmin = false,
            forcedOwner = Some(request.identity.username)
          ).map { _ => 
            Redirect(routes.RestoreController.index).flashing("success" -> "The document was restored successfully.") 
          }.recover { 
            
            case e: HasBackupValidation.InvalidSignatureException =>
              Redirect(routes.RestoreController.index).flashing("error" -> "The authenticity of your backup could not be verified.")
              
            case t: Throwable =>
              t.printStackTrace()
              Redirect(routes.RestoreController.index).flashing("error" -> "There was an error restoring your document.") 
          }
          
        case None =>
          Logger.warn("Personal document restore POST without file attached")
          Future.successful(BadRequest)        
      }
    }.getOrElse {
      Logger.warn("Personal document restore POST without form data")
      Future.successful(BadRequest)
    }
  }

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

import akka.stream.Materializer
import config.ConfigDecorator
import controllers.auth.AuthJourney
import com.google.inject.{Inject, Singleton}
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc._
import play.twirl.api.Html
import uk.gov.hmrc.play.bootstrap.http.FrontendErrorHandler
import uk.gov.hmrc.renderer.TemplateRenderer
import javax.inject.Provider
import util.LocalPartialRetriever

@Singleton
class LocalErrorHandler @Inject()(
  val messagesApi: MessagesApi,
  val materializer: Materializer,
  authJourney: Provider[AuthJourney]
)(
  implicit val partialRetriever: LocalPartialRetriever,
  val configDecorator: ConfigDecorator,
  val templateRenderer: TemplateRenderer)
    extends FrontendErrorHandler with I18nSupport with RendersErrors {

  override def standardErrorTemplate(
    pageTitle: String,
    heading: String,
    message: String
  )(implicit request: Request[_]): Html =
    views.html.unauthenticatedError(pageTitle, Some(heading), Some(message))

} 
Example 27
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 28
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 29
Source File: LanguageSwitchController.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers

import config.ConfigDecorator
import com.google.inject.Inject
import play.api.Configuration
import play.api.i18n.{Lang, MessagesApi}
import play.api.mvc.{Action, AnyContent, ControllerComponents, MessagesControllerComponents}
import uk.gov.hmrc.play.language.{LanguageController, LanguageUtils}

class LanguageSwitchController @Inject()(
  configDecorator: ConfigDecorator,
  configuration: Configuration,
  languageUtils: LanguageUtils,
  cc: ControllerComponents)
    extends LanguageController(configuration, languageUtils, cc) {

  def enGb(): Action[AnyContent] = switchToLanguage(language = "english")
  def cyGb(): Action[AnyContent] = switchToLanguage(language = "cymraeg")
  def fallbackURL: String = configDecorator.pertaxFrontendService
  def languageMap: Map[String, Lang] = Map(
    "english" -> Lang("en"),
    "cymraeg" -> Lang("cy")
  )

} 
Example 30
Source File: GetPersonDetailsAction.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import com.google.inject.Inject
import config.ConfigDecorator
import controllers.auth.requests.UserRequest
import models.PersonDetails
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc.Results.Locked
import play.api.mvc.{ActionFunction, ActionRefiner, ControllerComponents, MessagesControllerComponents, Result}
import services.partials.MessageFrontendService
import services.{CitizenDetailsService, PersonDetailsHiddenResponse, PersonDetailsSuccessResponse}
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.play.HeaderCarrierConverter
import uk.gov.hmrc.renderer.TemplateRenderer
import util.LocalPartialRetriever

import scala.concurrent.{ExecutionContext, Future}

class GetPersonDetailsAction @Inject()(
  citizenDetailsService: CitizenDetailsService,
  messageFrontendService: MessageFrontendService,
  cc: ControllerComponents,
  val messagesApi: MessagesApi)(
  implicit configDecorator: ConfigDecorator,
  partialRetriever: LocalPartialRetriever,
  ec: ExecutionContext,
  templateRenderer: TemplateRenderer)
    extends ActionRefiner[UserRequest, UserRequest] with ActionFunction[UserRequest, UserRequest] with I18nSupport {

  override protected def refine[A](request: UserRequest[A]): Future[Either[Result, UserRequest[A]]] =
    populatingUnreadMessageCount()(request).flatMap { messageCount =>
      if (!request.uri.contains("/signout")) {
        getPersonDetails()(request).map { a =>
          a.fold(
            Left(_),
            pd =>
              Right(
                UserRequest(
                  request.nino,
                  request.retrievedName,
                  request.saUserType,
                  request.credentials,
                  request.confidenceLevel,
                  pd,
                  request.trustedHelper,
                  request.profile,
                  messageCount,
                  request.activeTab,
                  request.breadcrumb,
                  request.request
                )
            )
          )
        }
      } else {
        Future.successful(
          Right(
            UserRequest(
              request.nino,
              request.retrievedName,
              request.saUserType,
              request.credentials,
              request.confidenceLevel,
              None,
              request.trustedHelper,
              request.profile,
              messageCount,
              request.activeTab,
              request.breadcrumb,
              request.request
            )
          )
        )
      }
    }

  def populatingUnreadMessageCount()(implicit request: UserRequest[_]): Future[Option[Int]] =
    messageFrontendService.getUnreadMessageCount

  private def getPersonDetails()(implicit request: UserRequest[_]): Future[Either[Result, Option[PersonDetails]]] = {

    implicit val hc: HeaderCarrier =
      HeaderCarrierConverter.fromHeadersAndSession(request.headers, Some(request.session))

    request.nino match {
      case Some(nino) =>
        citizenDetailsService.personDetails(nino).map {
          case PersonDetailsSuccessResponse(pd) => Right(Some(pd))
          case PersonDetailsHiddenResponse =>
            Left(Locked(views.html.manualCorrespondence()))
          case _ => Right(None)
        }
      case _ => Future.successful(Right(None))
    }
  }

  override protected def executionContext: ExecutionContext = cc.executionContext
} 
Example 31
Source File: UserResearchDismissalController.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers

import config.ConfigDecorator
import controllers.auth.AuthJourney
import controllers.controllershelpers.HomePageCachingHelper
import error.LocalErrorHandler
import com.google.inject.Inject
import play.api.i18n.MessagesApi
import play.api.mvc.{Action, AnyContent, MessagesControllerComponents}
import services._
import services.partials.MessageFrontendService
import uk.gov.hmrc.auth.core.AuthConnector
import uk.gov.hmrc.play.audit.http.connector.AuditConnector
import util.LocalPartialRetriever

import scala.concurrent.ExecutionContext

class UserResearchDismissalController @Inject()(
  val citizenDetailsService: CitizenDetailsService,
  val messageFrontendService: MessageFrontendService,
  val localErrorHandler: LocalErrorHandler,
  val homePageCachingHelper: HomePageCachingHelper,
  authJourney: AuthJourney,
  auditConnector: AuditConnector,
  authConnector: AuthConnector,
  cc: MessagesControllerComponents)(
  implicit partialRetriever: LocalPartialRetriever,
  configDecorator: ConfigDecorator,
  ec: ExecutionContext)
    extends PertaxBaseController(cc) {

  def dismissUrBanner: Action[AnyContent] = authJourney.authWithPersonalDetails { implicit request =>
    homePageCachingHelper.storeUserUrDismissal()
    NoContent
  }
} 
Example 32
Source File: PublicController.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers

import config.ConfigDecorator
import com.google.inject.Inject
import play.api.i18n.MessagesApi
import play.api.mvc.{Action, AnyContent, MessagesControllerComponents}
import uk.gov.hmrc.http.SessionKeys
import uk.gov.hmrc.play.binders.Origin
import uk.gov.hmrc.renderer.TemplateRenderer
import util.LocalPartialRetriever

import scala.concurrent.{ExecutionContext, Future}

class PublicController @Inject()(cc: MessagesControllerComponents)(
  implicit partialRetriever: LocalPartialRetriever,
  configDecorator: ConfigDecorator,
  templateRenderer: TemplateRenderer,
  ec: ExecutionContext)
    extends PertaxBaseController(cc) {

  def verifyEntryPoint: Action[AnyContent] = Action.async { implicit request =>
    Future.successful {
      Redirect(routes.HomeController.index).withNewSession.addingToSession(
        SessionKeys.authProvider -> configDecorator.authProviderVerify
      )
    }
  }

  def governmentGatewayEntryPoint: Action[AnyContent] = Action.async { implicit request =>
    Future.successful {
      Redirect(routes.HomeController.index).withNewSession.addingToSession(
        SessionKeys.authProvider -> configDecorator.authProviderGG
      )
    }
  }

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

  def redirectToExitSurvey(origin: Origin): Action[AnyContent] = Action.async { implicit request =>
    Future.successful {
      Redirect(configDecorator.getFeedbackSurveyUrl(origin))
    }
  }

  def redirectToTaxCreditsService(): Action[AnyContent] = Action.async { implicit request =>
    Future.successful {
      Redirect(configDecorator.tcsServiceRouterUrl, MOVED_PERMANENTLY)
    }
  }

  def redirectToPersonalDetails(): Action[AnyContent] = Action.async { implicit request =>
    Future.successful {
      Redirect(controllers.address.routes.PersonalDetailsController.onPageLoad())
    }
  }
} 
Example 33
Source File: UpdateAddressResponseSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import config.ConfigDecorator
import models.NonFilerSelfAssessmentUser
import org.scalatestplus.mockito.MockitoSugar
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc.Result
import play.api.mvc.Results.Ok
import play.api.test.FakeRequest
import play.api.test.Helpers._
import uk.gov.hmrc.auth.core.ConfidenceLevel
import uk.gov.hmrc.auth.core.retrieve.Credentials
import uk.gov.hmrc.http.HttpResponse
import util.UserRequestFixture.buildUserRequest
import util.BaseSpec

class UpdateAddressResponseSpec extends BaseSpec with I18nSupport with MockitoSugar {

  implicit val configDecorator: ConfigDecorator = injected[ConfigDecorator]

  override def messagesApi: MessagesApi = injected[MessagesApi]

  implicit val userRequest = buildUserRequest(
    saUser = NonFilerSelfAssessmentUser,
    credentials = Credentials("", "Verify"),
    confidenceLevel = ConfidenceLevel.L500,
    request = FakeRequest()
  )

  def genericFunc(): Result =
    Ok

  "UpdateAddressResponse.response" should {
    "return the block result for UpdateAddressSuccessResponse" in {
      val result = UpdateAddressSuccessResponse.response(genericFunc)
      status(result) shouldBe OK
    }

    "return BAD_REQUEST for UpdateAddressBadRequestResponse" in {
      val result = UpdateAddressBadRequestResponse.response(genericFunc)
      status(result) shouldBe BAD_REQUEST
    }

    "return INTERNAL_SERVER_ERROR for UpdateAddressUnexpectedResponse" in {
      val updateAddressResponse = UpdateAddressUnexpectedResponse(HttpResponse(123))
      val result = updateAddressResponse.response(genericFunc)
      status(result) shouldBe INTERNAL_SERVER_ERROR
    }

    "return INTERNAL_SERVER_ERROR for UpdateAddressErrorResponse" in {
      val updateAddressResponse = UpdateAddressErrorResponse(new RuntimeException("not used"))
      val result = updateAddressResponse.response(genericFunc)
      status(result) shouldBe INTERNAL_SERVER_ERROR
    }
  }
} 
Example 34
Source File: SaWrongCredentialsControllerSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers

import controllers.auth.FakeAuthJourney
import models.WrongCredentialsSelfAssessmentUser
import org.scalatestplus.mockito.MockitoSugar
import play.api.i18n.MessagesApi
import play.api.mvc.MessagesControllerComponents
import play.api.test.FakeRequest
import play.api.test.Helpers._
import uk.gov.hmrc.domain.{SaUtr, SaUtrGenerator}
import uk.gov.hmrc.renderer.TemplateRenderer
import util.{BaseSpec, LocalPartialRetriever}
import views.html.selfassessment.{DoYouKnowOtherCredentialsView, DoYouKnowUserIdView, FindYourUserIdView, NeedToResetPasswordView, SignInAgainView, SignedInWrongAccountView}

import scala.concurrent.ExecutionContext

class SaWrongCredentialsControllerSpec extends BaseSpec with MockitoSugar {

  val fakeAuthJourney = new FakeAuthJourney(
    WrongCredentialsSelfAssessmentUser(SaUtr(new SaUtrGenerator().nextSaUtr.utr)))

  def controller =
    new SaWrongCredentialsController(
      fakeAuthJourney,
      injected[MessagesControllerComponents],
      injected[SignedInWrongAccountView],
      injected[DoYouKnowOtherCredentialsView],
      injected[SignInAgainView],
      injected[DoYouKnowUserIdView],
      injected[NeedToResetPasswordView],
      injected[FindYourUserIdView]
    )(injected[LocalPartialRetriever], config, injected[TemplateRenderer], injected[ExecutionContext])

  "processDoYouKnowOtherCredentials" should {
    "redirect to 'Sign in using Government Gateway' page when supplied with value Yes" in {
      val request = FakeRequest("POST", "").withFormUrlEncodedBody("wrongCredentialsFormChoice" -> "true")

      val result = controller.processDoYouKnowOtherCredentials(request)
      status(result) shouldBe SEE_OTHER
      redirectLocation(await(result)) shouldBe Some(routes.SaWrongCredentialsController.signInAgain().url)
    }

    "redirect to 'You need to use the creds you've created' page when supplied with value No (false)" in {
      val request = FakeRequest("POST", "").withFormUrlEncodedBody("wrongCredentialsFormChoice" -> "false")

      val result = controller.processDoYouKnowOtherCredentials(request)

      status(result) shouldBe SEE_OTHER
      redirectLocation(await(result)) shouldBe Some(routes.SaWrongCredentialsController.doYouKnowUserId().url)
    }

    "return a bad request when supplied no value" in {
      val request = FakeRequest("POST", "")

      val result = controller.processDoYouKnowOtherCredentials(request)
      status(result) shouldBe BAD_REQUEST
    }
  }

  "processDoYouKnowUserId" should {
    "redirect to 'Sign in using Government Gateway' page when supplied with value Yes" in {
      val request = FakeRequest("POST", "").withFormUrlEncodedBody("wrongCredentialsFormChoice" -> "true")

      val result = controller.processDoYouKnowUserId(request)
      status(result) shouldBe SEE_OTHER
      redirectLocation(await(result)) shouldBe Some(routes.SaWrongCredentialsController.needToResetPassword().url)
    }

    "redirect to 'You need to use the creds you've created' page when supplied with value No (false)" in {
      val request = FakeRequest("POST", "").withFormUrlEncodedBody("wrongCredentialsFormChoice" -> "false")
      val result = controller.processDoYouKnowUserId(request)

      status(result) shouldBe SEE_OTHER
      redirectLocation(await(result)) shouldBe Some(routes.SaWrongCredentialsController.findYourUserId().url)
    }

    "return a bad request when supplied no value" in {
      val request = FakeRequest("POST", "")
      val result = controller.processDoYouKnowUserId(request)
      status(result) shouldBe BAD_REQUEST
    }
  }

  "ggSignInUrl" should {
    "be the gg-sign in url" in {
      controller.ggSignInUrl shouldBe "/gg/sign-in?continue=/personal-account&accountType=individual&origin=PERTAX"
    }
  }
} 
Example 35
Source File: PaymentsControllerSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers

import config.ConfigDecorator
import connectors._
import controllers.auth.requests.UserRequest
import controllers.auth.{AuthJourney, WithBreadcrumbAction}
import models.CreatePayment
import org.joda.time.DateTime
import org.mockito.Matchers.any
import org.mockito.Mockito.when
import org.scalatestplus.mockito.MockitoSugar
import play.api.Application
import play.api.i18n.MessagesApi
import play.api.inject.bind
import play.api.mvc.{ActionBuilder, MessagesControllerComponents, Request, Result}
import play.api.test.FakeRequest
import play.api.test.Helpers.{redirectLocation, _}
import uk.gov.hmrc.renderer.TemplateRenderer
import uk.gov.hmrc.time.CurrentTaxYear
import util.UserRequestFixture.buildUserRequest
import util.{ActionBuilderFixture, BaseSpec}

import scala.concurrent.{ExecutionContext, Future}

class PaymentsControllerSpec extends BaseSpec with CurrentTaxYear with MockitoSugar {

  override def now: () => DateTime = DateTime.now

  lazy val fakeRequest = FakeRequest("", "")

  val mockPayConnector = mock[PayApiConnector]
  val mockAuthJourney = mock[AuthJourney]

  override implicit lazy val app: Application = localGuiceApplicationBuilder()
    .overrides(
      bind[PayApiConnector].toInstance(mockPayConnector),
      bind[AuthJourney].toInstance(mockAuthJourney)
    )
    .build()

  def controller =
    new PaymentsController(
      mockPayConnector,
      mockAuthJourney,
      injected[WithBreadcrumbAction],
      injected[MessagesControllerComponents]
    )(mockLocalPartialRetriever, injected[ConfigDecorator], mock[TemplateRenderer], injected[ExecutionContext])

  when(mockAuthJourney.authWithPersonalDetails).thenReturn(new ActionBuilderFixture {
    override def invokeBlock[A](request: Request[A], block: UserRequest[A] => Future[Result]): Future[Result] =
      block(
        buildUserRequest(
          request = request
        ))
  })

  "makePayment" should {
    "redirect to the response's nextUrl" in {

      val expectedNextUrl = "someNextUrl"
      val createPaymentResponse = CreatePayment("someJourneyId", expectedNextUrl)

      when(mockPayConnector.createPayment(any())(any(), any()))
        .thenReturn(Future.successful(Some(createPaymentResponse)))

      val result = controller.makePayment()(FakeRequest())
      status(result) shouldBe SEE_OTHER
      redirectLocation(result) shouldBe Some("someNextUrl")
    }

    "redirect to a BAD_REQUEST page if createPayment failed" in {

      when(mockPayConnector.createPayment(any())(any(), any()))
        .thenReturn(Future.successful(None))

      val result = controller.makePayment()(FakeRequest())
      status(result) shouldBe BAD_REQUEST
    }
  }
} 
Example 36
Source File: PaperlessPreferencesControllerSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers

import config.ConfigDecorator
import controllers.auth.requests.UserRequest
import controllers.auth.{AuthJourney, WithActiveTabAction, WithBreadcrumbAction}
import models.{ActivatedOnlineFilerSelfAssessmentUser, NonFilerSelfAssessmentUser}
import org.mockito.Matchers._
import org.mockito.Mockito._
import org.scalatestplus.mockito.MockitoSugar
import play.api.i18n.MessagesApi
import play.api.mvc.{ActionBuilder, MessagesControllerComponents, Request, Result}
import play.api.test.FakeRequest
import play.api.test.Helpers._
import play.twirl.api.Html
import services.partials.PreferencesFrontendPartialService
import uk.gov.hmrc.auth.core.ConfidenceLevel
import uk.gov.hmrc.auth.core.retrieve.Credentials
import uk.gov.hmrc.domain.SaUtr
import uk.gov.hmrc.play.partials.HtmlPartial
import uk.gov.hmrc.renderer.TemplateRenderer
import util.UserRequestFixture.buildUserRequest
import util.{ActionBuilderFixture, BaseSpec, BetterOptionValues, LocalPartialRetriever, Tools}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{ExecutionContext, Future}

class PaperlessPreferencesControllerSpec extends BaseSpec with MockitoSugar {
  import BetterOptionValues._

  override implicit lazy val app = localGuiceApplicationBuilder().build()

  val mockPreferencesFrontendPartialService = mock[PreferencesFrontendPartialService]
  val mockAuthJourney = mock[AuthJourney]

  def controller: PaperlessPreferencesController =
    new PaperlessPreferencesController(
      mockPreferencesFrontendPartialService,
      mockAuthJourney,
      injected[WithActiveTabAction],
      injected[WithBreadcrumbAction],
      injected[MessagesControllerComponents],
      injected[Tools]
    )(mock[LocalPartialRetriever], injected[ConfigDecorator], injected[TemplateRenderer], injected[ExecutionContext]) {}

  "Calling PaperlessPreferencesController.managePreferences" should {
    "Redirect to  preferences-frontend manage paperless url when a user is logged in using GG" in {

      when(mockAuthJourney.authWithPersonalDetails).thenReturn(new ActionBuilderFixture {
        override def invokeBlock[A](request: Request[A], block: UserRequest[A] => Future[Result]): Future[Result] =
          block(
            buildUserRequest(request = request)
          )
      })

      val r = controller.managePreferences(FakeRequest())
      status(r) shouldBe SEE_OTHER

      val redirectUrl = redirectLocation(r).getValue
      val configDecorator = app.injector.instanceOf[ConfigDecorator]
      redirectUrl should include regex s"${configDecorator.preferencesFrontendService}/paperless/check-settings\\?returnUrl=.*\\&returnLinkText=.*"
    }

    "Return 400 for Verify users" in {

      when(mockAuthJourney.authWithPersonalDetails).thenReturn(new ActionBuilderFixture {
        override def invokeBlock[A](request: Request[A], block: UserRequest[A] => Future[Result]): Future[Result] =
          block(
            buildUserRequest(
              credentials = Credentials("", "Verify"),
              confidenceLevel = ConfidenceLevel.L500,
              request = request
            ))
      })

      val r = controller.managePreferences(FakeRequest())
      status(r) shouldBe BAD_REQUEST
    }
  }
} 
Example 37
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 38
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 39
Source File: LaboratoryController.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers.api

import com.fasterxml.jackson.annotation.JsonValue
import com.google.inject.Inject
import dao.{LaboratoryDAO, UserDAO}
import jp.t2v.lab.play2.auth.OptionalAuthElement
import model._
import model.json.LoginJson
import play.Logger
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.libs.json.{JsValue, Json, Writes}
import play.api.mvc.{Action, AnyContent, Controller}
import services.LaboratoryService
import views.html._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{ExecutionContext, Future}


class LaboratoryController @Inject()(userDAO: UserDAO, laboratoryService: LaboratoryService, val messagesApi: MessagesApi) extends Controller with I18nSupport {



  //override def resolveUser(id: LoginFormData)(implicit context: ExecutionContext): Future[Option[User]] = userDAO.get(id)

  def convertToJson(laboratoryObject: Laboratory, roomsWithComputers: Map[Room, Seq[(Computer, Option[(ComputerState, Seq[ConnectedUser])])]]): JsValue = {
    val roomsConverted = roomsWithComputers.toSeq
    val grouped = roomsConverted.groupBy(_._1)
    val resultRooms = grouped.map(filtered=>(filtered._1,filtered._2.map(_._2).head)).toSeq
    Json.toJson((laboratoryObject,resultRooms))
  }

  def get(id: Long) = Action.async { implicit request =>
    Logger.debug("PeticiĆ³n de listar el laboratory " + id + " [API] respondida.")
    implicit val username = Some("")
    laboratoryService.get(id).map {
      case Some((laboratoryObject, roomsWithComputers)) => Ok(convertToJson(laboratoryObject, roomsWithComputers))
      case _ => NotFound(Json.parse(
        """
          |{
          |  "answer"->"no encontrado"
          |}
        """))
    }
  }


} 
Example 40
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 41
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 42
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 43
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 44
Source File: CustomLanguageController.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.controllers

import javax.inject.Inject
import play.api.{Application, Configuration}
import play.api.i18n.{Lang, MessagesApi}
import play.api.mvc.Call
import uk.gov.hmrc.play.language.{LanguageController, LanguageUtils}

class CustomLanguageController @Inject()(implicit override val messagesApi: MessagesApi,
                                         application: Application,
                                         languageUtils: LanguageUtils,
                                         configuration: Configuration
                                        ) extends LanguageController(configuration, languageUtils) {

  def routeToSwitchLanguage = (lang: String) => routes.CustomLanguageController.switchToLanguage(lang)

  
  override def languageMap: Map[String, Lang] = Map(
    "english" -> Lang("en"),
    "cymraeg" -> Lang("cy")
  )
} 
Example 45
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 46
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 47
Source File: entity_manager.yaml.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
import play.api.mvc.{Action,Controller}

import play.api.data.validation.Constraint

import play.api.i18n.MessagesApi

import play.api.inject.{ApplicationLifecycle,ConfigurationProvider}

import de.zalando.play.controllers._

import PlayBodyParsing._

import PlayValidations._

import scala.util._

import javax.inject._

import de.zalando.play.controllers.PlayBodyParsing._
import org.apache.tinkerpop.gremlin.structure.{T,Vertex}
import org.janusgraph.core.attribute.Geoshape
import org.janusgraph.core.schema.JanusGraphManagement
import org.janusgraph.core.{JanusGraphFactory,PropertyKey}
import org.janusgraph.diskstorage.configuration.backend.CommonsConfiguration
import scala.concurrent.Future
import org.janusgraph.core.Cardinality
import collection.convert.decorateAsScala._
import collection.convert.decorateAsScala._
import collection.convert.decorateAsScala._
import collection.convert.decorateAsScala._
import collection.convert.decorateAsScala._
import collection.convert.decorateAsScala._


    lifecycle.addStopHook { () =>
      Future.successful({
        graph.close()
      })
    }

        // ----- End of unmanaged code area for constructor Entity_managerYaml
        val getEntities = getEntitiesAction { input: (EntitiesGetPageNumber, EntitiesGetPageNumber) =>
            val (pageSize, pageNumber) = input
            // ----- Start of unmanaged code area for action  Entity_managerYaml.getEntities
            NotImplementedYet
            // ----- End of unmanaged code area for action  Entity_managerYaml.getEntities
        }
        val createEntity = createEntityAction { (entity: Entity) =>  
            // ----- Start of unmanaged code area for action  Entity_managerYaml.createEntity
            val tx = graph.newTransaction
      val vertex = tx.addVertex(T.label, "entity", "entityName", entity.entityname)
      val id = vertex.id().asInstanceOf[Long]
      tx.commit()
      CreateEntity200(EntityId(id))
            // ----- End of unmanaged code area for action  Entity_managerYaml.createEntity
        }
        val getEntity = getEntityAction { (entityname: String) =>  
            // ----- Start of unmanaged code area for action  Entity_managerYaml.getEntity
            import collection.convert.decorateAsScala._
      val vertices = graph.traversal.V().has("entityName", entityname).asScala
      if (vertices.isEmpty)
        GetEntity404()
      else {
        val vertex = vertices.next()
        GetEntity200(Entity(vertex.property[String]("entityName").value()))
      }
            // ----- End of unmanaged code area for action  Entity_managerYaml.getEntity
        }
    
    }
} 
Example 48
Source File: RoomController.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers.admin

import com.google.inject.Inject
import controllers.{routes => normalroutes}
import model.Room
import model.json.ResultMessage
import play.Logger
import play.api.Environment
import play.api.i18n.MessagesApi
import play.api.libs.json.{JsError, JsSuccess, Json}
import services.{LaboratoryService, RoomService, UserService, state}

import scala.concurrent.{ExecutionContext, Future}


class RoomController @Inject()(roomService: RoomService, laboratoryService: LaboratoryService, val messagesApi: MessagesApi)(implicit userService: UserService, executionContext: ExecutionContext, environment: Environment) extends ControllerWithAuthRequired {

  def add = AuthRequiredAction { implicit request =>
    implicit val username = Some(loggedIn.username)
    Logger.debug("Adding room... ")
    request.body.asJson match {
      case Some(json) => json.validate[Room] match {
        case JsSuccess(room, _) => roomService.add(room).map {
          case state.ActionCompleted => Ok(Json.toJson(new ResultMessage("Room added")))
          case _ => BadRequest(Json.toJson(new ResultMessage("Could not add that room")))
        }
        case JsError(errors) => Future.successful(BadRequest(Json.toJson(ResultMessage.wrongJsonFormat(errors))))
      }
      case _ => Future.successful(BadRequest(Json.toJson(ResultMessage.inputWasNotAJson)))
    }
  }

  def update = AuthRequiredAction { implicit request =>
    implicit val username = Some(loggedIn.username)
    Logger.debug("Updating room... ")
    request.body.asJson match {
      case Some(json) => json.validate[Room] match {
        case JsSuccess(room, _) => roomService.update(room).map {
          case state.ActionCompleted => Ok(Json.toJson(new ResultMessage("Room updated")))
          case state.NotFound => NotFound(Json.toJson( ResultMessage("Room not found", Seq(("id", room.id.toString)))))
          case _ => BadRequest(Json.toJson(new ResultMessage("Could not update that room")))
        }
        case JsError(errors) => Future.successful(BadRequest(Json.toJson(ResultMessage.wrongJsonFormat(errors))))
      }
      case _ => Future.successful(BadRequest(Json.toJson(ResultMessage.inputWasNotAJson)))
    }
  }

  def delete(roomId: Long) = AuthRequiredAction { implicit request =>
    roomService.delete(roomId).map {
      case state.ActionCompleted => Redirect(normalroutes.HomeController.home())
      case state.NotFound => NotFound
      case _ => BadRequest
    }
  }

  def blockUser(roomId: Long) = AuthRequiredAction { implicit request =>
    // TODO: Processing Not Yet Implemented
    val results = for {
      roomResult <- roomService.get(roomId)
    } yield roomResult
    results.map { result: Option[Room] =>
      if (result.isDefined)
        Redirect(normalroutes.LaboratoryController.get(result.get.laboratoryID))
      else
        NotFound
    }
  }
} 
Example 49
Source File: SSHOrderController.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers.admin

import com.google.inject.Inject
import controllers.{routes => normalroutes}
import dao.{SSHOrderDAO, UserDAO}
import play.api.Environment
import play.api.i18n.MessagesApi
import services.{SSHOrderService, UserService, state}
import views.html._

import scala.concurrent.ExecutionContext


class SSHOrderController @Inject()(sSHOrderService: SSHOrderService, val messagesApi: MessagesApi)(implicit executionContext: ExecutionContext, userService: UserService, environment: Environment) extends ControllerWithAuthRequired {

  def listAll = AuthRequiredAction { implicit request =>
    implicit val username = Some(loggedIn.username)
    sSHOrderService.listAll.map {res=>
      Ok//(index(messagesApi("sshorders"),sshOrders(res.take(20))))
    }
  }

  def get(id: Long) = AuthRequiredAction { implicit request =>
    implicit val username = Some(loggedIn.username)
    sSHOrderService.get(id).map {res=>
      Ok//(index(messagesApi("sshorder"),sshOrder(res)))
    }
  }

  def delete(id: Long) = AuthRequiredAction { implicit request =>
    implicit val username = Some(loggedIn.username)
    sSHOrderService.delete(id).map {
      case state.ActionCompleted => Ok("OK")
      case _ => BadRequest
    }
  }
} 
Example 50
Source File: LaboratoryController.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers.admin

import com.google.inject.Inject
import controllers.{routes => normalroutes}
import model.json.{LaboratoryJson, ResultMessage}
import model.{Laboratory, Role}
import play.Logger
import play.api.Environment
import play.api.i18n.MessagesApi
import play.api.libs.json.{JsError, JsSuccess, Json}
import services.{LaboratoryService, UserService, state}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{ExecutionContext, Future}


class LaboratoryController @Inject()(laboratoryService: LaboratoryService, val messagesApi: MessagesApi)(implicit userService: UserService, executionContext: ExecutionContext, environment: Environment) extends ControllerWithAuthRequired {

  def update = AuthRequiredAction { implicit request =>
    implicit val username = Some(loggedIn.username)
    implicit val isAdmin = loggedIn.role == Role.Administrator
    // TODO: Get id from json
    request.body.asJson match {
      case Some(json) => json.validate[Laboratory] match {
        case JsSuccess(laboratory, _) =>
          laboratoryService.update(laboratory).map {
            case state.ActionCompleted => Ok(Json.toJson(new ResultMessage("Laboratory updated")))
            case state.NotFound => NotFound(Json.toJson(ResultMessage("Laboratory not found",Seq(("id", laboratory.id.toString)))))
            case _ => BadRequest(Json.toJson(new ResultMessage("Could not add that laboratory")))
          }
        case JsError(errors) =>Future.successful(BadRequest(Json.toJson(ResultMessage.wrongJsonFormat(errors))))
      }
      case _ => Future.successful(BadRequest(Json.toJson(ResultMessage.inputWasNotAJson)))
    }
  }

  def add = AuthRequiredAction { implicit request =>
    Logger.debug("Adding laboratory... ")
    implicit val username = Some(loggedIn.username)
    implicit val isAdmin = loggedIn.role == Role.Administrator
    request.body.asJson match {
      case Some(json) => json.validate[LaboratoryJson] match {
        case JsSuccess(laboratory, _) =>
          val newLaboratory = Laboratory(0, laboratory.name, laboratory.location, laboratory.administration)
          laboratoryService.add(newLaboratory).map {
            case state.ActionCompleted => Ok(Json.toJson(new ResultMessage("Laboratory added")))
            case _ => BadRequest(Json.toJson(new ResultMessage("Could not add that laboratory")))

          }
        case JsError(errors) =>Future.successful(BadRequest(Json.toJson(ResultMessage.wrongJsonFormat(errors))))
      }
      case _ => Future.successful(BadRequest(Json.toJson(ResultMessage.inputWasNotAJson)))
    }
  }

  def delete(id: Long) = AuthRequiredAction { implicit request =>
    laboratoryService.delete(id) map {
      case state.ActionCompleted => Ok(Json.toJson(new ResultMessage("Laboratory deleted successfully")))
      case state.NotFound => NotFound(Json.toJson(new ResultMessage("Laboratory not found")))
      case _ => BadRequest(Json.toJson(new ResultMessage("A server problem occurred while trying to delete the laboratory")))
    }
  }
}