Scala: how to get the result of the future

I have a method that returns Futurelike this ...

def isTokenExpired(token: String): Future[Boolean] = {
  ...
}

... and then I have another method that calls isTokenExpired, which returns Booleanas follows:

def isExpired(token: String): Boolean = {
  var result = true
  isTokenExpired(token).onComplete {
    case Success(r) => result = r
    case Failure(_) => result = true
  }
  result
}

Is there a better way to write a method isExpired?

EDIT

At the request of EECOLOR, let me provide you more detailed information. For my Play application, I implemented a JSON Web Token (jwt) authorization mechanism. All claims are contained in jwt, except the expiration time, which is stored in the MongoDB collection. The following is a brief description of what the class looks like Token:

class Token {
  ...

  def id: String = { ... }
  def issueTime: LocalDateTime = { ... }
  def issuer: String = { ... }
  ...
  def isValid: Boolean = { ... }
  def isExpired: Boolean = { /* uses ReactiveMongo to access MongoDB  */ }
}

, jwt , . isExpired ReactiveMongo, Future. , jwt Action :

class SecuredAction[T <: Controller] private(private val methodName: String)
  extends ActionBuilder[ApiRequest] {

  ...

  def invokeBlock[A](request: Request[A], block: (ApiRequest[A]) => Future[SimpleResult]) = {{
    request.headers.get(HeaderNames.AUTHORIZATION) match {
      case Some(header) => s"""$AuthType (.*)""".r.unapplySeq(header).map(_.head.trim)
      case _ => None
    }} match {
      case Some(tokenString) => {
        val token = Token(tokenString)

        if (!token.isValid) {
          Logger.warn(s"request ${request.uri} not authorized: token ${token.id} has been tampered")
          Future.successful(Unauthorized(AuthErrors.authenticationViolated(token.subject)(request).asJson))
        } else if (token.isExpired) {
          Logger.debug(s"request ${request.uri} not authorized: token ${token.id} has expired")
          Future.successful(Unauthorized(AuthErrors.authenticationExpired(token.subject)(request).asJson))
        } else if (!isAuthorized(token)) {
          Logger.info(s"request ${request.uri} not authorized: required claims not defined for account ${token.subject}")
          Future.successful(Forbidden(AuthErrors.requestNotAuthorized(token.subject)(request).asJson))
        } else {
          Logger.debug(s"request ${request.uri} authorized for account ${token.subject}")
          block(new ApiRequest(token, request))
        }
      }
      case _ => {
        Logger.debug(s"request ${request.uri} not authenticated")
        Future.successful(Unauthorized(
          AuthErrors.requestNotAuthenticated()(request).asJson
        ).withHeaders(HeaderNames.WWW_AUTHENTICATE -> AuthType))
      }
    }
  }

, Future[play.mvc.results.Result], Future[Boolean], isExpired, Future.map. ?

+4
2

, , , . ( ) true, result.

- :

isTokenExpired(token).map { result =>
   // do stuff
}

, "", Future http "" Future[SimpleResult]. Play , Future.

Future , Future .

, , :

Await.result(someFuture, 5.seconds)

Edit

, , , Future[Token]. . .

, , , , .

class TokenService(connection: MongoConnection) {

  def tokenFor(tokenString: String): Future[Token] = ???
}

class SecuredAction(tokenService: TokenService) extends 
  ActionBuilder[ApiRequest] {

  import play.api.libs.concurrent.Execution.Implicits._

  def invokeBlock[A](request: Request[A], block: (ApiRequest[A]) => Future[SimpleResult]) =
    extractTokenFrom(request) match {
      case Some(tokenString) => {

        tokenService.tokenFor(tokenString) flatMap {
          case token if (!token.isValid) =>
            Logger.warn(s"request ${request.uri} not authorized: token ${token.id} has been tampered")
            Future.successful(Unauthorized(AuthErrors.authenticationViolated(token.subject)(request).asJson))
          case token if (token.isExpired) =>
            Logger.debug(s"request ${request.uri} not authorized: token ${token.id} has expired")
            Future.successful(Unauthorized(AuthErrors.authenticationExpired(token.subject)(request).asJson))
          case token if (!token.isAuthorized) =>
            Logger.info(s"request ${request.uri} not authorized: required claims not defined for account ${token.subject}")
            Future.successful(Forbidden(AuthErrors.requestNotAuthorized(token.subject)(request).asJson))
          case token =>
            Logger.debug(s"request ${request.uri} authorized for account ${token.subject}")
            block(new ApiRequest(token, request))
        }
      }
      case _ =>
        Logger.debug(s"request ${request.uri} not authenticated")
        Future.successful(Unauthorized(
          AuthErrors.requestNotAuthenticated()(request).asJson).withHeaders(HeaderNames.WWW_AUTHENTICATE -> AuthType))
    }

  val AuthType = "MyAuthType"
  val TokenHeader = s"""$AuthType (.*)""".r

  def extractTokenFrom(request: RequestHeader) = {
    val authorizationHeader = request.headers.get(HeaderNames.AUTHORIZATION)
    authorizationHeader flatMap {
      case TokenHeader(token) => Some(token.trim)
      case _ => None
    }
  }
}
+5

:

Await.result(futureResult, Duration.Inf)

a Future[Value] Value, .

...

// wait forever to make future current (?)

. ScalaTest. @EECOLOR.

0

Source: https://habr.com/ru/post/1535282/


All Articles