score:0

Here is what I ended up doing. it works but I'd like to see feedback if there is more idiomatic Scala way:

        /** Contains the security token, extracted from the RequestHeader */
    case class AuthenticatedRequest[A](user: models.User, request: Request[A]) extends WrappedRequest[A](request)

   case class AuthorizedAction[A](action: Action[A]) extends Action[A] {
      lazy val parser = action.parser
      def apply(request: Request[A]): Future[SimpleResult] = {
        userTokenForm.bindFromRequest()(request).fold(
                formWithErrors => {
                    resolve(Results.Unauthorized(formWithErrors.errorsAsJson))
                },
                userData => {
                    models.UsersDAO.findByToken(userData.token) map { user=>
                      action(AuthenticatedRequest(user, request))
                    } getOrElse {
                      resolve(Results.Unauthorized("Token matched no one."))
                    }
                }
                )
      }
    }


   class RequestWithUser[A](val user: models.User, request: Request[A]) extends WrappedRequest[A](request)

   case class UserAction[A](userId: Long, action: Action[A]) extends Action[A] {
      lazy val parser = action.parser
      def apply(request: Request[A]): Future[SimpleResult] = {
        models.UsersDAO.findById(userId).map { user =>
          action(new RequestWithUser(user, request))
        } getOrElse {
          Future.successful(NotFound)
        }
      }
    }

   def UserHasPermission[A](userId: Long)  = new  ActionBuilder[AuthenticatedRequest] {
      def invokeBlock[A](request: Request[A], block: (AuthenticatedRequest[A]) => Future[SimpleResult]) = {
        request match {
          case req: AuthenticatedRequest[A] => {
            {
            for (
                authUserId <- req.user.id
                if authUserId == userId
                ) yield block(req)
            } getOrElse Future.successful(Unauthorized)
          }
          case _ => Future.successful(BadRequest)
        }
      }
      override def composeAction[A](action: Action[A]) = UserAction(userId, AuthorizedAction(action) )
    }

Related Query

More Query from same tag