0

我正在基于这个Scala Play Authentication example 实现身份验证。

因此,我使用以下内容ActionBuilder来构建一个UserAction.

UserAction.scala

class UserRequest[A](val user: Option[Admin], request: Request[A]) extends WrappedRequest[A](request)

class UserAction @Inject()(adminService: AdminService, parser: BodyParsers.Default)(implicit val executionContext: ExecutionContext)
  extends ActionBuilder[UserRequest, AnyContent]
    with ActionTransformer[Request, UserRequest] {

  def transform[A](request: Request[A]) = Future.successful {

    val sessionTokenOpt = request.session.get("sessionToken")

    val user = sessionTokenOpt
      .flatMap(token => Sessions.getSession(token))
      .filter(_.expiration.isAfter(LocalDateTime.now(ZoneOffset.UTC)))
      .map(_.email)
       // Signature: getAdminByEmail(email: String): Future[Option[Admin]]
      .flatMap(adminService.getAdminByEmail) // <- Extract Future here

    // The user has to be Option[Admin] but is Future[Option[Admin]]
    // because of adminService.getAdminByEmail
    new UserRequest(user, request)
  }
}

由于第25 行的示例实现没有返回 Future,因为没有包含数据库设置,所以我收到以下错误:

type mismatch;
 found   : scala.concurrent.Future[Option[models.Tables.Admin]]
 required: Option[?]

因为我是 scala 的新手,所以我现在不知道如何提取 Future。如何处理 Future 结果以确保我们返回一个Option[Admin]

4

1 回答 1

0

我自己修好了。我只是将电子邮件和获取分成两个不同的部分,Future并将email match.

class UserAction @Inject()(adminService: AdminService, val parser: BodyParsers.Default)(implicit val executionContext: ExecutionContext)
  extends ActionBuilder[UserRequest, AnyContent]
    with ActionTransformer[Request, UserRequest] {

  def transform[A](request: Request[A]) : Future[UserRequest[A]] = {
    val sessionTokenOpt = request.session.get("sessionToken")

    val email = sessionTokenOpt
      .flatMap(token => Sessions.getSession(token))
      .filter(_.expiration.isAfter(LocalDateTime.now(ZoneOffset.UTC)))
      .map(_.email)

    email match {
      case Some(value) =>
        adminService.getAdminByEmail(value).map(a => new UserRequest(a, request))
      case None =>
        Future { new UserRequest(None, request) }
    }
  }
}
于 2021-01-20T10:42:38.703 回答