com.google.inject.Singleton Scala Examples

The following examples show how to use com.google.inject.Singleton. 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: DateTimeTools.scala    From pertax-frontend   with Apache License 2.0 9 votes vote down vote up
package util

import com.google.inject.{Inject, Singleton}
import org.joda.time.format.{DateTimeFormat, DateTimeFormatter}
import org.joda.time.{DateTime, _}
import play.api.Logger
import uk.gov.hmrc.time.CurrentTaxYear

import scala.util.{Failure, Success, Try}

import java.time.{LocalDateTime => JavaLDT}

object DateTimeTools extends CurrentTaxYear {

  //Timezone causing problem on dev server
  val defaultTZ = DateTimeZone.forID("Europe/London")
  val unixDateFormat = "yyyy-MM-dd"
  val unixDateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss"
  val humanDateFormat = "dd MMMMM yyyy"

  //Returns for example 1516 in March 2016
  def previousAndCurrentTaxYear = previousAndCurrentTaxYearFromGivenYear(current.currentYear)

  def previousAndCurrentTaxYearFromGivenYear(year: Int) = {
    def y = year

    (y - 1).toString.takeRight(2) + (y).toString.takeRight(2)
  }

  private def formatter(pattern: String): DateTimeFormatter = DateTimeFormat.forPattern(pattern).withZone(defaultTZ)

  def short(dateTime: LocalDate) = formatter("dd/MM/yyy").print(dateTime)

  def asHumanDateFromUnixDate(unixDate: String): String =
    Try(DateTimeFormat.forPattern(humanDateFormat).print(DateTime.parse(unixDate))) match {
      case Success(v) => v
      case Failure(e) => {
        Logger.warn("Invalid date parse in DateTimeTools.asHumanDateFromUnixDate: " + e)
        unixDate
      }
    }

  def toPaymentDate(dateTime: JavaLDT): LocalDate =
    new LocalDate(dateTime.getYear, dateTime.getMonthValue, dateTime.getDayOfMonth)

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

@Singleton
class DateTimeTools @Inject()() {

  def showSendTaxReturnByPost = {

    val start = new DateTime(s"${DateTime.now().getYear}-11-01T00:00:00Z")
    val end = new DateTime(s"${DateTime.now().getYear + 1}-01-31T23:59:59Z")
    !DateTime.now().isAfter(start) && DateTime.now().isBefore(end)
  }
} 
Example 2
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 3
Source File: ChangeListener.scala    From apalache   with Apache License 2.0 5 votes vote down vote up
package at.forsyte.apalache.tla.lir.storage


import at.forsyte.apalache.tla.lir.transformations.TransformationListener
import at.forsyte.apalache.tla.lir.{LetInEx, OperEx, TlaEx, UID}
import com.google.inject.Singleton

import scala.collection.mutable


@Singleton
class ChangeListener extends TransformationListener {
  private val map = new mutable.HashMap[UID, UID]()

  private def conditionalInsert(ex: TlaEx, uid: UID): Unit =
    if (!map.contains(ex.ID) && ex.ID != uid)
      map.update( ex.ID, uid )

  // Sometimes, a transformation will create a complex expression from a simple one,
  // e.g. UNCHANGED x -> x' \in {x}
  // In these cases, we treat every subexpression of the resulting complex expression
  // as if it were produced by an anonymous transformation from the original
  private def inheritUID(ex: TlaEx, uid: UID) : Unit = {
    ex match {
      case LetInEx( body, defs@_* ) =>
        defs map {
          _.body
        } foreach {
          inheritUID( _, uid )
        }
        inheritUID( body, uid )

      case OperEx( _, args@_* ) =>
        args foreach {
          inheritUID( _, uid )
        }
      case _ => // noop
    }
    conditionalInsert( ex, uid )
  }

  override def onTransformation( originEx : TlaEx, newEx : TlaEx ) : Unit = {
    if ( originEx.ID != newEx.ID ) {
      map.update( newEx.ID, originEx.ID )
      inheritUID( newEx, originEx.ID )
    }
  }

  def traceBack( p_id : UID ) : UID = map.get( p_id ) match {
    case Some( id ) => traceBack( id )
    case _ => p_id
  }
} 
Example 4
Source File: PasswordInfoDAO.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.identities.daos

import com.google.inject.Singleton
import com.mohiva.play.silhouette.api.LoginInfo
import com.mohiva.play.silhouette.api.util.PasswordInfo
import com.mohiva.play.silhouette.persistence.daos.DelegableAuthInfoDAO

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

trait PasswordInfoDAO extends DelegableAuthInfoDAO[PasswordInfo]

@Singleton
class InMemoryPasswordInfoDAOImpl extends PasswordInfoDAO {

  val passwords = mutable.HashMap.empty[LoginInfo, PasswordInfo]

  
  def remove(loginInfo: LoginInfo): Future[Unit] = {
    Future.successful(
      passwords.remove(loginInfo)
    )
  }
} 
Example 5
Source File: MailsCreator.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.identities.utils.mails

import java.util.UUID

import cats.instances.all._
import com.google.inject.{Inject, Singleton}
import com.mohiva.play.silhouette.api.util.IDGenerator
import com.dataengi.crm.common.configurations.links.LinksConfiguration
import com.dataengi.crm.common.context.types._
import com.dataengi.crm.common.services.mailer.MailData

import scala.concurrent.ExecutionContext

@Singleton
class MailsCreator @Inject()(links: LinksConfiguration,
                             iDGenerator: IDGenerator,
                             implicit val executionContext: ExecutionContext) {

  def forgotPasswordEmail(hash: String): Or[MailData] =
    for {
      domain <- links.domain
      url    <- links.recoverPassword
    } yield {
      val totalLink = domain + url + hash
      val body =
        s"""
           |<p>You told us you forgot your password. If you really did, click here to choose a new one:</p> 
           |<a href="$totalLink">Choose a new password</a>
           |<p>If you didn't mean to reset your password, then you can just ignore this email; your password will not change.</p>""".stripMargin
      MailData("Recover password", Some(body), None)
    }

  def signUpInviteMail(hash: UUID): Or[MailData] = {
    for {
      domain <- links.domain
      url    <- links.signUpLink
    } yield {
      val totalLink = domain + url + hash.toString
      val body =
        s"""
           |<p>Thank you for registering at CRM. You may now log in by
           |clicking this link or copying and pasting it to your browser:</p>
           |<a href="$totalLink">$totalLink</a>
           |<p>This link can only be used once to log in and will lead you to a page where
           |you can set your password.</p>""".stripMargin
      MailData("Register invite", Some(body), None)
    }
  }

} 
Example 6
Source File: UsersManagementService.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.identities.services

import com.dataengi.crm.identities.models.{IdentityInfo, User, UserStates}
import com.dataengi.crm.common.context.types._
import com.google.inject.{Inject, Singleton}
import cats.instances.all._

import scala.concurrent.ExecutionContext

trait UsersManagementService {

  def getCompanyMembers(companyId: Long, identity: User): Or[List[User]]

  def identityInfo(user: User): Or[IdentityInfo]

  def activateUser(userId: Long): EmptyOr

  def deactivateUser(userId: Long): EmptyOr

}

@Singleton
class UsersManagementServiceImplementation @Inject()(userService: UsersService,
                                                     rolesService: RolesService,
                                                     implicit val executionContext: ExecutionContext)
    extends UsersManagementService {

  // TODO: Verify permissions
  override def getCompanyMembers(companyId: Long, identity: User): Or[List[User]] = userService.getCompanyMembers(companyId)

  override def identityInfo(user: User): Or[IdentityInfo] =
    for {
      companyMembers <- userService.getCompanyMembers(user.company.id.get).map(_.map(_.id.get))
      roles          <- rolesService.allRoles()
    } yield IdentityInfo(user, companyMembers, roles)

  override def activateUser(userId: Long): EmptyOr =
    for {
      user        <- userService.get(userId)
      updateState <- userService.updateState(userId, state = UserStates.Activated)
    } yield updateState

  override def deactivateUser(userId: Long): EmptyOr =
    for {
      user        <- userService.get(userId)
      updateState <- userService.updateState(userId, state = UserStates.Deactivated)
    } yield updateState

} 
Example 7
Source File: LinksConfiguration.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.common.configurations.links

import com.google.inject.{Inject, Singleton}
import com.dataengi.crm.common.context.types._
import com.dataengi.crm.common.errors.ConfigErrors
import play.api.Configuration

@Singleton
class LinksConfiguration @Inject()(configuration: Configuration) {

  def domain: Or[String] = {
    configuration.getOptional[String]("link.domain").toOrWithLeftError(ConfigErrors.ConfigNotFoundError)
  }

  def signUpLink: Or[String] = {
    configuration.getOptional[String]("link.signUp").toOrWithLeftError(ConfigErrors.ConfigNotFoundError)
  }

 def recoverPassword: Or[String] = {
    configuration.getOptional[String]("link.recoverPassword").toOrWithLeftError(ConfigErrors.ConfigNotFoundError)
  }

} 
Example 8
Source File: Global.scala    From daf-semantics   with Apache License 2.0 5 votes vote down vote up
import play._

import javax.inject.Inject
import com.google.inject.{ AbstractModule, Singleton }
import play.api.inject.ApplicationLifecycle
import scala.concurrent.Future
import modules.ClientsModule
import modules.ClientsModuleBase

@Singleton
class Global @Inject() (lifecycle: ApplicationLifecycle) {

  @Inject
  def onStart() {
    Logger.info("#### Application START")
  }

  // REVIEW here
  lifecycle.addStopHook { () =>
    Future.successful({
      Logger.info("#### Application STOP")
    })
  }

  // TODO: plug a servicefactory for repository

}

@Singleton
class StartModule extends AbstractModule {

  def configure() = {

    bind(classOf[ClientsModule]).to(classOf[ClientsModuleBase]).asEagerSingleton()
  }

} 
Example 9
Source File: Global.scala    From daf-semantics   with Apache License 2.0 5 votes vote down vote up
import play._

import javax.inject.Inject
import com.google.inject.{ AbstractModule, Singleton }
import play.api.inject.ApplicationLifecycle
import scala.concurrent.Future
import modules._

@Singleton
class Global @Inject() (lifecycle: ApplicationLifecycle) {

  @Inject
  def onStart() {
    Logger.info("#### Application START")
  }

  // REVIEW here
  lifecycle.addStopHook { () =>
    Future.successful({
      Logger.info("#### Application STOP")
    })
  }

  // TODO: plug a servicefactory for repository

}

@Singleton
class StartModule extends AbstractModule {

  def configure() = {
    bind(classOf[KBModule]).to(classOf[KBModuleBase]).asEagerSingleton()
  }

} 
Example 10
Source File: DatabaseInitializerImpl.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package dao.impl

import com.google.inject.{Inject, Singleton}
import dao.DatabaseInitializer
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import slick.driver.JdbcProfile
import slick.driver.H2Driver.api._
import slick.profile.SqlAction

import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success, Try}


@Singleton
class DatabaseInitializerImpl @Inject()
(protected val dbConfigProvider: DatabaseConfigProvider)(implicit executionContext: ExecutionContext) extends DatabaseInitializer with HasDatabaseConfigProvider[JdbcProfile] {

  import driver.api._

  def createTables = {
    val source = scala.io.Source.fromFile("conf/db/create.sql")
    val query = Try {
      source.mkString
    } match {
      case Success(string) =>
        sqlu"#$string"
      case Failure(e: Throwable) => play.Logger.error("Error reading conf/db/create.sql file",e)
        sqlu""""""
    }
    source.close()
    query

  }

  override def initialize(): Future[Int] = db.run {
    createTables
  }
} 
Example 11
Source File: RoomDAOImpl.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package dao.impl

import javax.inject.Inject

import com.google.inject.Singleton
import dao.RoomDAO
import model.Room
import model.table.RoomTable
import org.h2.jdbc.JdbcSQLException
import play.api.db.slick.DatabaseConfigProvider
import play.api.libs.concurrent.Execution.Implicits._
import services.state.ActionState
import services.state
import slick.driver.JdbcProfile

import scala.concurrent.Future
import scala.util.{Failure, Success}


  override def listAll: Future[Seq[Room]] = {
    db.run(rooms.result)
  }

  override def getByLaboratory(id: Long): Future[Seq[Room]] = {
    db.run(rooms.filter(_.laboratoryId === id).result)
  }

  override def update(room: Room): Future[ActionState] = {
    db.run {
      val foundLaboratory = search(room.id)
      foundLaboratory.update(room).asTry
    }.map{
      case Success(res) if res == 1 =>
        play.Logger.info(s"updated with result: $res")
        state.ActionCompleted
      case Success(_) =>
        play.Logger.info("Room not found")
        state.NotFound
      case Failure(e: JdbcSQLException) =>
        play.Logger.error("There was an error looking for that room",e)
        state.NotFound
      case _ => state.Failed
    }
  }
} 
Example 12
Source File: HomeController.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
package controllers

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

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


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

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

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

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

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

    Ok//(index(messagesApi("about"),views.html.about()))
  }
} 
Example 13
Source File: SimpleServer.scala    From akka-http-test   with Apache License 2.0 5 votes vote down vote up
package com.github.dnvriend.component.simpleserver

import javax.inject.Inject

import akka.actor.ActorSystem
import akka.event.{ Logging, LoggingAdapter }
import akka.http.scaladsl._
import akka.pattern.CircuitBreaker
import akka.stream.{ ActorMaterializer, Materializer }
import com.github.dnvriend.component.repository.PersonRepository
import com.github.dnvriend.component.simpleserver.route._
import com.google.inject.Singleton
import play.api.Configuration

import scala.concurrent.ExecutionContext
import scala.concurrent.duration._

@Singleton
class SimpleServer @Inject() (personDao: PersonRepository, cb: CircuitBreaker, interface: String, port: Int)(implicit system: ActorSystem, mat: Materializer, ec: ExecutionContext) {
  Http().bindAndHandle(SimpleServerRestRoutes.routes(personDao, cb), interface, port)
}

object SimpleServerLauncher extends App {
  implicit val system: ActorSystem = ActorSystem()
  implicit val mat: Materializer = ActorMaterializer()
  implicit val ec: ExecutionContext = system.dispatcher
  implicit val log: LoggingAdapter = Logging(system, this.getClass)
  val maxFailures: Int = 3
  val callTimeout: FiniteDuration = 1.seconds
  val resetTimeout: FiniteDuration = 10.seconds
  val cb = new CircuitBreaker(system.scheduler, maxFailures, callTimeout, resetTimeout)
  val config: play.api.Configuration = Configuration(system.settings.config)

  sys.addShutdownHook {
    system.terminate()
  }

  new SimpleServer(new PersonRepository, cb, config.getString("http.interface").getOrElse("0.0.0.0"), config.getInt("http.port").getOrElse(8080))
} 
Example 14
Source File: AuthModule.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.auth

import com.google.inject.{AbstractModule, Provides, Singleton}
import com.mohiva.play.silhouette.api.LoginInfo
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.services.IdentityService
import com.mohiva.play.silhouette.api.util.{Credentials, PasswordHasherRegistry, PasswordInfo}
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import com.mohiva.play.silhouette.password.BCryptPasswordHasher
import com.mohiva.play.silhouette.persistence.daos.InMemoryAuthInfoDAO
import com.mohiva.play.silhouette.persistence.repositories.DelegableAuthInfoRepository
import de.frosner.broccoli.BroccoliConfiguration
import net.codingwell.scalaguice.ScalaModule

import scala.concurrent.{ExecutionContext, Future}


  @Provides
  @Singleton
  def providesAuthInfoRepository(
      config: AuthConfiguration,
      passwordHasherRegistry: PasswordHasherRegistry
  )(implicit ec: ExecutionContext): AuthInfoRepository =
    new DelegableAuthInfoRepository(config.mode match {
      case AuthMode.Conf =>
        // Create an in-memory DAO and add all accounts from configuration to it
        val dao = new InMemoryAuthInfoDAO[PasswordInfo]()
        config.conf.accounts.foreach { account =>
          dao.add(LoginInfo(CredentialsProvider.ID, account.username),
                  passwordHasherRegistry.current.hash(account.password))
        }
        dao
      case _ =>
        // Use an empty DAO
        new InMemoryAuthInfoDAO[PasswordInfo]()
    })
} 
Example 15
Source File: CouchDBStorageModule.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.instances.storage.couchdb

import com.google.inject.{AbstractModule, Provides, Singleton}
import de.frosner.broccoli.BroccoliConfiguration
import de.frosner.broccoli.instances.storage.InstanceStorage
import net.codingwell.scalaguice.ScalaModule
import play.api.inject.ApplicationLifecycle
import play.api.libs.ws.WSClient

import scala.concurrent.Future


  @Provides
  @Singleton
  def provideCouchDBInstanceStorage(
      config: BroccoliConfiguration,
      client: WSClient,
      applicationLifecycle: ApplicationLifecycle
  ): InstanceStorage = {
    val couchdbConfig = config.instances.storage.couchdb
    val storage = new CouchDBInstanceStorage(couchdbConfig.url, couchdbConfig.database, client)
    applicationLifecycle.addStopHook(() => {
      if (!storage.isClosed) {
        storage.close()
      }
      Future.successful({})
    })
    storage
  }
} 
Example 16
Source File: FileSystemStorageModule.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.instances.storage.filesystem

import com.google.inject.{AbstractModule, Provides, Singleton}
import de.frosner.broccoli.BroccoliConfiguration
import de.frosner.broccoli.instances.storage.InstanceStorage
import net.codingwell.scalaguice.ScalaModule
import play.api.inject.ApplicationLifecycle

import scala.concurrent.Future


  @Provides
  @Singleton
  def provideFileSystemInstanceStorage(
      config: BroccoliConfiguration,
      applicationLifecycle: ApplicationLifecycle
  ): InstanceStorage = {
    val storage = new FileSystemInstanceStorage(config.instances.storage.fs.path.toAbsolutePath.toFile)
    applicationLifecycle.addStopHook(() => {
      if (!storage.isClosed) {
        storage.close()
      }
      Future.successful({})
    })
    storage
  }
} 
Example 17
Source File: JWTAuthenticatorRepository.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.identities.repositories

import com.dataengi.crm.identities.daos.JWTAuthenticatorDAO
import com.dataengi.crm.identities.models.JWTAuthenticatorData
import com.google.common.cache.CacheBuilder
import com.google.inject.{Inject, Singleton}
import com.mohiva.play.silhouette.api.crypto.AuthenticatorEncoder
import com.mohiva.play.silhouette.api.repositories.AuthenticatorRepository
import com.mohiva.play.silhouette.impl.authenticators.{JWTAuthenticator, JWTAuthenticatorSettings}

import scala.collection.concurrent.TrieMap
import scala.concurrent.{ExecutionContext, Future}
import scalacache.guava.GuavaCache

trait JWTAuthenticatorRepository extends AuthenticatorRepository[JWTAuthenticator]

@Singleton
class JWTAuthenticatorRepositoryInMemoryImplementation @Inject()(implicit val executionContext: ExecutionContext)
    extends JWTAuthenticatorRepository {

  protected val repository = TrieMap[String, JWTAuthenticator]()

  override def find(id: String): Future[Option[JWTAuthenticator]] = Future {
    repository.get(id)
  }

  override def add(authenticator: JWTAuthenticator): Future[JWTAuthenticator] = Future {
    repository.put(authenticator.id, authenticator)
    authenticator
  }

  override def update(authenticator: JWTAuthenticator): Future[JWTAuthenticator] = Future {
    repository.update(authenticator.id, authenticator)
    authenticator
  }

  override def remove(id: String): Future[Unit] = Future {
    repository.remove(id)
  }
}

@Singleton
class JWTAuthenticatorSerializableRepositoryImplementation @Inject()(implicit val executionContext: ExecutionContext,
                                                                     authenticatorDAO: JWTAuthenticatorDAO,
                                                                     authenticatorEncoder: AuthenticatorEncoder,
                                                                     conf: JWTAuthenticatorSettings)
    extends JWTAuthenticatorRepository {

  override def find(id: String): Future[Option[JWTAuthenticator]] =
    authenticatorDAO
      .getOption(id)
      .map(_.map(data => JWTAuthenticator.unserialize(data.authenticator, authenticatorEncoder, conf).get))

  override def add(authenticator: JWTAuthenticator): Future[JWTAuthenticator] =
    for {
      data      <- serializeData(authenticator)
      addResult <- authenticatorDAO.add(data)
    } yield authenticator

  private def serializeData(authenticator: JWTAuthenticator): Future[JWTAuthenticatorData] = {
    Future {
      val serializedData = JWTAuthenticator.serialize(authenticator, authenticatorEncoder, conf)
      JWTAuthenticatorData(serializedData, authenticator.id)
    }
  }

  override def update(authenticator: JWTAuthenticator): Future[JWTAuthenticator] =
    for {
      updatedAuthenticator <- authenticatorDAO.get(authenticator.id)
      data                 <- serializeData(authenticator)
      updateResult         <- authenticatorDAO.update(data.copy(id = updatedAuthenticator.id))
    } yield authenticator

  override def remove(id: String): Future[Unit] = authenticatorDAO.delete(id)

}

@Singleton
class JWTAuthenticatorCacheRepositoryImplementation @Inject()(implicit val executionContext: ExecutionContext)
    extends JWTAuthenticatorRepository {

  import scalacache._

  val underlyingGuavaCache = CacheBuilder.newBuilder().maximumSize(10000L).build[String, Object]
  implicit val scalaCache  = ScalaCache(GuavaCache(underlyingGuavaCache))
  val cache                = typed[JWTAuthenticator, NoSerialization]

  override def find(id: String): Future[Option[JWTAuthenticator]] = cache.get(id)

  override def add(authenticator: JWTAuthenticator): Future[JWTAuthenticator] =
    cache.put(authenticator.id)(authenticator).map(_ => authenticator)

  override def update(authenticator: JWTAuthenticator): Future[JWTAuthenticator] =
    cache.put(authenticator.id)(authenticator).map(_ => authenticator)

  override def remove(id: String): Future[Unit] = cache.remove(id)

} 
Example 18
Source File: WriteablePassOptions.scala    From apalache   with Apache License 2.0 5 votes vote down vote up
package at.forsyte.apalache.infra.passes

import at.forsyte.apalache.infra.PassOptionException
import com.google.inject.Singleton

import scala.collection.mutable


  def getOrError[T](passName: String, optionName: String): T = {
    val value = get(passName, optionName)
    if (value.isDefined) {
      value.get.asInstanceOf[T]
    } else {
      throw new PassOptionException("The mandatory option %s.%s not found"
        .format(passName, optionName))
    }
  }

} 
Example 19
Source File: UserDao.scala    From bay-scalajs.g8   with Apache License 2.0 5 votes vote down vote up
package services.dao

import bay.driver.CustomizedPgDriver
import com.github.t3hnar.bcrypt._
import com.google.inject.{Inject, Singleton}
import models.forms.LoginForm
import java.time._
import play.api.Logger
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import shared.utils.Implicits
import scala.concurrent.{ExecutionContext, Future}
import shared.models.slick.default._
import models.slick.Default._

@Singleton
class UserDao @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends HasDatabaseConfigProvider[CustomizedPgDriver] with Implicits {

  import profile.api._

  def findUserByEmail(email: String): Future[Option[User]] =
    db.run(users.filter(_.email === email.toLowerCase).result.headOption)

  def findUserById(id: Int): Future[Option[User]] =
    db.run(users.filter(_.id === id).result.headOption)

  def resolveUser(id: Int)(implicit ec: ExecutionContext): Future[Option[User]] = {
    db.run(users.filter(_.id === id).result.headOption).map { e =>
      if (e.isDefined) { // don't wait for this update
        db.run(users.filter(_.id === id).map(_.lastAction).update(OffsetDateTime.now.asOption))
      }

      e
    }
  }

  def isInGroup(id: Option[Int], groupName: String): Future[Boolean] =
    db.run(
      userToUserGroups
        .filter(e => e.userId === id && e.groupName === groupName.toLowerCase)
        .exists
        .result)

  def maybeLogin(loginForm: LoginForm)(implicit ec: ExecutionContext): Future[Option[Int]] =
    db.run(users.filter(_.email === loginForm.email).result.headOption).flatMap {
      case Some(user) if loginForm.password.isBcrypted(user.password) =>
        db.run(users.filter(_.id === user.id).map(_.lastLogin).update(OffsetDateTime.now.asOption)) map { n =>
          if (n > 0) {
            Logger.info(s"${user.email} logged in")
            user.id
          } else None
        }
      case _ =>
        None.asFuture
    }
} 
Example 20
Source File: PostRepositoryImpl.scala    From scala-graphql-api-example   with MIT License 5 votes vote down vote up
package repositories

import com.google.inject.{Inject, Singleton}
import errors.{AlreadyExists, AmbigousResult, NotFound}
import models.Post
import modules.AppDatabase

import scala.concurrent.{ExecutionContext, Future}


  object Actions {

    def create(post: Post): DBIO[Post] =
      for {
        maybePost <- if (post.id.isEmpty) DBIO.successful(None) else find(post.id.get)
        maybePostId <- maybePost match {
          case Some(value) => DBIO.failed(AlreadyExists(s"Already exists post with id = ${post.id}"))
          case _ => postQuery returning postQuery.map(_.id) += post
        }
        maybePost <- find(maybePostId)
        post <- maybePost match {
          case Some(value)=> DBIO.successful(value)
          case _ => DBIO.failed(AmbigousResult(s"Failed to save post [post=$post]"))
        }
      } yield post


    def find(id: Long): DBIO[Option[Post]] = for {
      maybePost <- postQuery.filter(_.id === id).result
      post <- if (maybePost.lengthCompare(2) < 0) DBIO.successful(maybePost.headOption) else DBIO.failed(AmbigousResult(s"Several posts with the same id = $id"))
    } yield post


    def findAll(): DBIO[List[Post]] = for {
      posts <- postQuery.result
    } yield posts.toList

    def update(post: Post): DBIO[Post] = for {
      maybeId <- if (post.id.isDefined) DBIO.successful(post.id.get) else DBIO.failed(NotFound(s"Not found 'id' in the [post=$post]"))
      count <- postQuery.filter(_.id === maybeId).update(post)
      _ <- count match {
        case 0 => DBIO.failed(NotFound(s"Not found post with id=${post.id.get}"))
        case _ => DBIO.successful(())
      }
    } yield post

    def delete(id: Long): DBIO[Boolean] = for {
      maybeDelete <- postQuery.filter(_.id === id).delete
      isDelete = if (maybeDelete == 1) true else false
    } yield isDelete
  }

} 
Example 21
Source File: GraphReaderModule.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.models.json.workflow

import com.google.inject.{AbstractModule, Provides, Singleton}

import ai.deepsense.deeplang.catalogs.doperations.DOperationsCatalog
import ai.deepsense.models.json.graph.GraphJsonProtocol.GraphReader

class GraphReaderModule extends AbstractModule {
  override def configure(): Unit = {
    // Done by 'provides' methods.
  }

  @Singleton
  @Provides
  def provideGraphReader(dOperationsCatalog: DOperationsCatalog): GraphReader = {
    new GraphReader(dOperationsCatalog)
  }
} 
Example 22
Source File: MqModule.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.sessionmanager.mq

import java.util.concurrent.TimeoutException

import akka.actor.{ActorRef, ActorSystem}
import com.google.inject.name.Named
import com.google.inject.{AbstractModule, Provides, Singleton}
import com.rabbitmq.client.ConnectionFactory
import com.thenewmotion.akka.rabbitmq.ConnectionActor

import scala.concurrent.{ExecutionContext, Future}
import scala.util.control.NonFatal

import ai.deepsense.commons.utils.Logging
import ai.deepsense.sessionmanager.service.executor.SessionExecutorClients
import ai.deepsense.sparkutils.AkkaUtils
import ai.deepsense.workflowexecutor.communication.mq.MQCommunication
import ai.deepsense.workflowexecutor.communication.mq.json.Global.{GlobalMQDeserializer, GlobalMQSerializer}
import ai.deepsense.workflowexecutor.rabbitmq.MQCommunicationFactory

class MqModule extends AbstractModule with Logging {
  override def configure(): Unit = {}

  @Provides
  @Singleton
  def communicationFactory(
      actorSystem: ActorSystem,
      @Named("MQConnectionActor") connection: ActorRef): MQCommunicationFactory = {
    MQCommunicationFactory(actorSystem, connection, GlobalMQSerializer, GlobalMQDeserializer)
  }

  @Provides
  @Singleton
  @Named("MQConnectionActor")
  def createConnection(
      system: ActorSystem,
      @Named("queue.host") host: String,
      @Named("queue.port") port: Int,
      @Named("queue.user") user: String,
      @Named("queue.pass") pass: String): ActorRef = {
    val factory = new ConnectionFactory()
    factory.setHost(host)
    factory.setPort(port)
    factory.setUsername(user)
    factory.setPassword(pass)
    system.actorOf(
      ConnectionActor.props(factory),
      MQCommunication.mqActorSystemName)
  }

  @Provides
  @Singleton
  def createSessionExecutorClients(
      communicationFactory: MQCommunicationFactory): SessionExecutorClients = {
    new SessionExecutorClients(communicationFactory)
  }

  @Provides
  @Singleton
  @Named("SessionService.HeartbeatSubscribed")
  def heartbeatSubscriber(
      system: ActorSystem,
      communicationFactory: MQCommunicationFactory,
      @Named("SessionService.Actor") sessionServiceActor: ActorRef,
      @Named("queue.heartbeat.subscription.timeout") timeout: Long): Future[Unit] = {
    import ai.deepsense.sessionmanager.mq.MQCommunicationFactoryEnrichments._
    implicit val ec: ExecutionContext = system.dispatcher
    val subscribed = communicationFactory
      .registerBroadcastSubscriber("seahorse_heartbeats_all", sessionServiceActor)

    val subscribedWithTimeout = Future.firstCompletedOf(List(subscribed, Future {
      Thread.sleep(timeout)
      throw new TimeoutException
    }))

    subscribedWithTimeout.onFailure {
      case NonFatal(e) =>
        logger.error(s"Haven't subscribed to Heartbeats after '$timeout' millis." +
          " Shutting down!")
        AkkaUtils.terminate(system)
    }

    subscribedWithTimeout.map(_.data)
  }
} 
Example 23
Source File: ServiceModule.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.sessionmanager.service

import akka.actor.{ActorRef, ActorSystem}
import com.google.inject.name.Named
import com.google.inject.{AbstractModule, Provides, Singleton}

import ai.deepsense.commons.akka.GuiceAkkaExtension
import ai.deepsense.sessionmanager.service.actors.SessionServiceActor
import ai.deepsense.sessionmanager.service.sessionspawner.SessionSpawner
import ai.deepsense.sessionmanager.service.sessionspawner.sparklauncher.SparkLauncherSessionSpawner

class ServiceModule extends AbstractModule {
  override def configure(): Unit = {
    bind(classOf[SessionSpawner]).to(classOf[SparkLauncherSessionSpawner])
  }

  @Provides
  @Singleton
  @Named("SessionService.Actor")
  def sessionServiceActor(system: ActorSystem): ActorRef = {
    system.actorOf(GuiceAkkaExtension(system).props[SessionServiceActor], "SessionService.Actor")
  }
} 
Example 24
Source File: KeystoneApiModule.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.commons.jclouds

import java.util.Properties

import com.google.inject.name.Named
import com.google.inject.{AbstractModule, Provides, Singleton}
import org.jclouds.Constants.{PROPERTY_CONNECTION_TIMEOUT, PROPERTY_SO_TIMEOUT}
import org.jclouds.ContextBuilder
import org.jclouds.openstack.keystone.v2_0.KeystoneApi

class KeystoneApiModule extends AbstractModule {
  override def configure(): Unit = {
    // Configuration not needed - everything is done by the methods annotated with "Provides".
  }

  @Provides
  @Singleton
  def provideKeystoneApi(
      @Named("auth-service.endpoint") endpoint: String,
      @Named("auth-service.identity") identity: String,
      @Named("auth-service.password") password: String,
      @Named("auth-service.timeout.connection") connectionTimeout: Long,
      @Named("auth-service.timeout.socket") socketTimeout: Long): KeystoneApi = {
    val overrides = new Properties()
    overrides.setProperty(PROPERTY_CONNECTION_TIMEOUT, connectionTimeout.toString)
    overrides.setProperty(PROPERTY_SO_TIMEOUT, socketTimeout.toString)
    ContextBuilder.newBuilder("openstack-keystone")
      .endpoint(endpoint)
      .credentials(identity, password)
      .overrides(overrides)
      .buildApi(classOf[KeystoneApi])
  }
} 
Example 25
Source File: RestModule.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.commons.rest

import scala.concurrent.Await
import scala.concurrent.duration._

import akka.actor.{ActorRef, ActorSystem}
import akka.pattern.ask
import akka.util.Timeout
import com.google.inject.name.Named
import com.google.inject.{AbstractModule, Provides, Singleton}

import ai.deepsense.commons.akka.GuiceAkkaExtension


class RestModule extends AbstractModule {
  override def configure(): Unit = {
    bind(classOf[RestServer])
  }

  @Provides
  @Singleton
  @Named("ApiRouterActorRef")
  def provideApiRouterActorRef(
      @Named("server.startup.timeout") startupTimeout: Long,
      system: ActorSystem): ActorRef = {
    val supervisor =
      system.actorOf(GuiceAkkaExtension(system).props[RestServiceSupervisor], "RestSupervisor")
    val restServiceActorProps = GuiceAkkaExtension(system).props[RestServiceActor]
    implicit val timeout: Timeout = startupTimeout.seconds
    val actorRef = supervisor.ask((restServiceActorProps, "RestServiceActor")).mapTo[ActorRef]
    Await.result(actorRef, timeout.duration)
  }
} 
Example 26
Source File: AppModule.scala    From iep-apps   with Apache License 2.0 5 votes vote down vote up
package com.netflix.iep.ses

import com.google.inject.AbstractModule
import com.google.inject.Provides
import com.google.inject.Singleton
import com.google.inject.multibindings.Multibinder
import com.netflix.iep.aws2.AwsClientFactory
import com.netflix.iep.service.Service
import software.amazon.awssdk.services.sqs.SqsAsyncClient

class AppModule extends AbstractModule {
  override def configure(): Unit = {
    val serviceBinder = Multibinder.newSetBinder(binder(), classOf[Service])
    serviceBinder.addBinding().to(classOf[SesMonitoringService])
  }

  @Singleton
  @Provides
  def provideAwsSqsAsyncClient(factory: AwsClientFactory): SqsAsyncClient = {
    System.setProperty(
      "software.amazon.awssdk.http.async.service.impl",
      "software.amazon.awssdk.http.nio.netty.NettySdkAsyncHttpService"
    )
    factory.newInstance(classOf[SqsAsyncClient])
  }

  @Provides
  def providesNotificationLogger(): NotificationLogger = {
    SesNotificationLogger
  }
} 
Example 27
Source File: StackConfig.scala    From sundial   with MIT License 5 votes vote down vote up
package config

import javax.inject.Named
import com.google.inject.{AbstractModule, Provides, Singleton}
import software.amazon.awssdk.regions.internal.util.EC2MetadataUtils
import software.amazon.awssdk.services.cloudformation.CloudFormationClient
import software.amazon.awssdk.services.cloudformation.model.{
  DescribeStackResourceRequest,
  DescribeStacksRequest
}
import software.amazon.awssdk.services.ec2.Ec2Client
import software.amazon.awssdk.services.ec2.model.DescribeTagsRequest
import software.amazon.awssdk.services.ec2.model.Filter

class StackConfig extends AbstractModule {

  override def configure() = {}

  @Provides
  @Named("cfnStackName")
  @Singleton
  def cfnStackName(ec2Client: Ec2Client): String = {
    import scala.collection.JavaConverters._
    val instanceId = EC2MetadataUtils.getInstanceId
    val resourceTypeFilter =
      Filter.builder.name("resource-type").values("instance").build()
    val resourceIdFilter =
      Filter.builder().name("resource-id").values(instanceId).build()
    val stackIdFilter =
      Filter.builder().name("key").values("aws:cloudformation:stack-id").build()
    val describeTagsRequest = DescribeTagsRequest
      .builder()
      .filters(resourceTypeFilter, resourceIdFilter, stackIdFilter)
      .build()
    val tags = ec2Client.describeTags(describeTagsRequest).tags().asScala
    tags
      .find(_.key() == "aws:cloudformation:stack-id")
      .getOrElse(sys.error("aws:cloudformation:stack-id tag is compulsory"))
      .value()
  }

  @Provides
  @Named("s3Bucket")
  @Singleton
  def s3Bucket(cfnClient: CloudFormationClient,
               @Named("cfnStackName") cfnStackName: String): String = {
    val describeStackRequest = DescribeStackResourceRequest
      .builder()
      .stackName(cfnStackName)
      .logicalResourceId("S3Bucket")
      .build()
    cfnClient
      .describeStackResource(describeStackRequest)
      .stackResourceDetail()
      .physicalResourceId()
  }
  @Provides
  @Named("sundialUrl")
  @Singleton
  def sundialUrl(cfnClient: CloudFormationClient,
                 @Named("cfnStackName") cfnStackName: String) = {
    import scala.collection.JavaConverters._
    val describeStackRequest =
      DescribeStacksRequest.builder().stackName(cfnStackName).build()
    val stack =
      cfnClient.describeStacks(describeStackRequest).stacks().get(0)
    stack
      .outputs()
      .asScala
      .find(_.outputKey() == "WebAddress")
      .get
      .outputValue()
  }

} 
Example 28
Source File: DevelopmentConfig.scala    From sundial   with MIT License 5 votes vote down vote up
package config

import javax.inject.Named

import com.google.inject.{AbstractModule, Provides, Singleton}
import play.api.{Configuration, Environment}

class DevelopmentConfig(environment: Environment, configuration: Configuration)
    extends AbstractModule {

  override def configure() = {}

  @Provides
  @Named("cfnStackName")
  @Singleton
  def cfnStackName: String = "dumm-stack-name"

  @Provides
  @Named("s3Bucket")
  @Singleton
  def s3Bucket: String = configuration.get[String]("s3.bucket")

  @Provides
  @Named("sdbDomain")
  @Singleton
  def sdbDomain: String = "dummy-sdb-domain"

  @Provides
  @Named("sundialUrl")
  @Singleton
  def sundialUrl: String = "http://localhost:9000"

} 
Example 29
Source File: Config.scala    From sundial   with MIT License 5 votes vote down vote up
package config

import javax.inject.Inject
import com.google.inject.{AbstractModule, Provides, Singleton}
import dao.SundialDaoFactory
import dto.DisplayModels
import org.lyranthe.prometheus.client.{DefaultRegistry, Registry, jmx}
import play.api.libs.ws.WSClient
import play.api.{Configuration, Environment, Logging}
import service._
import service.notifications.{
  DevelopmentEmailNotifications,
  EmailNotifications,
  Notification,
  PagerdutyNotifications
}
import software.amazon.awssdk.services.batch.BatchClient
import software.amazon.awssdk.services.cloudformation.CloudFormationClient
import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient
import software.amazon.awssdk.services.ec2.Ec2Client
import software.amazon.awssdk.services.emr.EmrClient
import software.amazon.awssdk.services.s3.S3Client
import software.amazon.awssdk.services.ses.SesClient

@Singleton
class PrometheusJmxInstrumentation @Inject()(implicit val registry: Registry) {
  jmx.register
}

class Config(environment: Environment, configuration: Configuration)
    extends AbstractModule
    with Logging {

  override def configure(): Unit = {

    logger.info(s" *** Starting Sundial *** ")

    logger.info("Env Variables:")
    sys.env.foreach {
      case (key, value) => logger.info(s"Key($key), Value($value)")
    }

    logger.info("Sundial Configuration:")
    configuration.entrySet.foreach { entry =>
      logger.info(s"Key(${entry._1}), Value[${entry._2.toString}]")
    }

    bind(classOf[Registry]).toInstance(DefaultRegistry())

    // AWS Clients
    bind(classOf[BatchClient]).toInstance(BatchClient.create())
    bind(classOf[S3Client]).toInstance(S3Client.create())
    bind(classOf[CloudWatchLogsClient])
      .toInstance(CloudWatchLogsClient.create())
    bind(classOf[Ec2Client]).toInstance(Ec2Client.create())
    bind(classOf[EmrClient]).toInstance(EmrClient.create())
    bind(classOf[CloudFormationClient])
      .toInstance(CloudFormationClient.create())
    bind(classOf[SesClient])
      .toInstance(SesClient.create())

    bind(classOf[PrometheusJmxInstrumentation]).asEagerSingleton()

    bind(classOf[Sundial]).asEagerSingleton()

  }

  @Provides
  @Singleton
  def notifications(wsClient: WSClient,
                    daoFactory: SundialDaoFactory,
                    displayModels: DisplayModels,
                    sesClient: SesClient): Seq[Notification] = {
    configuration.getOptional[String]("notifications.mode") match {
      case Some("browser") =>
        Seq(
          new DevelopmentEmailNotifications(daoFactory,
                                            displayModels,
                                            sesClient))
      case Some("email") =>
        Seq(
          new EmailNotifications(
            daoFactory,
            configuration.get[String]("notifications.from"),
            displayModels,
            sesClient))
      case Some("all") =>
        Seq(
          new EmailNotifications(
            daoFactory,
            configuration.get[String]("notifications.from"),
            displayModels,
            sesClient),
          new PagerdutyNotifications(wsClient, daoFactory)
        )
      case _ => Seq.empty
    }
  }

} 
Example 30
Source File: GraphReaderModule.scala    From seahorse-workflow-executor   with Apache License 2.0 5 votes vote down vote up
package io.deepsense.models.json.workflow

import com.google.inject.{AbstractModule, Provides, Singleton}

import io.deepsense.deeplang.catalogs.doperations.DOperationsCatalog
import io.deepsense.models.json.graph.GraphJsonProtocol.GraphReader

class GraphReaderModule extends AbstractModule {
  override def configure(): Unit = {
    // Done by 'provides' methods.
  }

  @Singleton
  @Provides
  def provideGraphReader(dOperationsCatalog: DOperationsCatalog): GraphReader = {
    new GraphReader(dOperationsCatalog)
  }
} 
Example 31
Source File: AddressJourneyCachingHelper.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.controllershelpers

import com.google.inject.{Inject, Singleton}
import controllers.bindable.AddrType
import controllers.routes
import models.{AddressFinderDtoId, AddressJourneyData, AddressPageVisitedDtoId, CacheIdentifier, SelectedAddressRecordId, SelectedRecordSetId, SubmittedAddressDtoId, SubmittedInternationalAddressChoiceId, SubmittedResidencyChoiceDtoId, SubmittedStartDateId, SubmittedTaxCreditsChoiceId}
import models.addresslookup.{AddressRecord, RecordSet}
import models.dto._
import play.api.libs.json.Writes
import play.api.mvc.{Result, Results}
import services.LocalSessionCache
import uk.gov.hmrc.http.cache.client.CacheMap
import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse}

import scala.concurrent.{ExecutionContext, Future}

@Singleton
class AddressJourneyCachingHelper @Inject()(val sessionCache: LocalSessionCache)(implicit ec: ExecutionContext)
    extends Results {

  val addressLookupServiceDownKey = "addressLookupServiceDown"

  def addToCache[A: Writes](id: CacheIdentifier[A], record: A)(implicit hc: HeaderCarrier): Future[CacheMap] =
    sessionCache.cache(id.id, record)

  def cacheAddressLookupServiceDown()(implicit hc: HeaderCarrier): Future[CacheMap] =
    sessionCache.cache(addressLookupServiceDownKey, true)

  def clearCache()(implicit hc: HeaderCarrier): Future[HttpResponse] =
    sessionCache.remove()

  def gettingCachedAddressPageVisitedDto[T](block: Option[AddressPageVisitedDto] => Future[T])(
    implicit hc: HeaderCarrier): Future[T] =
    sessionCache.fetch() flatMap {
      case Some(cacheMap) =>
        block(cacheMap.getEntry[AddressPageVisitedDto](AddressPageVisitedDtoId.id))
      case None =>
        block(None)
    }

  def gettingCachedAddressLookupServiceDown[T](block: Option[Boolean] => T)(implicit hc: HeaderCarrier): Future[T] =
    sessionCache.fetch() map { cacheMap =>
      {
        block(cacheMap.flatMap(_.getEntry[Boolean](addressLookupServiceDownKey)))
      }
    }

  def gettingCachedTaxCreditsChoiceDto[T](block: Option[TaxCreditsChoiceDto] => T)(
    implicit hc: HeaderCarrier): Future[T] =
    sessionCache.fetch() map { cacheMap =>
      {
        block(cacheMap.flatMap(_.getEntry[TaxCreditsChoiceDto](SubmittedTaxCreditsChoiceId.id)))
      }
    }

  def gettingCachedJourneyData[T](typ: AddrType)(block: AddressJourneyData => Future[T])(
    implicit hc: HeaderCarrier): Future[T] =
    sessionCache.fetch() flatMap {
      case Some(cacheMap) =>
        block(
          AddressJourneyData(
            cacheMap.getEntry[AddressPageVisitedDto](AddressPageVisitedDtoId.id),
            cacheMap.getEntry[ResidencyChoiceDto](SubmittedResidencyChoiceDtoId(typ).id),
            cacheMap.getEntry[RecordSet](SelectedRecordSetId(typ).id),
            cacheMap.getEntry[AddressFinderDto](AddressFinderDtoId(typ).id),
            cacheMap.getEntry[AddressRecord](SelectedAddressRecordId(typ).id),
            cacheMap.getEntry[AddressDto](SubmittedAddressDtoId(typ).id),
            cacheMap.getEntry[InternationalAddressChoiceDto](SubmittedInternationalAddressChoiceId.id),
            cacheMap.getEntry[DateDto](SubmittedStartDateId(typ).id),
            cacheMap.getEntry[Boolean](addressLookupServiceDownKey).getOrElse(false)
          )
        )
      case None =>
        block(AddressJourneyData(None, None, None, None, None, None, None, None, addressLookupServiceDown = false))
    }

  def enforceDisplayAddressPageVisited(addressPageVisitedDto: Option[AddressPageVisitedDto])(block: => Future[Result])(
    implicit hc: HeaderCarrier): Future[Result] =
    addressPageVisitedDto match {
      case Some(_) =>
        block
      case None =>
        Future.successful(Redirect(controllers.address.routes.PersonalDetailsController.onPageLoad()))
    }

  def enforceResidencyChoiceSubmitted(journeyData: AddressJourneyData)(
    block: AddressJourneyData => Future[Result]): Future[Result] =
    journeyData match {
      case AddressJourneyData(_, Some(_), _, _, _, _, _, _, _) =>
        block(journeyData)
      case AddressJourneyData(_, None, _, _, _, _, _, _, _) =>
        Future.successful(Redirect(controllers.address.routes.PersonalDetailsController.onPageLoad()))
    }

} 
Example 32
Source File: AddressLookupService.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import com.kenshoo.play.metrics.Metrics
import config.ConfigDecorator
import com.google.inject.{Inject, Singleton}
import metrics._
import models.addresslookup.RecordSet
import play.api.Mode.Mode
import play.api.{Configuration, Environment, Logger}
import services.http.SimpleHttp
import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse}
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import util._

import scala.concurrent.Future

sealed trait AddressLookupResponse

final case class AddressLookupSuccessResponse(addressList: RecordSet) extends AddressLookupResponse
final case class AddressLookupUnexpectedResponse(r: HttpResponse) extends AddressLookupResponse
final case class AddressLookupErrorResponse(cause: Exception) extends AddressLookupResponse

@Singleton
class AddressLookupService @Inject()(
  environment: Environment,
  configuration: Configuration,
  configDecorator: ConfigDecorator,
  val simpleHttp: SimpleHttp,
  val metrics: Metrics,
  val tools: Tools,
  servicesConfig: ServicesConfig)
    extends HasMetrics {

  val mode: Mode = environment.mode
  val runModeConfiguration: Configuration = configuration
  lazy val addressLookupUrl = servicesConfig.baseUrl("address-lookup")

  def lookup(postcode: String, filter: Option[String] = None)(
    implicit hc: HeaderCarrier): Future[AddressLookupResponse] =
    withMetricsTimer("address-lookup") { t =>
      val hn = tools.urlEncode(filter.getOrElse(""))
      val pc = postcode.replaceAll(" ", "")
      val newHc = hc.withExtraHeaders("X-Hmrc-Origin" -> configDecorator.origin)

      simpleHttp.get[AddressLookupResponse](s"$addressLookupUrl/v1/gb/addresses.json?postcode=$pc&filter=$hn")(
        onComplete = {
          case r if r.status >= 200 && r.status < 300 =>
            t.completeTimerAndIncrementSuccessCounter()
            AddressLookupSuccessResponse(RecordSet.fromJsonAddressLookupService(r.json))

          case r =>
            t.completeTimerAndIncrementFailedCounter()
            Logger.warn(s"Unexpected ${r.status} response getting address record from address lookup service")
            AddressLookupUnexpectedResponse(r)
        },
        onError = {
          case e =>
            t.completeTimerAndIncrementFailedCounter()
            Logger.warn("Error getting address record from address lookup service", e)
            AddressLookupErrorResponse(e)
        }
      )(newHc)
    }
} 
Example 33
Source File: LocalSessionCache.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import com.google.inject.{Inject, Singleton}
import config.ConfigDecorator
import javax.inject.Named
import play.api.{Configuration, Environment}
import uk.gov.hmrc.http.cache.client.SessionCache
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import uk.gov.hmrc.play.bootstrap.http.HttpClient

@Singleton
class LocalSessionCache @Inject()(
  environment: Environment,
  configuration: Configuration,
  val appNameConfiguration: Configuration,
  override val http: HttpClient,
  configDecorator: ConfigDecorator,
  servicesConfig: ServicesConfig,
  @Named("appName") appName: String)
    extends SessionCache {
  override lazy val defaultSource = appName
  override lazy val baseUri = servicesConfig.baseUrl("cachable.session-cache")
  override lazy val domain = servicesConfig.getConfString("cachable.session-cache.domain", "keystore")
} 
Example 34
Source File: TaxCalculationService.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import com.kenshoo.play.metrics.Metrics
import com.google.inject.{Inject, Singleton}
import metrics._
import models.{TaxCalculation, TaxYearReconciliation}
import play.api.Mode.Mode
import play.api.http.Status._
import play.api.{Configuration, Environment, Logger}
import services.http.SimpleHttp
import uk.gov.hmrc.domain.Nino
import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse}
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import uk.gov.hmrc.play.bootstrap.http.HttpClient

import scala.concurrent.{ExecutionContext, Future}
import scala.util.control.NonFatal

sealed trait TaxCalculationResponse
case class TaxCalculationSuccessResponse(taxCalculation: TaxCalculation) extends TaxCalculationResponse
case object TaxCalculationNotFoundResponse extends TaxCalculationResponse
case class TaxCalculationUnexpectedResponse(r: HttpResponse) extends TaxCalculationResponse
case class TaxCalculationErrorResponse(cause: Exception) extends TaxCalculationResponse
@Singleton
class TaxCalculationService @Inject()(
  environment: Environment,
  configuration: Configuration,
  val simpleHttp: SimpleHttp,
  val metrics: Metrics,
  val http: HttpClient,
  servicesConfig: ServicesConfig)(implicit ec: ExecutionContext)
    extends HasMetrics {
  val mode: Mode = environment.mode
  val runModeConfiguration: Configuration = configuration
  lazy val taxCalcUrl = servicesConfig.baseUrl("taxcalc")

  
  def getTaxCalculation(nino: Nino, year: Int)(implicit hc: HeaderCarrier): Future[TaxCalculationResponse] =
    withMetricsTimer("get-taxcalc-summary") { t =>
      simpleHttp.get[TaxCalculationResponse](s"$taxCalcUrl/taxcalc/$nino/taxSummary/$year")(
        onComplete = {

          case r if r.status >= 200 && r.status < 300 =>
            Logger.debug(r.body)
            t.completeTimerAndIncrementSuccessCounter()
            TaxCalculationSuccessResponse(r.json.as[TaxCalculation])

          case r if r.status == NOT_FOUND =>
            Logger.debug(r.body)
            t.completeTimerAndIncrementSuccessCounter()
            TaxCalculationNotFoundResponse

          case r =>
            Logger.debug(r.body)
            t.completeTimerAndIncrementFailedCounter()
            Logger.debug(s"Unexpected ${r.status} response getting tax calculation from tax-calculation-service")
            TaxCalculationUnexpectedResponse(r)
        },
        onError = { e =>
          Logger.debug(e.toString)
          t.completeTimerAndIncrementFailedCounter()
          Logger.warn("Error getting tax calculation from tax-calculation-service", e)
          TaxCalculationErrorResponse(e)
        }
      )
    }

  def getTaxYearReconciliations(nino: Nino)(
    implicit headerCarrier: HeaderCarrier): Future[List[TaxYearReconciliation]] =
    http
      .GET[List[TaxYearReconciliation]](s"$taxCalcUrl/taxcalc/$nino/reconciliations")
      .recover {
        case NonFatal(e) =>
          Logger.debug(s"An exception was thrown by taxcalc reconciliations: ${e.getMessage}")
          Nil
      }
} 
Example 35
Source File: IdentityVerificationFrontendService.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import com.kenshoo.play.metrics.Metrics
import com.google.inject.{Inject, Singleton}
import metrics.HasMetrics
import play.api.Mode.Mode
import play.api.http.Status._
import play.api.{Configuration, Environment, Logger}
import services.http.SimpleHttp
import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse}
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig

import scala.concurrent.Future

trait IdentityVerificationResponse
case class IdentityVerificationSuccessResponse(result: String) extends IdentityVerificationResponse
case object IdentityVerificationNotFoundResponse extends IdentityVerificationResponse
case class IdentityVerificationUnexpectedResponse(r: HttpResponse) extends IdentityVerificationResponse
case class IdentityVerificationErrorResponse(cause: Exception) extends IdentityVerificationResponse

object IdentityVerificationSuccessResponse {
  val Success = "Success"
  val Incomplete = "Incomplete"
  val FailedMatching = "FailedMatching"
  val InsufficientEvidence = "InsufficientEvidence"
  val LockedOut = "LockedOut"
  val UserAborted = "UserAborted"
  val Timeout = "Timeout"
  val TechnicalIssue = "TechnicalIssue"
  val PrecondFailed = "PreconditionFailed"
}
@Singleton
class IdentityVerificationFrontendService @Inject()(
  environment: Environment,
  configuration: Configuration,
  val simpleHttp: SimpleHttp,
  val metrics: Metrics,
  servicesConfig: ServicesConfig)
    extends HasMetrics {

  val mode: Mode = environment.mode
  val runModeConfiguration: Configuration = configuration
  lazy val identityVerificationFrontendUrl: String = servicesConfig.baseUrl("identity-verification-frontend")

  def getIVJourneyStatus(journeyId: String)(implicit hc: HeaderCarrier): Future[IdentityVerificationResponse] =
    withMetricsTimer("get-iv-journey-status") { t =>
      simpleHttp.get[IdentityVerificationResponse](
        s"$identityVerificationFrontendUrl/mdtp/journey/journeyId/$journeyId")(
        onComplete = {
          case r if r.status >= 200 && r.status < 300 =>
            t.completeTimerAndIncrementSuccessCounter()
            val result = List((r.json \ "journeyResult").asOpt[String], (r.json \ "result").asOpt[String]).flatten.head //FIXME - dont use head
            IdentityVerificationSuccessResponse(result)

          case r if r.status == NOT_FOUND =>
            t.completeTimerAndIncrementFailedCounter()
            Logger.warn("Unable to get IV journey status from identity-verification-frontend-service")
            IdentityVerificationNotFoundResponse

          case r =>
            t.completeTimerAndIncrementFailedCounter()
            Logger.warn(
              s"Unexpected ${r.status} response getting IV journey status from identity-verification-frontend-service")
            IdentityVerificationUnexpectedResponse(r)
        },
        onError = {
          case e =>
            t.completeTimerAndIncrementFailedCounter()
            Logger.warn("Error getting IV journey status from identity-verification-frontend-service", e)
            IdentityVerificationErrorResponse(e)
        }
      )

    }
} 
Example 36
Source File: LifetimeAllowanceService.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import com.kenshoo.play.metrics.Metrics
import com.google.inject.{Inject, Singleton}
import metrics.HasMetrics
import models.LtaProtections
import play.api.Mode.Mode
import play.api.{Configuration, Environment, Logger}
import services.http.SimpleHttp
import uk.gov.hmrc.domain.Nino
import uk.gov.hmrc.http.{HeaderCarrier, HttpReads}
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
@Singleton
class LifetimeAllowanceService @Inject()(
  environment: Environment,
  configuration: Configuration,
  val simpleHttp: SimpleHttp,
  val metrics: Metrics,
  servicesConfig: ServicesConfig)
    extends HasMetrics {

  val mode: Mode = environment.mode
  val runModeConfiguration: Configuration = configuration
  lazy val lifetimeAllowanceUrl = servicesConfig.baseUrl("pensions-lifetime-allowance")

  def getCount(nino: Nino)(implicit hc: HeaderCarrier, rds: HttpReads[LtaProtections]): Future[Option[Int]] =
    withMetricsTimer("has-lta-response") { t =>
      simpleHttp.get[Option[Int]](
        lifetimeAllowanceUrl + s"/protect-your-lifetime-allowance/individuals/$nino/protections/count")(
        onComplete = {
          case r if r.status >= 200 && r.status < 300 =>
            t.completeTimerAndIncrementSuccessCounter()
            Some((r.json.as[LtaProtections]).count)

          case r =>
            t.completeTimerAndIncrementFailedCounter()
            Logger.warn(
              s"Unexpected ${r.status} response getting lifetime allowance protections count from LTA service")
            None
        },
        onError = {
          case e =>
            t.completeTimerAndIncrementFailedCounter()
            Logger.warn("Error getting lifetime allowance protections count from LTA service", e)
            None
        }
      )
    }

  def hasLtaProtection(nino: Nino)(implicit hc: HeaderCarrier, rds: HttpReads[LtaProtections]): Future[Boolean] =
    getCount(nino) map {
      case (Some(0) | None) => false
      case _                => true
    }
} 
Example 37
Source File: TaiService.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import com.kenshoo.play.metrics.Metrics
import com.google.inject.{Inject, Singleton}
import metrics._
import models._
import play.api.Mode.Mode
import play.api.http.Status._
import play.api.{Configuration, Environment, Logger}
import services.http.SimpleHttp
import uk.gov.hmrc.domain.Nino
import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse}
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig

import scala.concurrent.Future

sealed trait TaxComponentsResponse
case class TaxComponentsSuccessResponse(taxComponents: TaxComponents) extends TaxComponentsResponse
case object TaxComponentsUnavailableResponse extends TaxComponentsResponse
case class TaxComponentsUnexpectedResponse(r: HttpResponse) extends TaxComponentsResponse
case class TaxComponentsErrorResponse(cause: Exception) extends TaxComponentsResponse
@Singleton
class TaiService @Inject()(
  environment: Environment,
  runModeConfiguration: Configuration,
  val simpleHttp: SimpleHttp,
  val metrics: Metrics,
  servicesConfig: ServicesConfig)
    extends HasMetrics {

  val mode: Mode = environment.mode
  lazy val taiUrl = servicesConfig.baseUrl("tai")

  
  def taxComponents(nino: Nino, year: Int)(implicit hc: HeaderCarrier): Future[TaxComponentsResponse] =
    withMetricsTimer("get-tax-components") { t =>
      simpleHttp.get[TaxComponentsResponse](s"$taiUrl/tai/$nino/tax-account/$year/tax-components")(
        onComplete = {
          case r if r.status >= 200 && r.status < 300 =>
            t.completeTimerAndIncrementSuccessCounter()
            TaxComponentsSuccessResponse(TaxComponents.fromJsonTaxComponents(r.json))

          case r if r.status == NOT_FOUND | r.status == BAD_REQUEST =>
            t.completeTimerAndIncrementSuccessCounter()
            Logger.warn("Unable to find tax components from the tai-service")
            TaxComponentsUnavailableResponse

          case r =>
            t.completeTimerAndIncrementFailedCounter()
            Logger.warn(s"Unexpected ${r.status} response getting tax components from the tai-service")
            TaxComponentsUnexpectedResponse(r)
        },
        onError = {
          case e =>
            t.completeTimerAndIncrementFailedCounter()
            Logger.error("Error getting tax components from the tai-service", e)
            TaxComponentsErrorResponse(e)
        }
      )
    }
} 
Example 38
Source File: SimpleHttp.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services.http

import com.google.inject.{Inject, Singleton}
import play.api.libs.json.Writes
import uk.gov.hmrc.http.{HeaderCarrier, HttpReads, HttpResponse}
import uk.gov.hmrc.play.bootstrap.http.HttpClient

import scala.concurrent.{ExecutionContext, Future}

@Singleton
class SimpleHttp @Inject()(http: HttpClient)(implicit executionContext: ExecutionContext) {

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

  def get[T](url: String)(onComplete: HttpResponse => T, onError: Exception => T)(
    implicit hc: HeaderCarrier): Future[T] =
    http.GET[HttpResponse](url) map { response =>
      onComplete(response)
    } recover {
      case e: Exception =>
        onError(e)
    }

  def post[I, T](url: String, body: I)(onComplete: HttpResponse => T, onError: Exception => T)(
    implicit hc: HeaderCarrier,
    w: Writes[I]): Future[T] =
    http.POST[I, HttpResponse](url, body) map { response =>
      onComplete(response)
    } recover {
      case e: Exception =>
        onError(e)
    }

  def put[I, T](url: String, body: I)(onComplete: HttpResponse => T, onError: Exception => T)(
    implicit hc: HeaderCarrier,
    w: Writes[I]): Future[T] =
    http.PUT[I, HttpResponse](url, body) map { response =>
      onComplete(response)
    } recover {
      case e: Exception =>
        onError(e)
    }

} 
Example 39
Source File: SaPartialService.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services.partials

import com.google.inject.{Inject, Singleton}
import com.kenshoo.play.metrics.Metrics
import config.ConfigDecorator
import metrics.HasMetrics
import play.api.Mode.Mode
import play.api.mvc.RequestHeader
import play.api.{Configuration, Environment}
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import uk.gov.hmrc.play.bootstrap.filters.frontend.crypto.SessionCookieCrypto
import uk.gov.hmrc.play.bootstrap.http.HttpClient
import uk.gov.hmrc.play.partials.HtmlPartial
import util.{EnhancedPartialRetriever, Tools}

import scala.concurrent.{ExecutionContext, Future}
@Singleton
class SaPartialService @Inject()(
  environment: Environment,
  runModeConfiguration: Configuration,
  override val http: HttpClient,
  val metrics: Metrics,
  val configDecorator: ConfigDecorator,
  sessionCookieCrypto: SessionCookieCrypto,
  val tools: Tools,
  servicesConfig: ServicesConfig)(implicit executionContext: ExecutionContext)
    extends EnhancedPartialRetriever(sessionCookieCrypto) with HasMetrics {

  val mode: Mode = environment.mode
  private val returnUrl = configDecorator.pertaxFrontendHomeUrl
  private val returnLinkText = configDecorator.saPartialReturnLinkText

  def getSaAccountSummary(implicit request: RequestHeader): Future[HtmlPartial] =
    loadPartial(
      configDecorator.businessTaxAccountService + s"/business-account/partial/sa/account-summary?returnUrl=${tools
        .urlEncode(returnUrl)}&returnLinkText=${tools.urlEncode(returnLinkText)}")

} 
Example 40
Source File: MessageFrontendService.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services.partials

import com.google.inject.{Inject, Singleton}
import com.kenshoo.play.metrics.Metrics
import metrics.HasMetrics
import models.MessageCount
import play.api.Mode.Mode
import play.api.mvc.RequestHeader
import play.api.{Configuration, Environment, Logger}
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import uk.gov.hmrc.play.bootstrap.filters.frontend.crypto.SessionCookieCrypto
import uk.gov.hmrc.play.bootstrap.http.HttpClient
import uk.gov.hmrc.play.partials.HtmlPartial
import util.EnhancedPartialRetriever

import scala.concurrent.{ExecutionContext, Future}

@Singleton
class MessageFrontendService @Inject()(
  environment: Environment,
  runModeConfiguration: Configuration,
  override val http: HttpClient,
  val metrics: Metrics,
  val sessionCookieCrypto: SessionCookieCrypto,
  servicesConfig: ServicesConfig)(implicit executionContext: ExecutionContext)
    extends EnhancedPartialRetriever(sessionCookieCrypto) with HasMetrics {

  val mode: Mode = environment.mode

  lazy val messageFrontendUrl: String = servicesConfig.baseUrl("message-frontend")

  def getMessageListPartial(implicit request: RequestHeader): Future[HtmlPartial] =
    loadPartial(messageFrontendUrl + "/messages")

  def getMessageDetailPartial(messageToken: String)(implicit request: RequestHeader): Future[HtmlPartial] =
    loadPartial(messageFrontendUrl + "/messages/" + messageToken)

  def getMessageInboxLinkPartial(implicit request: RequestHeader): Future[HtmlPartial] =
    loadPartial(
      messageFrontendUrl + "/messages/inbox-link?messagesInboxUrl=" + controllers.routes.MessageController
        .messageList())

  def getUnreadMessageCount(implicit request: RequestHeader): Future[Option[Int]] =
    loadJson(messageFrontendUrl + "/messages/count?read=No").map(_.map(_.count))

  private def loadJson(url: String)(implicit hc: HeaderCarrier): Future[Option[MessageCount]] =
    withMetricsTimer("load-json") { t =>
      http.GET[Option[MessageCount]](url) recover {
        case e =>
          t.completeTimerAndIncrementFailedCounter()
          Logger.warn(s"Failed to load json", e)
          None
      }
    }
} 
Example 41
Source File: PreferencesFrontendPartialService.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services.partials

import com.google.inject.{Inject, Singleton}
import com.kenshoo.play.metrics.Metrics
import metrics.HasMetrics
import play.api.Mode.Mode
import play.api.mvc.RequestHeader
import play.api.{Configuration, Environment}
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import uk.gov.hmrc.play.bootstrap.filters.frontend.crypto.SessionCookieCrypto
import uk.gov.hmrc.play.bootstrap.http.HttpClient
import uk.gov.hmrc.play.partials.HtmlPartial
import util.{EnhancedPartialRetriever, Tools}

import scala.concurrent.{ExecutionContext, Future}

@Singleton
class PreferencesFrontendPartialService @Inject()(
  environment: Environment,
  runModeConfiguration: Configuration,
  val http: HttpClient,
  val metrics: Metrics,
  sessionCookieCrypto: SessionCookieCrypto,
  val tools: Tools,
  servicesConfig: ServicesConfig)(implicit executionContext: ExecutionContext)
    extends EnhancedPartialRetriever(sessionCookieCrypto) with HasMetrics {

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

  def getManagePreferencesPartial(returnUrl: String, returnLinkText: String)(
    implicit request: RequestHeader): Future[HtmlPartial] =
    loadPartial(s"$preferencesFrontendUrl/paperless/manage?returnUrl=${tools
      .encryptAndEncode(returnUrl)}&returnLinkText=${tools.encryptAndEncode(returnLinkText)}")

} 
Example 42
Source File: FormPartialService.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services.partials

import com.google.inject.{Inject, Singleton}
import com.kenshoo.play.metrics.Metrics
import config.ConfigDecorator
import metrics.HasMetrics
import play.api.Mode.Mode
import play.api.mvc.RequestHeader
import play.api.{Configuration, Environment}
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import uk.gov.hmrc.play.bootstrap.filters.frontend.crypto.SessionCookieCrypto
import uk.gov.hmrc.play.bootstrap.http.HttpClient
import uk.gov.hmrc.play.partials.HtmlPartial
import util.EnhancedPartialRetriever

import scala.concurrent.{ExecutionContext, Future}

@Singleton
class FormPartialService @Inject()(
  environment: Environment,
  runModeConfiguration: Configuration,
  override val http: HttpClient,
  val metrics: Metrics,
  val configDecorator: ConfigDecorator,
  sessionCookieCrypto: SessionCookieCrypto,
  servicesConfig: ServicesConfig)(implicit executionContext: ExecutionContext)
    extends EnhancedPartialRetriever(sessionCookieCrypto) with HasMetrics {

  val mode: Mode = environment.mode
  def getNationalInsurancePartial(implicit request: RequestHeader): Future[HtmlPartial] =
    loadPartial(configDecorator.nationalInsuranceFormPartialLinkUrl)

  def getSelfAssessmentPartial(implicit request: RequestHeader): Future[HtmlPartial] =
    loadPartial(configDecorator.selfAssessmentFormPartialLinkUrl)

} 
Example 43
Source File: NinoDisplayService.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import com.google.inject.{Inject, Singleton}
import config.ConfigDecorator
import controllers.auth.requests.UserRequest
import uk.gov.hmrc.domain.Nino
import uk.gov.hmrc.http.HeaderCarrier

import scala.concurrent.{ExecutionContext, Future}



@Singleton
class NinoDisplayService @Inject()(configDecorator: ConfigDecorator, citizenDetailsService: CitizenDetailsService)(
  implicit ec: ExecutionContext) {

  def getNino(implicit request: UserRequest[_], hc: HeaderCarrier): Future[Option[Nino]] =
    if (configDecorator.getNinoFromCID) {
      request.nino match {
        case Some(nino) =>
          for {
            result <- citizenDetailsService.personDetails(nino)
          } yield {
            result match {
              case PersonDetailsSuccessResponse(personDetails) => personDetails.person.nino
              case _                                           => None
            }
          }
        case _ => Future.successful(None)
      }
    } else {
      Future.successful(request.nino)
    }
} 
Example 44
Source File: PersonalDetailsCardGenerator.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.controllershelpers

import config.ConfigDecorator
import controllers.auth.requests.UserRequest
import com.google.inject.{Inject, Singleton}
import models.{AddressJourneyTTLModel, EditCorrespondenceAddress, EditPrimaryAddress, EditSoleAddress}
import play.twirl.api.{Html, HtmlFormat}
import uk.gov.hmrc.domain.Nino
import views.html.cards.personaldetails._

@Singleton
class PersonalDetailsCardGenerator @Inject()(
  val configDecorator: ConfigDecorator,
  val countryHelper: CountryHelper,
  mainAddress: MainAddressView,
  postalAddress: PostalAddressView,
  nationalInsurance: NationalInsuranceView,
  changeName: ChangeNameView
) {

  def getPersonalDetailsCards(changedAddressIndicator: List[AddressJourneyTTLModel], ninoToDisplay: Option[Nino])(
    implicit request: UserRequest[_],
    configDecorator: ConfigDecorator,
    messages: play.api.i18n.Messages): Seq[Html] = {

    val optionalEditAddress = changedAddressIndicator.map(y => y.editedAddress)

    val mainAddressChangeIndicator = optionalEditAddress.exists(_.isInstanceOf[EditSoleAddress]) || optionalEditAddress
      .exists(_.isInstanceOf[EditPrimaryAddress])
    val correspondenceAddressChangeIndicator =
      optionalEditAddress.exists(_.isInstanceOf[EditCorrespondenceAddress])

    List(
      getChangeNameCard(),
      getMainAddressCard(mainAddressChangeIndicator),
      getPostalAddressCard(correspondenceAddressChangeIndicator),
      getNationalInsuranceCard(ninoToDisplay)
    ).flatten
  }

  private def getPersonDetails()(implicit request: UserRequest[_]) =
    request.personDetails

  def hasCorrespondenceAddress()(implicit request: UserRequest[_]): Boolean = {
    val cAdd = getPersonDetails.flatMap(_.correspondenceAddress)
    cAdd.isDefined
  }

  def getMainAddressCard(isLocked: Boolean)(
    implicit request: UserRequest[_],
    messages: play.api.i18n.Messages): Option[HtmlFormat.Appendable] =
    getPersonDetails match {
      case Some(personDetails) =>
        Some(
          mainAddress(
            personDetails = personDetails,
            taxCreditsEnabled = configDecorator.taxCreditsEnabled,
            hasCorrespondenceAddress = hasCorrespondenceAddress,
            isLocked = isLocked,
            countryHelper.excludedCountries
          ))
      case _ => None
    }

  def getPostalAddressCard(isLocked: Boolean)(
    implicit request: UserRequest[_],
    messages: play.api.i18n.Messages): Option[HtmlFormat.Appendable] =
    getPersonDetails match {
      case Some(personDetails) =>
        hasCorrespondenceAddress match {
          case true if !personDetails.correspondenceAddress.exists(_.isWelshLanguageUnit) =>
            Some(
              postalAddress(
                personDetails = personDetails,
                isLocked = isLocked,
                countryHelper.excludedCountries,
                configDecorator.closePostalAddressEnabled))
          case _ => None
        }
      case _ => None
    }

  def getNationalInsuranceCard(ninoToDisplay: Option[Nino])(
    implicit request: UserRequest[_],
    messages: play.api.i18n.Messages): Option[HtmlFormat.Appendable] =
    ninoToDisplay.map(n => nationalInsurance(n))

  def getChangeNameCard()(
    implicit request: UserRequest[_],
    configDecorator: ConfigDecorator,
    messages: play.api.i18n.Messages): Option[HtmlFormat.Appendable] =
    request.name.map(_ => changeName())
} 
Example 45
Source File: PasswordInfoDAOSlickImplementation.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.identities.daos

import com.dataengi.crm.identities.slick.queries.Queries
import com.dataengi.crm.identities.slick.tables.credentionals.{LoginInfoTableDescription, PasswordInfoTableDescription}
import com.google.inject.{Inject, Singleton}
import com.mohiva.play.silhouette.api.LoginInfo
import com.mohiva.play.silhouette.api.util.PasswordInfo
import play.api.db.slick.DatabaseConfigProvider

import scala.concurrent.{ExecutionContext, Future}

@Singleton
class PasswordInfoDAOSlickImplementation @Inject()(protected val dbConfigProvider: DatabaseConfigProvider,
                                                   implicit val executionContext: ExecutionContext)
    extends PasswordInfoDAO
    with PasswordInfoTableDescription
    with LoginInfoTableDescription
    with PasswordInfoDAOQueries {

  import profile.api._

  
  def remove(loginInfo: LoginInfo): Future[Unit] =
    db.run(passwordInfoSubQuery(loginInfo).delete).map(_ => ())
}

trait PasswordInfoDAOQueries extends Queries with LoginInfoTableDescription with PasswordInfoTableDescription {
  implicit val executionContext: ExecutionContext

  import profile.api._

  def loginInfoQuery(loginInfo: LoginInfo) = {
    LoginInfoTableQuery.filter { rawLoginInfo =>
      val providerId  = rawLoginInfo.providerID === loginInfo.providerID
      val providerKey = rawLoginInfo.providerKey === loginInfo.providerKey
      providerId && providerKey
    }
  }

  protected def passwordInfoQuery(loginInfo: LoginInfo) =
    for {
      rawLoginInfo    <- loginInfoQuery(loginInfo)
      rawPasswordInfo <- PasswordInfoTableQuery if rawPasswordInfo.loginInfoId === rawLoginInfo.id
    } yield rawPasswordInfo

  // Use subquery workaround instead of join to get authinfo because slick only supports selecting
  // from a single table for update/delete queries (https://github.com/slick/slick/issues/684).
  protected def passwordInfoSubQuery(loginInfo: LoginInfo) =
    PasswordInfoTableQuery.filter(_.loginInfoId in loginInfoQuery(loginInfo).map(_.id))

  protected def addAction(loginInfo: LoginInfo, authInfo: PasswordInfo) =
    loginInfoQuery(loginInfo).result.head.flatMap { rawLoginInfo =>
      PasswordInfoTableQuery +=
        PasswordInfoRaw(authInfo.hasher, authInfo.password, authInfo.salt, rawLoginInfo.id)
    }.transactionally

  protected def updateAction(loginInfo: LoginInfo, authInfo: PasswordInfo) =
    passwordInfoSubQuery(loginInfo)
      .map(rawPasswordInfo => (rawPasswordInfo.hasher, rawPasswordInfo.password, rawPasswordInfo.salt))
      .update((authInfo.hasher, authInfo.password, authInfo.salt))

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import com.google.inject.{ImplementedBy, Inject, Singleton}
import play.api.Mode
import play.api.libs.ws.{WSClient, WSResponse}
import play.api.{Configuration, Environment}
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig

import scala.concurrent.Future

@ImplementedBy(classOf[FrontendPdfGeneratorConnector])
trait PdfGeneratorConnector {
  val serviceURL: String
  def getWsClient: WSClient

  def generatePdf(html: String): Future[WSResponse] =
    getWsClient.url(serviceURL).post(Map("html" -> Seq(html)))
}

@Singleton
class FrontendPdfGeneratorConnector @Inject()(
  environment: Environment,
  runModeConfiguration: Configuration,
  wsClient: WSClient,
  servicesConfig: ServicesConfig)
    extends PdfGeneratorConnector {
  val mode: Mode = environment.mode
  val pdfServiceUrl: String = servicesConfig.baseUrl("pdf-generator-service")
  val serviceURL = pdfServiceUrl + "/pdf-generator-service/generate"

  override def getWsClient: WSClient = wsClient
} 
Example 48
Source File: ContactsBooksService.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.contacts.services

import cats.instances.all._
import com.dataengi.crm.contacts.models.ContactsBook
import com.dataengi.crm.contacts.repositories.ContactsBooksRepository
import com.google.inject.{Inject, Singleton}
import com.dataengi.crm.common.context.types._
import org.joda.time.DateTime

import scala.concurrent.ExecutionContext

trait ContactsBooksService {

  def update(value: ContactsBook): EmptyOr

  def get(id: Long): Or[ContactsBook]

  def findByOwner(userId: Long): Or[ContactsBook]

  def create(userId: Long): Or[ContactsBook]

}

@Singleton
class ContactsBooksServiceImplementation @Inject()(contactsBookRepository: ContactsBooksRepository,
                                                   implicit val executionContext: ExecutionContext)
    extends ContactsBooksService {

  override def findByOwner(userId: Long): Or[ContactsBook] =
    for {
      contactsBookOpt <- contactsBookRepository.findByOwner(userId)
      contactsBook    <- getOrCreate(contactsBookOpt, userId)
    } yield contactsBook

  override def create(userId: Long): Or[ContactsBook] = {
    val contactsBook = ContactsBook(ownerId = userId, createDate = DateTime.now().getMillis)
    contactsBookRepository.add(contactsBook).map(id => contactsBook.copy(id = Some(id)))
  }

  private def getOrCreate(contactBookOption: Option[ContactsBook], userId: Long) = contactBookOption match {
    case Some(contactsBook) => contactsBook.toOr
    case None               => create(userId)
  }

  override def get(id: Long): Or[ContactsBook] =
    for {
      contactsBook <- contactsBookRepository.get(id)
    } yield contactsBook

  override def update(contact: ContactsBook): EmptyOr = contactsBookRepository.update(contact.id.get, contact)

} 
Example 49
Source File: CompaniesConfiguration.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.configurations

import com.google.inject.{Inject, Singleton}
import com.dataengi.crm.common.extensions.awaits._
import com.dataengi.crm.common.extensions.logging._
import play.api.{Configuration, Logger}
import scalty.types._
import cats.instances.all._
import com.dataengi.crm.identities.services.CompaniesService

import scala.concurrent.ExecutionContext

@Singleton
class CompaniesConfiguration @Inject()(configuration: Configuration, companiesService: CompaniesService, implicit val executionContext: ExecutionContext) {

  def loadRootCompany: Unit = {
    val addRootCompanyOr = for {
      rootCompanyOpt <- companiesService.findOption(CompaniesConfiguration.RootCompanyName)
      rootCompanyId <- rootCompanyOpt match {
        case Some(company) =>
          Logger.info(s"[com.dataengi.crm.identities-initiation][load-root-company] $company already exists")
          company.id.get.toOr
        case None =>
          Logger.info(s"[com.dataengi.crm.identities-initiation][load-root-company] creating ${CompaniesConfiguration.RootCompanyName}")
          companiesService.create(CompaniesConfiguration.RootCompanyName)

      }
    } yield rootCompanyId

    val addRootCompanyResult = addRootCompanyOr.await()
    Logger.info(s"[com.dataengi.crm.identities-initiation][load-root-company] ${addRootCompanyResult.logResult}")
  }

}

object CompaniesConfiguration {
  val RootCompanyName = "ROOT_COMPANY"
} 
Example 50
Source File: SilhouetteConfiguration.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.configurations

import com.google.inject.{Inject, Singleton}
import com.mohiva.play.silhouette.api.util.Clock
import com.typesafe.config.Config
import play.api.Configuration
import net.ceedubs.ficus.Ficus._
import com.mohiva.play.silhouette.api.Authenticator.Implicits._

import scala.concurrent.duration.FiniteDuration

@Singleton
class SilhouetteConfiguration @Inject()(configuration: Configuration, clock: Clock) {

  val underlying: Config = configuration.underlying

  def authenticatorExpiry: FiniteDuration =
    underlying.as[FiniteDuration]("silhouette.authenticator.rememberMe.authenticatorExpiry")
  def authenticatorIdleTimeout: Option[FiniteDuration] =
    underlying.getAs[FiniteDuration]("silhouette.authenticator.rememberMe.authenticatorIdleTimeout")

  def recoverPasswordTimeout: Long =
    (clock.now + underlying.as[FiniteDuration]("silhouette.authenticator.recoverPasswordExpiry")).getMillis

} 
Example 51
Source File: RootConfiguration.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.configurations

import com.dataengi.crm.identities.models.{Company, Role, User}
import com.google.inject.{Inject, Singleton}
import com.mohiva.play.silhouette.api.LoginInfo
import com.mohiva.play.silhouette.api.util.{PasswordHasher}
import play.api.Configuration

@Singleton
class RootConfiguration @Inject()(configuration: Configuration, passwordHasher: PasswordHasher) {

  private val rootEmail = configuration.getOptional[String]("crm.users.root.email").getOrElse("admin")
  val rootPassword      = configuration.getOptional[String]("crm.users.root.password").getOrElse("admin")
  val rootLoginInfo     = LoginInfo("credentials", rootEmail)
  val rootPasswordInfo  = passwordHasher.hash(rootPassword)

  def createRootUser(rootCompany: Company, rootRole: Role): User = User(
    loginInfo = rootLoginInfo,
    role = rootRole,
    company = rootCompany
  )

} 
Example 52
Source File: InitiateProfilesTables.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.profiles.slick

import com.dataengi.crm.identities.slick.tables.TablesInitiation
import com.dataengi.crm.profiles.slick.tables.ProfilesTableDescription
import com.google.inject.{Inject, Singleton}
import play.api.Configuration
import play.api.db.slick.DatabaseConfigProvider

import scala.collection.immutable.List
import scala.concurrent.ExecutionContext

@Singleton
class InitiateProfilesTables @Inject()(val configuration: Configuration,
                                       protected val dbConfigProvider: DatabaseConfigProvider,
                                       implicit val executionContext: ExecutionContext)
    extends ProfilesTableDescription
    with TablesInitiation {

  val All = List(Profiles)
  createTables(All)
  printMigrationDDL(All)

} 
Example 53
Source File: AvatarService.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.profiles.services

import java.net.URLEncoder._
import java.security.MessageDigest

import cats.instances.all._
import com.dataengi.crm.profiles.services.errors.ProfileServiceErrors
import com.google.inject.{Inject, Singleton}
import com.dataengi.crm.common.context.types._
import play.api.libs.ws.WSClient

import scala.concurrent.ExecutionContext

trait AvatarService {

  def retrieveURL(email: String): Or[Option[String]]

}

@Singleton
class AvatarServiceImplementation @Inject()(wSClient: WSClient,
                                            implicit val executionContext: ExecutionContext,
                                            settings: GravatarServiceSettings)
    extends AvatarService {

  override def retrieveURL(email: String): Or[Option[String]] = hash(email) match {
    case Some(hash) =>
      val url = settings.getUrl(hash)
      gerAvatarUrl(url)
    case None => ProfileServiceErrors.avatarCreatingUrlError(email).toErrorOr
  }

  private def gerAvatarUrl(url: String): Or[Option[String]] =
    wSClient
      .url(url)
      .get()
      .toOr
      .flatMap(response =>
        response.status match {
          case 200  => Option(url).toOr
          case code => ProfileServiceErrors.avatarReceivingError(code, url).toErrorOr
      })

  private def hash(email: String): Option[String] = {
    val s = email.trim.toLowerCase
    if (s.length > 0) {
      Some(MessageDigest.getInstance(GravatarService.MD5).digest(s.getBytes).map("%02x".format(_)).mkString)
    } else {
      None
    }
  }

}

object GravatarService {
  val InsecureURL = "http://www.gravatar.com/avatar/%s%s"
  val SecureURL   = "https://secure.gravatar.com/avatar/%s%s"
  val MD5         = "MD5"
}

case class GravatarServiceSettings(secure: Boolean = true, params: Map[String, String] = Map("d" -> "identicon")) {

  def getUrl(hash: String): String = {
    val encodedParams = params.map { p =>
      encode(p._1, "UTF-8") + "=" + encode(p._2, "UTF-8")
    }
    (if (secure) GravatarService.SecureURL else GravatarService.InsecureURL)
      .format(hash, encodedParams.mkString("?", "&", ""))
  }

} 
Example 54
Source File: ProfilesService.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.profiles.services

import cats.instances.all._
import com.dataengi.crm.profiles.controllers.data.{GetUsersProfilesData, UpdateProfileData}
import com.dataengi.crm.profiles.models.Profile
import com.dataengi.crm.profiles.repositories.ProfilesRepository
import com.dataengi.crm.profiles.services.errors.ProfileServiceErrors
import com.google.inject.{Inject, Singleton}
import com.dataengi.crm.common.context.types._
import com.dataengi.crm.identities.models.User
import com.dataengi.crm.identities.services.UsersService
import scalty.types.or
import cats.syntax.traverse._

import scala.concurrent.ExecutionContext

trait ProfilesService {

  def get(body: GetUsersProfilesData): Or[List[Profile]]

  def get(user: User): Or[Profile]

  def getOption(userId: Long): Or[Option[Profile]]

  def update(updateProfileData: UpdateProfileData, user: User): EmptyOr

  def existProfileWithNickname(nickname: String): EmptyOr

}

@Singleton
class ProfilesServiceImplementation @Inject()(profilesRepository: ProfilesRepository,
                                              avatarService: AvatarService,
                                              usersService: UsersService,
                                              implicit val executionContext: ExecutionContext)
    extends ProfilesService {

  override def getOption(userId: Long) = profilesRepository.findByUserId(userId)

  override def update(data: UpdateProfileData, user: User): EmptyOr =
    for {
      profile             <- get(user)
      nicknameCheckResult <- existProfileWithNickname(data.nickname, profile.nickname)
      updateResult <- profilesRepository.update(
        profile.id.get,
        profile
          .copy(nickname = data.nickname, firstName = data.firstName, lastName = data.lastName, avatarUrl = data.avatarUrl))
    } yield updateResult

  private def existProfileWithNickname(newNickname: String, currentNickname: String): EmptyOr =
    if (newNickname != currentNickname) {
      existProfileWithNickname(newNickname)
    } else {
      currentNickname.toEmptyOr
    }

  private def checkNickname(profileOpt: Option[Profile]): EmptyOr = profileOpt match {
    case Some(profile) => ProfileServiceErrors.profileWithNicknameAlreadyExist(profile.nickname).toErrorOr
    case None          => or.EMPTY_OR
  }

  override def get(user: User): Or[Profile] = getOption(user.id.get).flatMap {
    case Some(profile) => profile.toOr
    case None          => createForUser(user)
  }

  private def createForUser(user: User): Or[Profile] =
    for {
      avatarUrlOpt <- avatarService.retrieveURL(user.loginInfo.providerKey)
      profile = Profile(userId = user.id.get,
                        nickname = user.loginInfo.providerKey,
                        email = user.loginInfo.providerKey,
                        avatarUrl = avatarUrlOpt)
      profileId <- profilesRepository.add(profile)
    } yield profile.copy(id = Some(profileId))

  override def existProfileWithNickname(nickname: String): EmptyOr =
    profilesRepository.findProfileByNickName(nickname).flatMap(checkNickname)

  override def get(data: GetUsersProfilesData): Or[List[Profile]] =
    for {
      profiles <- data.userIds.traverse[Or, Profile](getUserProfile)
    } yield profiles

  private def getUserProfile(userId: Long) = getOption(userId).flatMap {
    case Some(profile) => profile.toOr
    case None          => getDefaultUserProfile(userId)
  }

  private def getDefaultUserProfile(userId: Long) = {
    for {
      user    <- usersService.get(userId)
      profile <- createForUser(user)
    } yield profile
  }

} 
Example 55
Source File: ProfilesController.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.profiles.controllers

import com.dataengi.crm.identities.actions.SecuredFilteredAction
import cats.instances.all._
import com.google.inject.{Inject, Singleton}
import com.mohiva.play.silhouette.api.Silhouette
import com.dataengi.crm.common.context.types._
import com.dataengi.crm.common.controllers.ApplicationController
import play.api.mvc.{AbstractController, ControllerComponents}
import com.dataengi.crm.profiles.formatters.ProfilesFormatter._
import com.dataengi.crm.profiles.services.ProfilesService
import com.dataengi.crm.identities.utils.auth.DefaultEnv

import scala.concurrent.ExecutionContext

@Singleton
class ProfilesController @Inject()(profilesService: ProfilesService,
                                   val silhouette: Silhouette[DefaultEnv],
                                   components: ControllerComponents,
                                   implicit val executionContext: ExecutionContext)
  extends ApplicationController(components) with SecuredFilteredAction {

  def update = SecuredAccessAction.async(parse.json(updateProfileFormatter)) { implicit request =>
    profilesService.update(request.body, request.identity)
  }

  def get = SecuredAccessAction.async { implicit request =>
    profilesService.get(request.identity)
  }

  def getProfilesByUsers = SecuredAccessAction.async(parse.json(getUsersProfilesDataFormatter)) { implicit request =>
    profilesService.get(request.body)
  }

  def checkNickname(nickname: String) = SecuredAccessAction.async { implicit request =>
    profilesService.existProfileWithNickname(nickname)
  }

} 
Example 56
Source File: SilhouetteModule.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.identities.modules

import com.dataengi.crm.configurations.{CompaniesConfiguration, RolesConfiguration, RootConfiguration, SilhouetteConfiguration}
import com.dataengi.crm.identities.actions.{ActionsProvider, ActionsProviderImplementation}
import com.google.inject.name.Named
import com.google.inject.{Provides, Singleton}
import com.mohiva.play.silhouette.api.actions.SecuredErrorHandler
import com.mohiva.play.silhouette.api.crypto.{AuthenticatorEncoder, Crypter, CrypterAuthenticatorEncoder}
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.services._
import com.mohiva.play.silhouette.api.util._
import com.mohiva.play.silhouette.api.{Environment, EventBus, Silhouette, SilhouetteProvider}
import com.mohiva.play.silhouette.crypto.{JcaCrypter, JcaCrypterSettings}
import com.mohiva.play.silhouette.impl.authenticators._
import com.mohiva.play.silhouette.impl.providers._
import com.mohiva.play.silhouette.impl.services._
import net.ceedubs.ficus.readers.EnumerationReader._
import com.mohiva.play.silhouette.impl.util._
import com.mohiva.play.silhouette.password.BCryptPasswordHasher
import com.mohiva.play.silhouette.persistence.daos.DelegableAuthInfoDAO
import com.mohiva.play.silhouette.persistence.repositories.DelegableAuthInfoRepository
import net.ceedubs.ficus.Ficus._
import net.ceedubs.ficus.readers.ArbitraryTypeReader._
import net.codingwell.scalaguice.ScalaModule
import play.api.Configuration
import play.api.libs.ws.WSClient
import com.dataengi.crm.identities.daos._
import com.dataengi.crm.identities.repositories._
import com.dataengi.crm.identities.services._
import com.dataengi.crm.identities.slick.initiation.InitiateTables
import com.dataengi.crm.identities.utils.auth.DefaultEnv

import scala.concurrent.ExecutionContext

class SilhouetteModule extends ScalaModule {

  def configure() = {
    // Initiation ORDER make sense
    bind[InitiateTables].asEagerSingleton()
    bind[IdentitiesInitiation].asEagerSingleton()

    // Silhouette
    bind[SecuredErrorHandler].to[CustomSecuredErrorHandler]
    bind[Silhouette[DefaultEnv]].to[SilhouetteProvider[DefaultEnv]]
    bind[CacheLayer].to[PlayCacheLayer]
    bind[PasswordHasher].toInstance(new BCryptPasswordHasher)
    bind[FingerprintGenerator].toInstance(new DefaultFingerprintGenerator(false))
    bind[EventBus].toInstance(EventBus())
    bind[Clock].toInstance(Clock())

    // Replace this with the bindings to your concrete DAOs
    bind[PasswordInfoDAO].to[PasswordInfoDAOSlickImplementation]
    bind[DelegableAuthInfoDAO[PasswordInfo]].to[PasswordInfoDAO]

    // Repository
    bind[RolesRepository].to[RolesRepositoryImplementation]
    bind[CompaniesRepository].to[CompaniesRepositoryImplementation]
    bind[InvitesRepository].to[InvitesRepositoryImplementation]
    bind[JWTAuthenticatorRepository].to[JWTAuthenticatorCacheRepositoryImplementation]
    bind[UsersRepository].to[UsersRepositoryImplementation]
    bind[RecoverPasswordInfoRepository].to[RecoverPasswordInfoRepositoryImplementation]

    // DAOs
    bind[CompaniesDAO].to[CompaniesSlickDAOImplementation]
    bind[RolesDAO].to[RolesSlickDAOImplementation]
    bind[InvitesDAO].to[InvitesSlickDAOImplementation]
    bind[JWTAuthenticatorDAO].to[JWTAuthenticatorSlickDAOImplementation]
    bind[UsersDAO].to[UsersSlickDAOImplementation]
    bind[RecoverPasswordInfoDAO].to[RecoverPasswordInfoSlickDAOImplementation]

    // Services
    bind[UsersService].to[UsersServiceImplementation]
    bind[CompaniesService].to[CompaniesServiceImplementation]
    bind[RolesService].to[RolesServiceImplementation]
    bind[InvitesService].to[InvitesServiceImplementation]
    bind[AuthenticationService].to[AuthenticationServiceImplementation]
    bind[UsersManagementService].to[UsersManagementServiceImplementation]

    // Actions
    bind[ActionsProvider].to[ActionsProviderImplementation]

    // Configuration
    bind[RolesConfiguration].asEagerSingleton()
    bind[CompaniesConfiguration].asEagerSingleton()
    bind[RootConfiguration].asEagerSingleton()
    bind[SilhouetteConfiguration].asEagerSingleton()

  }

  
  @Provides
  def provideCredentialsProvider(authInfoRepository: AuthInfoRepository,
                                 passwordHasherRegistry: PasswordHasherRegistry,
                                 executionContext: ExecutionContext): CredentialsProvider = {

    new CredentialsProvider(authInfoRepository, passwordHasherRegistry)(executionContext)
  }

} 
Example 57
Source File: IdentitiesInitiation.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.identities.modules

import cats.instances.all._
import com.dataengi.crm.common.context.types._
import com.dataengi.crm.common.extensions.awaits._
import com.dataengi.crm.common.extensions.logging._
import com.dataengi.crm.configurations.{CompaniesConfiguration, RolesConfiguration, RootConfiguration}
import com.google.inject.{Inject, Singleton}
import play.api.Logger
import com.dataengi.crm.identities.daos.PasswordInfoDAO
import com.dataengi.crm.identities.services.{CompaniesService, RolesService}
import com.dataengi.crm.identities.modules.InitiationErrors._
import com.dataengi.crm.identities.repositories.UsersRepository

import scala.concurrent.ExecutionContext

@Singleton
class IdentitiesInitiation @Inject()(usersRepository: UsersRepository,
                                     passwordInfoDAO: PasswordInfoDAO,
                                     companiesService: CompaniesService,
                                     rolesService: RolesService,
                                     rolesConfiguration: RolesConfiguration,
                                     companiesConfiguration: CompaniesConfiguration,
                                     rootConfiguration: RootConfiguration,
                                     implicit val executionContext: ExecutionContext) {

  companiesConfiguration.loadRootCompany
  rolesConfiguration.loadBaseRoles

  val addRootUserResult: Or[Long] = for {
    rootCompany <- companiesService.findOption(CompaniesConfiguration.RootCompanyName).toOrWithLeft(RootCompanyNotFound)
    rootRole    <- rolesService.findOption(RolesConfiguration.Root).toOrWithLeft(RootRoleNotFound)
    rootUserOpt <- usersRepository.find(rootConfiguration.rootLoginInfo)
    saveRootUserResult <- rootUserOpt match {
      case Some(user) =>
        Logger.info(s"[com.dataengi.crm.identities-initiation][add-root] updating root user ${rootConfiguration.rootLoginInfo}")
        usersRepository
          .update(user.id.get, rootConfiguration.createRootUser(rootCompany, rootRole))
          .map(result => user.id.get)
      case None =>
        Logger.info(s"[com.dataengi.crm.identities-initiation][add-root] creating root user ${rootConfiguration.rootLoginInfo}")
        usersRepository.add(rootConfiguration.createRootUser(rootCompany, rootRole))
    }
    savePasswordInfoResult <- passwordInfoDAO.add(rootConfiguration.rootLoginInfo, rootConfiguration.rootPasswordInfo).toOr
  } yield saveRootUserResult

  val result = addRootUserResult.await()

  Logger.info(s"[com.dataengi.crm.identities-initiation][add-root] ${result.logResult}")

} 
Example 58
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))

}