sss.openstar.controller.ApiHostHelper.scala Maven / Gradle / Ivy
package sss.openstar.controller
import sss.openstar.identityledger.IdentityServiceQuery
import sss.openstar.ui.rpc.{ApiToken, Result, ok, problem}
import sss.openstar.wallet.UnlockedWallet
import sss.openstar.{Currency, UniqueNodeIdentifier}
import scala.util.{Failure, Success}
class ApiHostHelper[C <: Currency](hostWallet: UnlockedWallet[C])(implicit identityServiceQuery: IdentityServiceQuery) {
private def isProxyAuthorized(proxyName: UniqueNodeIdentifier): Boolean = true
private def amountForServiceCall(
proxyName: UniqueNodeIdentifier,
clientName: UniqueNodeIdentifier): Option[Option[Long]] =
Some(Some(1))
private def debitByProxy(from: ApiToken,
to: ApiToken): Result[Boolean] = {
if (!isProxyAuthorized(to.name)) {
problem(s"Proxy ${to.name} not authorized")
} else {
val serviceSecretGood = IdentityAttributes.validateSecret(to.name, to.secret)
val clientSecretGood = IdentityAttributes.validateSecret(from.name, from.secret)
if (serviceSecretGood && clientSecretGood) {
amountForServiceCall(to.name, from.name) match {
case None =>
problem(s"Client not ${from.name} not authorized")
case Some(Some(amount)) =>
hostWallet.transferBetweenClients(amount, from.name, to.name) match {
case Failure(exception) => problem(exception)
case Success(_) => ok()
}
case Some(None) => ok() //client plays for free
}
} else {
problem(s"Secret for ${to.name} or ${from.name} is invalid")
}
}
}
def charge(proxy: ApiToken, client: ApiToken): Result[Boolean] = debitByProxy(client, proxy)
def refund(proxy: ApiToken, client: ApiToken): Result[Boolean] = debitByProxy(proxy, client)
}