play.api.i18n.I18nSupport Scala Examples

The following examples show how to use play.api.i18n.I18nSupport. 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: 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 3
Source File: SocialAuthController.scala    From scalafiddle-editor   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.impl.providers._
import kamon.Kamon
import play.api.i18n.I18nSupport
import play.api.mvc.InjectedController

import scala.concurrent.{ExecutionContext, Future}
import scalafiddle.server.models.services.UserService
import scalafiddle.server.utils.auth.DefaultEnv


  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)
              authenticator <- silhouette.env.authenticatorService.create(profile.loginInfo)
              value         <- silhouette.env.authenticatorService.init(authenticator)
              result        <- silhouette.env.authenticatorService.embed(value, Redirect(routes.Application.index("", "0")))
            } yield {
              loginCount.increment()
              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.Application.index("", "0"))
    }
  }
} 
Example 4
Source File: AbstractAuthController.scala    From silhouette-vuejs-app   with Apache License 2.0 5 votes vote down vote up
package controllers

import com.mohiva.play.silhouette.api.Authenticator.Implicits._
import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.services.AuthenticatorResult
import com.mohiva.play.silhouette.api.util.Clock
import models.User
import net.ceedubs.ficus.Ficus._
import play.api.Configuration
import play.api.i18n.I18nSupport
import play.api.libs.json.Json
import play.api.mvc._
import utils.auth.DefaultEnv

import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}


  protected def authenticateUser(user: User, loginInfo: LoginInfo, rememberMe: Boolean)(implicit request: Request[_]): Future[AuthenticatorResult] = {
    val c = configuration.underlying
    silhouette.env.authenticatorService.create(loginInfo).map {
      case authenticator if rememberMe =>
        authenticator.copy(
          expirationDateTime = clock.now + c.as[FiniteDuration]("silhouette.authenticator.rememberMe.authenticatorExpiry"),
          idleTimeout = c.getAs[FiniteDuration]("silhouette.authenticator.rememberMe.authenticatorIdleTimeout")
        )
      case authenticator => authenticator
    }.flatMap { authenticator =>
      silhouette.env.eventBus.publish(LoginEvent(user, request))
      silhouette.env.authenticatorService.init(authenticator).flatMap { token =>
        silhouette.env.authenticatorService.embed(token, Ok(Json.obj(
          "id" -> user.userID,
          "token" -> token,
          "firstName" -> user.firstName,
          "lastName" -> user.lastName,
          "role" -> user.role,
          "email" -> user.email
        )))
      }
    }
  }
} 
Example 5
Source File: ChangePasswordController.scala    From silhouette-vuejs-app   with Apache License 2.0 5 votes vote down vote up
package controllers

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

import scala.concurrent.{ExecutionContext, Future}


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

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.util.Clock
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import forms.SignInForm
import javax.inject.Inject
import models.services._
import play.api.Configuration
import play.api.i18n.I18nSupport
import play.api.libs.json.Json
import play.api.mvc.{AnyContent, Request}
import utils.auth.DefaultEnv

import scala.concurrent.{ExecutionContext, Future}


  def submit = silhouette.UnsecuredAction.async { implicit request: Request[AnyContent] =>
    SignInForm.form.bindFromRequest.fold(
      _ => Future.successful(BadRequest),
      data => {
        authenticateService.credentials(data.email, data.password).flatMap {
          case Success(user) =>
            val loginInfo = LoginInfo(CredentialsProvider.ID, user.email.get)
            authenticateUser(user, loginInfo, data.rememberMe)
          case InvalidPassword(attemptsAllowed) =>
            Future.successful(Forbidden(Json.obj("errorCode" -> "InvalidPassword", "attemptsAllowed" -> attemptsAllowed)))
          case NonActivatedUserEmail =>
            Future.successful(Forbidden(Json.obj("errorCode" -> "NonActivatedUserEmail")))
          case UserNotFound =>
            Future.successful(Forbidden(Json.obj("errorCode" -> "UserNotFound")))
          case ToManyAuthenticateRequests(nextAllowedAttemptTime) =>
            Future.successful(TooManyRequests(Json.obj("errorCode" -> "TooManyRequests", "nextAllowedAttemptTime" -> nextAllowedAttemptTime)))
        }
        .recover {
          case e =>
            logger.error(s"Sign in error email = ${data.email}", e)
            InternalServerError(Json.obj("errorCode" -> "SystemError"))
        }
      }
    )
  }
} 
Example 7
Source File: SignUpController.scala    From silhouette-vuejs-app   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 forms.SignUpForm
import models.services._
import play.api.i18n.I18nSupport
import play.api.mvc.{AbstractController, AnyContent, ControllerComponents, Request}
import utils.auth.DefaultEnv

import scala.concurrent.{ExecutionContext, Future}


  def submit = silhouette.UnsecuredAction.async { implicit request: Request[AnyContent] =>
    SignUpForm.form.bindFromRequest.fold(
      _ => Future.successful(BadRequest),
      data => {
        val activationUrlProvider: UUID => String = authTokenId => routes.ActivateAccountController.activate(authTokenId).absoluteURL()

        signUpService.signUpByCredentials(data, request.remoteAddress, activationUrlProvider).map {
          case UserCreated(user) =>
            silhouette.env.eventBus.publish(SignUpEvent(user, request))
            Ok
          case UserAlreadyExists =>
            Conflict
          case InvalidRecaptchaCode =>
            BadRequest("Captcha code is not correct")
        }
      }
    )
  }
} 
Example 8
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 9
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 10
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 11
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 12
Source File: BaseController.scala    From play-silhouette-postgres-async-seed   with Apache License 2.0 5 votes vote down vote up
package controllers

import java.util.UUID

import org.joda.time.LocalDateTime
import play.api.i18n.I18nSupport
import services.user.AuthenticationEnvironment
import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.impl.authenticators.CookieAuthenticator
import models.user.{ Role, User }
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.mvc.{ AnyContent, Result }

import scala.concurrent.Future

abstract class BaseController() extends Silhouette[User, CookieAuthenticator] with I18nSupport {
  def env: AuthenticationEnvironment

  def withAdminSession(block: (SecuredRequest[AnyContent]) => Future[Result]) = SecuredAction.async { implicit request =>
    if (request.identity.roles.contains(Role.Admin)) {
      block(request)
    } else {
      Future.successful(NotFound("404 Not Found"))
    }
  }

  def withSession(block: (SecuredRequest[AnyContent]) => Future[Result]) = UserAwareAction.async { implicit request =>
    val response = request.identity match {
      case Some(user) =>
        val secured = SecuredRequest(user, request.authenticator.getOrElse(throw new IllegalStateException()), request)
        block(secured).map { r =>
          r
        }
      case None =>
        val user = User(
          id = UUID.randomUUID(),
          username = None,
          profiles = Nil,
          created = new LocalDateTime()
        )

        for {
          user <- env.userService.save(user)
          authenticator <- env.authenticatorService.create(LoginInfo("anonymous", user.id.toString))
          value <- env.authenticatorService.init(authenticator)
          result <- block(SecuredRequest(user, authenticator, request))
          authedResponse <- env.authenticatorService.embed(value, result)
        } yield {
          env.eventBus.publish(SignUpEvent(user, request, request2Messages))
          env.eventBus.publish(LoginEvent(user, request, request2Messages))
          authedResponse
        }
    }
    response
  }
} 
Example 13
Source File: Application.scala    From bay-scalajs.g8   with Apache License 2.0 5 votes vote down vote up
package controllers

import cats.implicits._
import com.google.inject.Inject
import jp.t2v.lab.play2.auth.LoginLogout
import jp.t2v.lab.play2.auth.OptionalAuthElement
import models.forms.LoginForm
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.I18nSupport
import play.api.mvc._
import services._
import shared.models.WiredApiModel.UnauthorizedApi
import shared.services.WiredApi
import upickle.default._

import scala.concurrent.ExecutionContext

class Application @Inject()(val services: Services)(implicit val ec: ExecutionContext)
    extends ExtendedController
    with AuthConfigImpl
    with OptionalAuthElement
    with LoginLogout
    with I18nSupport {

  def index(path: String) = StackAction { implicit request =>
    loggedIn match {
      case Some(_) =>
        Ok(views.html.index())
      case None =>
        Ok(views.html.login(loginForm.fill(LoginForm("[email protected]", "testpw"))))
    }
  }

  val loginForm = Form(
    mapping(
      "email"    -> nonEmptyText,
      "password" -> nonEmptyText
    )(LoginForm.apply)(LoginForm.unapply)
  )

  def login: Action[AnyContent] = Action.async { implicit request =>
    val result = for {
      form <- loginForm.bindFromRequest() |> HttpResult.fromForm(e =>
        BadRequest(views.html.login(e)))
      userId <- services.userDao.maybeLogin(form) |> HttpResult.fromFOption(
        BadRequest(views.html.login(loginForm.fill(form).withGlobalError("bad.password"))))
      loginResult <- gotoLoginSucceeded(userId) |> HttpResult.fromFuture
    } yield loginResult

    constructResult(result)
  }

  def logout: Action[AnyContent] = Action.async { implicit request =>
    gotoLogoutSucceeded
  }

  def api(s: String) = AsyncStack(parse.multipartFormData) { implicit request =>
    val path = s.split("/")
    loggedIn match {
      case Some(user) =>
        val dataStr = request.body.dataParts
          .get("data")
          .flatMap(_.headOption)
          .getOrElse("")

        AutowireRouter
          .route[WiredApi](new WiredApiService(user, services, request.body.files)) {
            val json = read[Map[String, String]](dataStr)
            autowire.Core.Request(path, json)
          }
          .map { responseData =>
            Ok(responseData).as("application/json")
          }
      case None =>
        Ok(write(Left(UnauthorizedApi))).as("application/json").asFuture
    }
  }
} 
Example 14
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 15
Source File: ResetPasswordController.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.landing

import javax.inject.{Inject, Singleton}
import services.user.UserService
import services.generated.tables.records.UserRecord
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.I18nSupport
import play.api.libs.mailer._
import play.api.mvc.{Action, AbstractController, ControllerComponents}
import scala.concurrent.{ExecutionContext, Future}

case class ResetPasswordData(email: String)

@Singleton
class ResetPasswordController @Inject() (
    val components: ControllerComponents,
    val users: UserService,
    val mailerClient: MailerClient,
    implicit val ctx: ExecutionContext
  ) extends AbstractController(components) with I18nSupport {
  
  val resetPasswordForm = Form(
    mapping("email" -> email)(ResetPasswordData.apply)(ResetPasswordData.unapply)
  )

  
  private def sendMail(user: UserRecord, newPassword: String) = Future {
    val name = Option(user.getRealName).getOrElse(user.getUsername)
    
    val message =
      s"""Dear $name,
        |
        |Your Recogito password was reset to
        |
        |   $newPassword
        |
        |Please log in to Recogito with this password. You can change it
        |in your personal Account Settings.
        |
        |Cheers,
        |the Recogito Team""".stripMargin
    
    // TODO this now hard-wires "[email protected]" as reply address
    // TODO see if we can take this directly from the config file instead
    val email = Email(
      "Your Recogito password was reset",
      "Recogito Team <[email protected]>",
      Seq(users.decryptEmail(user.getEmail)),
      Some(message)
    )
    
    mailerClient.send(email)
  } recover { case t: Throwable =>
    t.printStackTrace
  }
  
  def showResetForm = Action { implicit request =>
    Ok(views.html.landing.resetPassword(resetPasswordForm))
  }
  
  def resetPassword = Action.async { implicit request =>
    resetPasswordForm.bindFromRequest.fold(
      formWithErrors =>
        Future.successful(BadRequest(views.html.landing.resetPassword(formWithErrors))),

      resetData => 
        users.findByEmail(resetData.email).flatMap {
          case Some(user) => 
            users.resetPassword(user.getUsername).map { password =>
              sendMail(user, password)
              Ok(views.html.landing.resetPasswordOk())
            }
                       
          case None =>
            Future.successful(Redirect(routes.ResetPasswordController.showResetForm()).flashing("error" -> "Can't find that e-mail, sorry."))
        }
    )
  }
  
} 
Example 16
Source File: LoginLogoutController.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.landing

import com.mohiva.play.silhouette.api.{LoginInfo, Silhouette}
import controllers.{HasConfig, HasUserService, Security}
import java.util.UUID
import javax.inject.{Inject, Singleton}
import services.announcement.AnnouncementService
import services.user.UserService
import play.api.Configuration
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.I18nSupport
import play.api.mvc.{AbstractController, ControllerComponents}
import scala.concurrent.{ ExecutionContext, Future }

case class LoginData(usernameOrPassword: String, password: String)

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

  private val MESSAGE = "message"

  private val INVALID_LOGIN = "Invalid Username or Password"
  
  private val auth = silhouette.env.authenticatorService

  val loginForm = Form(
    mapping(
      "username" -> nonEmptyText,
      "password" -> nonEmptyText
    )(LoginData.apply)(LoginData.unapply)
  )

  def showLoginForm(destination: Option[String]) = Action { implicit request =>
    destination match {
      case None => Ok(views.html.landing.login(loginForm))
      case Some(dest) => Ok(views.html.landing.login(loginForm)).withSession("access_uri" -> dest)
    }
  }

  def processLogin = silhouette.UserAwareAction.async { implicit request =>    
    loginForm.bindFromRequest.fold(
      formWithErrors =>
        Future(BadRequest(views.html.landing.login(formWithErrors))),

      loginData =>
        users.validateUser(loginData.usernameOrPassword, loginData.password).flatMap {
          case Some(validUser) =>
            
            val destination = request.session.get("access_uri").getOrElse(routes.LandingController.index.toString)
            users.updateLastLogin(validUser.getUsername)
            
            val fAuthentication = auth.create(LoginInfo(Security.PROVIDER_ID, validUser.getUsername))
              .flatMap(auth.init(_))
                          
            fAuthentication.flatMap { authentication =>               
                auth.embed(authentication,
                  Redirect(destination).withSession(request.session - "access_uri"))
            }
          
          case None => Future(Redirect(routes.LoginLogoutController.showLoginForm()).flashing(MESSAGE -> INVALID_LOGIN))
        }
    )
  }

  def confirmServiceAnnouncement(id: UUID, response: String, destination: Option[String]) = silhouette.SecuredAction.async { implicit request =>
    announcements.confirm(id, request.identity.username, response).map { success =>
      if (success) destination.map(Redirect(_)).getOrElse(Redirect(routes.LandingController.index))
      else InternalServerError
    }
  }

  def logout = silhouette.SecuredAction.async { implicit request =>
    auth.discard(request.authenticator, Redirect(routes.LandingController.index))
  }

} 
Example 17
Source File: LandingController.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.landing

import com.mohiva.play.silhouette.api.Silhouette
import controllers.{ HasConfig, HasUserService, HasVisitLogging, HasPrettyPrintJSON, Security }
import java.io.FileInputStream
import javax.inject.{ Inject, Singleton }
import java.net.URI
import org.webjars.play.WebJarsUtil
import play.api.Configuration
import play.api.i18n.I18nSupport
import play.api.libs.json.{Json, JsObject}
import play.api.mvc.{Action, AbstractController, ControllerComponents}
import scala.concurrent.ExecutionContext
import services.annotation.AnnotationService
import services.contribution.ContributionService
import services.document.DocumentService
import services.user.UserService
import services.visit.VisitService

@Singleton
class LandingController @Inject() (
    val components: ControllerComponents,
    val config: Configuration,
    val annotations: AnnotationService,
    val contributions: ContributionService,
    val documents: DocumentService,
    val users: UserService,
    val silhouette: Silhouette[Security.Env],
    implicit val ctx: ExecutionContext,
    implicit val visits: VisitService,
    implicit val webjars: WebJarsUtil
) extends AbstractController(components) with HasConfig with HasUserService with HasVisitLogging with HasPrettyPrintJSON with I18nSupport {

  def index = silhouette.UserAwareAction { implicit request =>
    // Temporary hack only
    request.queryString.get("lang").flatMap(_.headOption) match {
      case Some(lang) =>
        Redirect(routes.LandingController.index).withLang(play.api.i18n.Lang(lang))
      case None =>
        request.identity match {
          case Some(user) =>
            Redirect(controllers.my.routes.WorkspaceController.workspace(user.username))

          case None =>
            logPageView()
            Ok(views.html.landing.index())
        }
    }
  }

  def getStats() = silhouette.UnsecuredAction.async { implicit request =>
    val fAnnotations = annotations.countTotal()
    val fEdits = contributions.countLast24hrs()
    val fUsers = users.countUsers()

    val f = for {
      annotations <- fAnnotations
      edits <- fEdits
      users <- fUsers
    } yield (annotations, edits, users)

    f.map { case (annotations, edits, users) =>
      jsonOk(Json.obj(
        "annotations" -> annotations,
        "edits" -> edits,
        "users" -> users
      ))
    }
  }

  def sitemap() = Action.async { implicit request =>
    documents.listOwnersWithPublicDocuments().map { users =>
      val baseURL = routes.LandingController.index().absoluteURL()
      val sitemap = users.map(user => s"${baseURL}${user}").mkString("\n")
      Ok(sitemap).as("text/plain")
    }
  }

  def robots() = Action { implicit request =>
    val sitemapURL = routes.LandingController.sitemap().absoluteURL()
    Ok(s"SITEMAP: ${sitemapURL}").as("text/plain")
  }

  def swaggerConfig() = Action { implicit request => 
    val json = Json.parse(new FileInputStream("conf/swagger.json"))
    val baseURL = new URI(routes.LandingController.index.absoluteURL)
    val host = if (baseURL.getPort == -1) baseURL.getHost else s"${baseURL.getHost}:${baseURL.getPort}"
    jsonOk(json.as[JsObject] ++ Json.obj("host" -> host))
  }

} 
Example 18
Source File: WorkspaceController.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.my

import com.mohiva.play.silhouette.api.Silhouette
import controllers.{BaseController, Security, HasPrettyPrintJSON}
import javax.inject.{Inject, Singleton}
import services.contribution.{Contribution, ContributionService}
import services.user.{User, UserService}
import org.webjars.play.WebJarsUtil
import play.api.{Configuration, Environment}
import play.api.i18n.I18nSupport
import play.api.libs.json.Json
import play.api.mvc.{ControllerComponents, RequestHeader}
import services.document.DocumentService
import scala.concurrent.{ExecutionContext, Future}

@Singleton
class WorkspaceController @Inject() (
  val components: ControllerComponents,
  val contributions: ContributionService,
  val users: UserService,
  val config: Configuration,
  val silhouette: Silhouette[Security.Env],
  implicit val documents: DocumentService,
  implicit val ctx: ExecutionContext,
  implicit val env: Environment,
  implicit val webjars: WebJarsUtil
) extends BaseController(components, config, users) with I18nSupport with HasPrettyPrintJSON {

  
  def workspace(usernameInPath: String) = silhouette.UserAwareAction.async { implicit request =>    
    // If the user is logged in & the name in the path == username it's the profile owner
    val isProfileOwner = request.identity match {
      case Some(userWithRoles) => userWithRoles.username.equalsIgnoreCase(usernameInPath)
      case None => false
    }
    
    if (isProfileOwner)
      Future.successful(Ok(views.html.my.workspace()))
    else
      renderPublicProfile(usernameInPath, request.identity)
  }

  def activityFeed(usernameInPath: String) = silhouette.UserAwareAction.async { implicit request =>
    val loggedInAs = request.identity.map(_.username)
    contributions.getUserActivityFeed(Seq(usernameInPath), loggedInAs).map { response => 
      jsonOk(Json.toJson(response))
    } 
  }
  
} 
Example 19
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 20
Source File: AccountSettingsController.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, LoginInfo}
import controllers.{HasUserService, HasConfig, Security}
import javax.inject.Inject
import services.announcement.AnnouncementService
import services.annotation.AnnotationService
import services.contribution.ContributionService
import services.user.Roles._
import services.user.UserService
import services.upload.UploadService
import services.document.DocumentService
import org.webjars.play.WebJarsUtil
import play.api.Configuration
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.I18nSupport
import play.api.mvc.{AbstractController, ControllerComponents}
import scala.concurrent.{Await, ExecutionContext, Future}
import scala.concurrent.duration._
import controllers.HasAccountRemoval

case class AccountSettingsData(
  email  : String,
  name   : Option[String],
  bio    : Option[String],
  website: Option[String])

class AccountSettingsController @Inject() (
  val components: ControllerComponents,
  val config: Configuration,
  val silhouette: Silhouette[Security.Env],
  implicit val announcements: AnnouncementService,
  implicit val annotations: AnnotationService,
  implicit val contributions: ContributionService,
  implicit val ctx: ExecutionContext,
  implicit val documents: DocumentService,
  implicit val uploads: UploadService,
  implicit val users: UserService,
  implicit val webjars: WebJarsUtil
) extends AbstractController(components) with HasUserService with HasConfig with HasAccountRemoval with I18nSupport {

  val accountSettingsForm = Form(
    mapping(
      "email" -> email,
      "name" -> optional(text(maxLength=80)),
      "bio" -> optional(text(maxLength=256)),
      "website" -> optional(text(maxLength=256))
    )(AccountSettingsData.apply)(AccountSettingsData.unapply)
  )

  def index() = silhouette.SecuredAction { implicit request =>
    val u = request.identity
    
    val form = accountSettingsForm.fill(AccountSettingsData(
      users.decryptEmail(u.email),
      u.realName,
      u.bio,
      u.website))
    
    Ok(views.html.my.settings.account(form, u))
  }

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

      f =>
        users.updateUserSettings(request.identity.username, f.email, f.name, f.bio, f.website)
          .map { success =>
            if (success)
              Redirect(routes.AccountSettingsController.index).flashing("success" -> "Your settings have been saved.")
            else 
              Redirect(routes.AccountSettingsController.index).flashing("error" -> "There was an error while saving your settings.")
          }.recover { case t:Throwable => {
            t.printStackTrace()
            Redirect(routes.AccountSettingsController.index).flashing("error" -> "There was an error while saving your settings.")
          }}
    )
  }
  
  def deleteAccount() = silhouette.SecuredAction.async { implicit request =>
    deleteUserAccount(request.identity.username).flatMap { _ =>
      silhouette.env.authenticatorService.discard(
        request.authenticator,
        Redirect(controllers.landing.routes.LandingController.index))
    }
  }

} 
Example 21
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 22
Source File: MapController.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.document.map

import com.mohiva.play.silhouette.api.Silhouette
import controllers.{BaseOptAuthController, HasVisitLogging, Security}
import javax.inject.{Inject, Singleton}
import services.document.DocumentService
import services.annotation.AnnotationService
import services.user.UserService
import services.user.Roles._
import services.visit.VisitService
import org.webjars.play.WebJarsUtil
import play.api.Configuration
import play.api.mvc.ControllerComponents
import play.api.i18n.I18nSupport
import scala.concurrent.{ExecutionContext, Future}

@Singleton
class MapController @Inject() (
    val components: ControllerComponents,
    val config: Configuration,
    val annotations: AnnotationService,
    val document: DocumentService,
    val users: UserService,
    val silhouette: Silhouette[Security.Env],
    implicit val visitService: VisitService,
    implicit val ctx: ExecutionContext,
    implicit val webjars: WebJarsUtil
  ) extends BaseOptAuthController(components, config, document, users) with HasVisitLogging with I18nSupport {

  def showMap(documentId: String) = silhouette.UserAwareAction.async { implicit request =>
    documentReadResponse(documentId, request.identity,  { case (doc, accesslevel) =>
      logDocumentView(doc.document, None, accesslevel)
      annotations.countByDocId(documentId).map { documentAnnotationCount =>
        Ok(views.html.document.map.index(doc, request.identity, accesslevel, documentAnnotationCount))
      }
    })
  }

} 
Example 23
Source File: StatsController.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.document.stats

import com.mohiva.play.silhouette.api.Silhouette
import controllers.{BaseOptAuthController, Security, HasVisitLogging, HasPrettyPrintJSON}
import java.io.{ByteArrayOutputStream, PrintWriter}
import javax.inject.{Inject, Singleton}
import kantan.csv._
import kantan.csv.ops._
import kantan.csv.CsvConfiguration.{Header, QuotePolicy}
import kantan.csv.engine.commons._
import services.annotation.AnnotationService
import services.document.DocumentService
import services.user.UserService
import services.user.Roles._
import services.visit.VisitService
import org.webjars.play.WebJarsUtil
import play.api.Configuration
import play.api.mvc.{AnyContent, Request, Result, ControllerComponents}
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.i18n.I18nSupport
import plugins.PluginRegistry
import scala.concurrent.{ExecutionContext, Future}

@Singleton
class StatsController @Inject() (
  val components: ControllerComponents,
  val config: Configuration,
  val documents: DocumentService,
  val annotations: AnnotationService,
  val users: UserService,
  val silhouette: Silhouette[Security.Env],
  implicit val visitService: VisitService,
  implicit val webjars: WebJarsUtil,
  implicit val ctx: ExecutionContext
) extends BaseOptAuthController(components, config, documents, users) 
    with HasVisitLogging 
    with HasPrettyPrintJSON 
    with I18nSupport {
  
  private val CSV_CONFIG = CsvConfiguration(',', '"', QuotePolicy.WhenNeeded, Header.None)
    
  implicit val tuple2Writes: Writes[Tuple2[String, Long]] = (
    (JsPath \ "value").write[String] and
    (JsPath \ "count").write[Long]
  )(t => (t._1, t._2))
  
  private def toCSV(stats: Seq[(String, Long)]): String = {
    val out = new ByteArrayOutputStream()
    val writer = out.asCsvWriter[(String, Long)](CSV_CONFIG)
    stats.foreach(writer.write(_))
    writer.close()
    new String(out.toByteArray, "UTF-8")
  }
  
  def showDocumentStats(documentId: String, tab: Option[String]) = silhouette.UserAwareAction.async { implicit request =>
    documentReadResponse(documentId, request.identity,  { case (doc, accesslevel) =>
      logDocumentView(doc.document, None, accesslevel)      
      tab.map(_.toLowerCase) match {
        case Some(t) if t == "activity" =>  
          val plugins = PluginRegistry.listConfigs("document.stats.activity")
          Future.successful(Ok(views.html.document.stats.activity(doc, request.identity, accesslevel, plugins)))
          
        case Some(t) if t == "entities" =>
          val plugins = PluginRegistry.listConfigs("document.stats.entities")
          Future.successful(Ok(views.html.document.stats.entities(doc, request.identity, accesslevel, plugins)))
          
        case Some(t) if t == "tags" =>
          val plugins = PluginRegistry.listConfigs("document.stats.tags")
          Future.successful(Ok(views.html.document.stats.tags(doc, request.identity, accesslevel, plugins)))
          
        case _ =>
          val plugins = PluginRegistry.listConfigs("document.stats.activity")
          Future.successful(Ok(views.html.document.stats.activity(doc, request.identity, accesslevel, plugins)))
      }
    })
  }
  
  private def getTags(documentId: String)(action: (Seq[(String, Long)], Request[AnyContent]) => Result) =
    silhouette.UserAwareAction.async { implicit request =>
      documentReadResponse(documentId, request.identity,  { case (doc, accesslevel) =>
          annotations.getTagStats(documentId).map { buckets =>
            action(buckets, request.request)
          }
        }
      )
    }
  
  def getTagsAsJSON(documentId: String) = getTags(documentId) { case (buckets, request) =>
    jsonOk(Json.toJson(buckets))(request)
  }
  
  def getTagsAsCSV(documentId: String) = getTags(documentId) { case(buckets, request) =>
    Ok(toCSV(buckets)).withHeaders(CONTENT_DISPOSITION -> { s"attachment; filename=${documentId}_tags.csv" })
  }

} 
Example 24
Source File: DiscussionController.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.document.discussion

import com.mohiva.play.silhouette.api.Silhouette
import controllers.{BaseAuthController, Security}
import javax.inject.{Inject, Singleton}
import services.document.DocumentService
import services.user.UserService
import services.user.Roles._
import org.webjars.play.WebJarsUtil
import play.api.Configuration
import play.api.mvc.ControllerComponents
import play.api.i18n.I18nSupport
import scala.concurrent.ExecutionContext

@Singleton
class DiscussionController @Inject() (
    val components: ControllerComponents,
    val config: Configuration,
    val documents: DocumentService,
    val users: UserService,
    val silhouette: Silhouette[Security.Env],
    implicit val webjars: WebJarsUtil,
    implicit val ctx: ExecutionContext
  ) extends BaseAuthController(components, config, documents, users) with I18nSupport {

  def showDiscussionBoard(documentId: String) = silhouette.SecuredAction.async { implicit request =>
    documentResponse(documentId, request.identity, { case (doc, accesslevel) =>
      Ok(views.html.document.discussion.index(doc, Some(request.identity), accesslevel)) })
  }

} 
Example 25
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 26
Source File: RolesController.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.identities.controllers

import com.dataengi.crm.identities.actions.SecuredFilteredAction
import com.dataengi.crm.identities.services.RolesService
import com.dataengi.crm.identities.formatters.roles.RoleFormatter._
import com.dataengi.crm.common.controllers.ApplicationController
import com.google.inject.Inject
import com.mohiva.play.silhouette.api.Silhouette
import play.api.i18n.I18nSupport
import play.api.mvc.ControllerComponents
import com.dataengi.crm.identities.utils.auth.DefaultEnv

import scala.concurrent.ExecutionContext

class RolesController @Inject()(rolesService: RolesService,
                                val silhouette: Silhouette[DefaultEnv],
                                components: ControllerComponents,
                                implicit val executionContext: ExecutionContext)
    extends ApplicationController(components)
    with SecuredFilteredAction
    with I18nSupport {
  def all = SecuredAccessAction.async { implicit request =>
    rolesService.allRoles(request.identity)
  }

  def get(id: Long) = SecuredAccessAction.async { implicit request =>
    rolesService.get(id)
  }

  def findByName(name: String) = SecuredAccessAction.async { implicit request =>
    rolesService.find(name)
  }

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

import controllers.controllershelpers.ControllerLikeHelpers
import models.Breadcrumb
import play.api.i18n.I18nSupport
import play.api.mvc._
import uk.gov.hmrc.play.bootstrap.controller.{FrontendController, Utf8MimeTypes}

import scala.concurrent.{ExecutionContext, Future}

abstract class PertaxBaseController(cc: MessagesControllerComponents)(implicit ec: ExecutionContext)
    extends FrontendController(cc) with I18nSupport with ControllerLikeHelpers {

  implicit class SessionKeyRemover(result: Future[Result]) {
    def removeSessionKey(key: String)(implicit request: Request[_]): Future[Result] = result.map {
      _.withSession(request.session - key)
    }
  }

  val baseBreadcrumb: Breadcrumb =
    List("label.account_home" -> routes.HomeController.index().url)

}

trait PertaxBaseControllerTrait extends PertaxBaseController 
Example 28
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 29
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 30
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 31
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 32
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 33
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 34
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 35
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 36
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 37
Source File: CompaniesController.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.identities.controllers

import com.dataengi.crm.common.controllers.ApplicationController
import com.dataengi.crm.identities.actions.SecuredFilteredAction
import com.google.inject.Inject
import com.mohiva.play.silhouette.api.Silhouette
import com.dataengi.crm.identities.formatters.companies.CompaniesFormatter._
import com.dataengi.crm.identities.services.CompaniesService
import play.api.i18n.I18nSupport
import play.api.mvc.ControllerComponents
import com.dataengi.crm.identities.utils.auth.DefaultEnv

import scala.concurrent.ExecutionContext

class CompaniesController @Inject()(companiesService: CompaniesService,
                                    val silhouette: Silhouette[DefaultEnv],
                                    components: ControllerComponents,
                                    implicit val executionContext: ExecutionContext)
    extends ApplicationController(components)
    with SecuredFilteredAction
    with I18nSupport {

  def all = SecuredAccessAction.async { implicit request =>
    companiesService.all()
  }

  def get(id: Long) = SecuredAccessAction.async { implicit request =>
    companiesService.get(id)
  }

  def findByName(name: String) = SecuredAccessAction.async { implicit request =>
    companiesService.find(name)
  }

  def create = SecuredAccessAction.async(parse.json(companyDataFormatter)) { implicit request =>
    companiesService.create(request.body)
  }

} 
Example 38
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 39
Source File: UsersManagementController.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.identities.controllers

import com.dataengi.crm.identities.actions.SecuredFilteredAction
import com.google.inject.Inject
import com.mohiva.play.silhouette.api.Silhouette
import com.dataengi.crm.identities.services.UsersManagementService
import com.dataengi.crm.identities.formatters.authentication.IdentityFormatter._
import com.dataengi.crm.common.controllers.ApplicationController
import play.api.mvc.ControllerComponents
import play.api.i18n.I18nSupport
import com.dataengi.crm.identities.utils.auth.DefaultEnv

import scala.concurrent.ExecutionContext

class UsersManagementController @Inject()(usersManagementService: UsersManagementService,
                                          val silhouette: Silhouette[DefaultEnv],
                                          components: ControllerComponents,
                                          implicit val executionContext: ExecutionContext)
    extends ApplicationController(components)
    with SecuredFilteredAction
    with I18nSupport {

  def getCompanyMembers(companyId: Long) = SecuredAccessAction.async { implicit request =>
    usersManagementService.getCompanyMembers(companyId, request.identity)
  }

  def getCompanyCurrentMembers = SecuredAccessAction.async { implicit request =>
    usersManagementService.getCompanyMembers(request.identity.company.id.get, request.identity)

  }

  def identityInfo = SecuredAccessAction.async { implicit request =>
    usersManagementService.identityInfo(request.identity)
  }

  def activateUser(userId: Long) = SecuredAccessAction.async { implicit request =>
    usersManagementService.activateUser(userId)
  }

  def deactivateUser(userId: Long) = SecuredAccessAction.async { implicit request =>
    usersManagementService.deactivateUser(userId)
  }

} 
Example 40
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 41
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 42
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 43
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 44
Source File: LogoutController.scala    From dependency   with MIT License 5 votes vote down vote up
package controllers

import io.flow.dependency.www.lib.UiData
import io.flow.play.util.Config
import play.api.i18n.I18nSupport
import play.api.mvc.ControllerComponents

class LogoutController @javax.inject.Inject() (
  config: Config,
  val controllerComponents: ControllerComponents
) extends play.api.mvc.BaseController with I18nSupport {

  def logged_out = Action { implicit request =>
    Ok(
      views.html.logged_out(
        UiData(requestPath = request.path, config = config)
      )
    )
  }

  def index() = Action {
    Redirect("/logged_out").withNewSession
  }

} 
Example 45
Source File: Consumer.scala    From CMAK   with Apache License 2.0 5 votes vote down vote up
package controllers

import features.ApplicationFeatures
import models.navigation.Menus
import play.api.i18n.I18nSupport
import play.api.mvc._

import scala.concurrent.ExecutionContext


class Consumer (val cc: ControllerComponents, val kafkaManagerContext: KafkaManagerContext)
               (implicit af: ApplicationFeatures, menus: Menus, ec: ExecutionContext) extends AbstractController(cc) with I18nSupport {

  private[this] val kafkaManager = kafkaManagerContext.getKafkaManager

  def consumers(cluster: String) = Action.async { implicit request: RequestHeader =>
    kafkaManager.getConsumerListExtended(cluster).map { errorOrConsumerList =>
      Ok(views.html.consumer.consumerList(cluster, errorOrConsumerList)).withHeaders("X-Frame-Options" -> "SAMEORIGIN")
    }
  }

  def consumer(cluster: String, consumerGroup: String, consumerType: String) = Action.async { implicit request: RequestHeader =>
    kafkaManager.getConsumerIdentity(cluster,consumerGroup, consumerType).map { errorOrConsumerIdentity =>
      Ok(views.html.consumer.consumerView(cluster,consumerGroup,errorOrConsumerIdentity)).withHeaders("X-Frame-Options" -> "SAMEORIGIN")
    }
  }

  def consumerAndTopic(cluster: String, consumerGroup: String, topic: String, consumerType: String) = Action.async { implicit request: RequestHeader =>
    kafkaManager.getConsumedTopicState(cluster,consumerGroup,topic, consumerType).map { errorOrConsumedTopicState =>
      Ok(views.html.consumer.consumedTopicView(cluster,consumerGroup,consumerType,topic,errorOrConsumedTopicState)).withHeaders("X-Frame-Options" -> "SAMEORIGIN")
    }
  }
} 
Example 46
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 47
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 48
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 49
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")))
    }
  }
}