• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala Result类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中play.api.mvc.Result的典型用法代码示例。如果您正苦于以下问题:Scala Result类的具体用法?Scala Result怎么用?Scala Result使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Result类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: ResultMessage

//设置package包名称以及导入依赖的类
package services

import play.api.libs.json.{JsValue, Json}

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import play.api.mvc.Results.{Ok, BadRequest}
import play.api.mvc.Result

object ResultMessage {
  val MESSAGE_INVALID_JSON = "Invalid json"
  val MESSAGE_DB_ERROR = "DB error"
  val MESSAGE_API_NOT_FOUND = "Api is not found"
  val MESSAGE_SOME_IDS_HAVE_NOT_REGISTERED = "Some ids have not registered"
  val MESSAGE_VALUE_IS_NOT_FOUND = (value: String) => s"$value is not found"
  val MESSAGE_TABLE_REPOSITORY_ERROR = (message: String) => s"$message"

  case class ErrorMessage(json: JsValue)

  private val keyErrorMessage = "errorMessage"

  sealed trait ApiResult {
    def getAsFuture: Future[Result]
  }

  case class ApiSuccess(future: Future[String]) extends ApiResult {
    override def getAsFuture: Future[Result] = future.map{Ok(_)}
  }

  case class ApiError(errorMessage: ErrorMessage) extends ApiResult {
    override def getAsFuture: Future[Result] = Future[Result]{BadRequest(errorMessage.json.toString)}
  }

  def generateError(errorMessage: String): ErrorMessage = {
    ErrorMessage(
      Json.obj(keyErrorMessage -> errorMessage)
    )
  }
} 
开发者ID:misoton665,项目名称:ibuki,代码行数:40,代码来源:ResultMessage.scala


示例2: onServerError

//设置package包名称以及导入依赖的类
package org.danielnixon.progressive.play

import play.api.Logger
import play.api.http.HttpErrorHandler
import play.api.http.HttpVerbs.{ GET, POST }
import play.api.http.Status.INTERNAL_SERVER_ERROR
import play.api.mvc.Results._
import play.api.mvc.{ Call, RequestHeader, Result }
import org.danielnixon.progressive.play.extensions.{ RequestHeaderWrapper, ResultWrapper }
import org.danielnixon.progressive.play.Results.redirectToRefererOrElse
import org.danielnixon.progressive.shared.api.AjaxResponse
import play.twirl.api.HtmlFormat

import scalaz.Scalaz._
import scala.concurrent.Future


  def onServerError(request: RequestHeader, exception: Throwable): Future[Result] = {
    val errorMessage = serverErrorToErrorMessage(request, exception)
    Logger.error(errorMessage, exception)
    errorResponse(request, errorMessage, INTERNAL_SERVER_ERROR)
  }

  private def errorResponse(request: RequestHeader, errorMessage: String, statusCode: Int): Future[Result] = {
    val status = Status(statusCode)

    Future.successful {
      request.isAjax match {
        case true => status(AjaxResponse.asJson(AjaxResponse(Some(errorMessage), None, None)))
        case false if request.method === POST => redirectToRefererOrElse(errorRoute)(request).flashingError(errorMessage)
        case _ => status(errorPage(request, statusCode, errorMessage))
      }
    }
  }
} 
开发者ID:danielnixon,项目名称:progressive,代码行数:36,代码来源:ProgressiveErrorHandler.scala


示例3: StashController

//设置package包名称以及导入依赖的类
package controllers

import javax.inject.{Inject, Singleton}

import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._
import play.api.mvc
import play.api.mvc.{Action, AnyContent, Controller, Result}
import services.{Constants, JsonConverter, Stash, StashStore}

import scala.concurrent.Future


@Singleton
class StashController @Inject()(stashStore: StashStore, jsonConverter: JsonConverter) extends Controller {

  def addStash = Action.async(request => {
    validateStashAndRespond(request, (stash) => stashStore.addStash(stash).map(addedStash => Ok(Json.toJson[Stash](addedStash))))
  })

  def index = Action.async(request => {
    stashStore.getStashes().map(stashes => Ok(Json.toJson(stashes)))
  })

  def getStash(id: String) = Action.async(request =>
    stashStore.getStash(id).map {
      case Some(retrievedStash) => Ok(Json.toJson[Stash](retrievedStash))
      case None => NotFound
    }
  )

  def updateStash = Action.async(request => {
    validateStashAndRespond(request, (stash) => stashStore.updateStash(stash).map(updatedStash => Ok(Json.toJson[Stash](updatedStash))))
  })

  private def validateStashAndRespond(request: mvc.Request[AnyContent], responseAction: (Stash) => Future[Result]): Future[Result] = {
    request.body.asJson match {
      case None => Future.successful(BadRequest(Constants.noValidJsonMessage))
      case Some(json) =>
        val stash = jsonConverter.getStashFromRequestBody(json)
        stash match {
          case Some(value) => responseAction(value)
          case None => Future.successful(BadRequest(json))
        }
    }
  }
} 
开发者ID:dgrald,项目名称:locals-only-service-play,代码行数:48,代码来源:StashController.scala


示例4: BreakfastAppControllerSpec

//设置package包名称以及导入依赖的类
package controllers

import org.scalatestplus.play.{OneAppPerSuite, PlaySpec}
import play.api.mvc.Result
import play.api.test.FakeRequest
import play.api.test.Helpers._

import scala.concurrent.Future

class BreakfastAppControllerSpec extends PlaySpec with OneAppPerSuite {
  "BreakfastAppController" should {
    "not return 404" when {
      "we try to hit the route /home" in {
        route(app, FakeRequest(GET, "/home")).map(status(_)) must not be Some(NOT_FOUND)
      }
    }
    "reneder a page" when {
      "we try to hit the route /home" in {
        var result: Option[Future[Result]] = route(app, FakeRequest(GET, "/home"))

        result.map(status(_)) mustBe Some(OK)

        val text: String = result.map(contentAsString(_)).get
        text must include ("Welcome to Play")
      }
    }
  }
} 
开发者ID:Hejocaso,项目名称:LunchApp,代码行数:29,代码来源:BreakfastAppControllerSpec.scala


示例5: BaseAuthController

//设置package包名称以及导入依赖的类
package controllers

import jp.t2v.lab.play2.auth.AuthElement
import models.document.{ DocumentAccessLevel, DocumentInfo, DocumentService }
import models.generated.tables.records.{ DocumentFilepartRecord, DocumentRecord, UserRecord }
import models.user.UserService
import play.api.Configuration
import play.api.mvc.Result
import scala.concurrent.ExecutionContext

abstract class BaseAuthController(
    config: Configuration,
    documents: DocumentService,
    users: UserService
  ) extends BaseController(config, users) with AuthElement {
  
  
  protected def documentPartResponse(
      docId: String,
      partNo: Int,
      user: UserRecord,
      response: (DocumentInfo, DocumentFilepartRecord, DocumentAccessLevel) => Result
    )(implicit ctx: ExecutionContext) = {

    documentResponse(docId, user, { case (doc, accesslevel) =>
      doc.fileparts.find(_.getSequenceNo == partNo) match {
        case None => NotFoundPage
        case Some(part) => response(doc, part, accesslevel)
      }
    })
  }
  
} 
开发者ID:pelagios,项目名称:recogito2,代码行数:34,代码来源:BaseAuthController.scala


示例6: BaseOptAuthController

//设置package包名称以及导入依赖的类
package controllers

import jp.t2v.lab.play2.auth.OptionalAuthElement
import models.document.{ DocumentAccessLevel, DocumentInfo, DocumentService }
import models.generated.tables.records.{ DocumentFilepartRecord, DocumentRecord, UserRecord }
import models.user.UserService
import play.api.Configuration
import play.api.mvc.{ AnyContent, Request, Result }
import scala.concurrent.{ ExecutionContext, Future }

abstract class BaseOptAuthController(
    config: Configuration,
    documents: DocumentService,
    users: UserService
  ) extends BaseController(config, users) with OptionalAuthElement {
  
  
  
  protected def documentPartResponse(
      documentId: String,
      partNo: Int,
      maybeUser: Option[UserRecord],
      response: (DocumentInfo, DocumentFilepartRecord, DocumentAccessLevel) => Future[Result]
    )(implicit ctx: ExecutionContext) = {
    
    documentResponse(documentId, maybeUser, { case (doc, accesslevel) =>
      doc.fileparts.find(_.getSequenceNo == partNo) match {
        case None => Future.successful(NotFoundPage)
        case Some(part) => response(doc, part, accesslevel)
      }
    })
  }
  
} 
开发者ID:pelagios,项目名称:recogito2,代码行数:35,代码来源:BaseOptAuthController.scala


示例7: ErrorHandler

//设置package包名称以及导入依赖的类
package common

import org.slf4j.MDC
import play.api.Logger
import play.api.http.HttpErrorHandler
import play.api.libs.json.Json
import play.api.mvc.Results._
import play.api.mvc.{Result, RequestHeader}

import scala.concurrent.Future
import scala.util.Try

class ErrorHandler extends HttpErrorHandler {

  def onClientError(request: RequestHeader, statusCode: Int, m: String): Future[Result] = {
    val message = if(m.isEmpty) "there was a problem in the request, please check the path and the headers" else m
    Logger.warn(s"There was a client error with statusCode $statusCode in ${request.method} ${request.path} with message: $message")
    Future.successful(Status(statusCode)(Json.obj("error" -> true, "message" -> message)))
  }

  def onServerError(request: RequestHeader, exception: Throwable): Future[Result] = {
    val requestId = Try(MDC.get("requestId")).getOrElse{Logger.warn("couldnt get the requestId from MDC");""}
    val message = s"There was a server error in ${request.method} ${request.path} with requestId $requestId"
    Logger.error(message, exception)
    Future.successful(InternalServerError(Json.obj("error" -> true, "message" -> exception.getMessage)))
  }

} 
开发者ID:dtambussi,项目名称:pedidos,代码行数:29,代码来源:ErrorHandler.scala


示例8: apply

//设置package包名称以及导入依赖的类
package net.white_azalea.filters.security.authorization

import javax.inject.Inject

import akka.stream.Materializer
import play.api.mvc.{ Filter, RequestHeader, Result }

import scala.concurrent.Future


  override def apply(nextFilter: (RequestHeader) => Future[Result])(rh: RequestHeader): Future[Result] = {
    val authName = auth.readAuthName(rh)
    lazy val isAccessible = auth.isAccessible(authName)(rh)

    if (isAccessible) {
      nextFilter(rh)
    } else {
      auth.handleNotAccessible(rh)
    }
  }
} 
开发者ID:Sunao-Yoshii,项目名称:SimplePlayModule,代码行数:22,代码来源:AuthorizationFilter.scala


示例9: CorrelationIdFilter

//设置package包名称以及导入依赖的类
package filters

import akka.actor.ActorSystem
import akka.stream.{ ActorMaterializer, Materializer }
import javax.inject.Inject
import play.api.mvc.{ Filter, RequestHeader, Result }

import scala.concurrent.{ ExecutionContext, Future }

class CorrelationIdFilter @Inject() (implicit val executionContext: ExecutionContext, implicit val actorSystem: ActorSystem) extends Filter {

  val mat: Materializer = ActorMaterializer()
  def apply(nextFilter: (RequestHeader) => Future[Result])(requestHeader: RequestHeader): Future[Result] = {
    nextFilter(requestHeader.copy(
      tags = requestHeader.tags +
      (CorrelationContext.correlationIdTag ->
        requestRefNum(requestHeader).map(_.toString.toLowerCase).getOrElse(CorrelationContext.newCorrelationId))
    ))
  }

  private def requestRefNum(requestHeader: RequestHeader): Option[String] = {
    requestHeader.headers.get("L-IS24-RequestRefnum").map(_.trim).filter(!_.isEmpty)
  }
} 
开发者ID:mriehl,项目名称:play-bug,代码行数:25,代码来源:CorrelationIdFilter.scala


示例10: SettingSpec

//设置package包名称以及导入依赖的类
package httpmock

import play.api.mvc.{RequestHeader, Result, Results}

class SettingSpec extends TestHelper {
  describe("Setting()") {
    it("can start http service on some port") {
      val setting = Setting()
      start(setting) { server =>
        assert(server.port > 0)
      }
    }
  }

  describe("Setting(methods = Set(GET))") {
    val setting = Setting(methods = Set(GET))
    it("accepts GET [200]") {
      start(setting) { server =>
        assert(get(server.url).getStatusCode === 200)
      }
    }

    it("rejects POST [404]") {
      start(setting) { server =>
        assert(post(server.url, "body").getStatusCode === 404)
      }
    }
  }

  describe("Setting(handler = ???") {
    val handler: PartialFunction[RequestHeader, Result] = {
      case h: RequestHeader if h.method == "POST" => Results.Unauthorized
      case h: RequestHeader if h.uri.contains("rerorero") => Results.InternalServerError
    }

    it("responses matched handler results") {
      start(Setting(methods = Set(GET, POST), handler = handler)) { server =>
        assert(post(server.url, "body").getStatusCode === 401)
        assert(get(server.url + "rerorero").getStatusCode === 500)
      }
    }

    it("responses according to methods property if not matched") {
      start(Setting(methods = Set(GET), handler = handler)) { server =>
        assert(post(server.url, "body").getStatusCode === 404)
        assert(get(server.url + "rorerore").getStatusCode === 200)
      }
    }
  }
} 
开发者ID:xuwei-k,项目名称:httpmock,代码行数:51,代码来源:SettingSpec.scala


示例11: ApiTest

//设置package包名称以及导入依赖的类
package global

import user.Fixtures

import scala.concurrent.Future
import play.api.libs.json.Json
import play.api.mvc.Result
import play.api.test.FakeApplication
import play.api.test.FakeRequest
import play.api.test.Helpers._
import org.scalatest.TestData

class ApiTest extends ApiSpecServer with TestUtils {

  implicit override def newAppForTest(td: TestData): FakeApplication = getFakeApp(new TestGlobal()(Fixtures))

  "The application " should {

    "return OK on ping" in {
      val result: Future[Result] = (new controllers.Application()).ping().apply(FakeRequest())
      val bodyText: String = contentAsString(result)
      bodyText mustBe "Ok"
    }
  }
} 
开发者ID:Driox,项目名称:play-app-seed,代码行数:26,代码来源:ApiTest.scala


示例12: helloMessage

//设置package包名称以及导入依赖的类
package controllers

import com.google.inject.Inject
import io.toolsplus.atlassian.connect.play.actions.JwtAuthenticationActions
import io.toolsplus.atlassian.connect.play.api.models.AtlassianHostUser
import io.toolsplus.atlassian.connect.play.auth.jwt.request.SelfAuthenticationTokenGenerator
import play.api.Logger
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._
import play.api.mvc.{Controller, Result}

import scala.concurrent.Future


  def helloMessage = jwtAuthenticationActions.withAtlassianHostUser.async {
    implicit request =>
      val json =
        Json.obj("message" -> s"Hello ${request.hostUser.host.baseUrl}")
      Future
        .successful(json)
        .map(json => withJwtAuthorizationHeaders(Ok(json)))
  }

  private def withJwtAuthorizationHeaders(result: Result)(
      implicit hostUser: AtlassianHostUser): Result = {
    selfAuthenticationTokenGenerator.createSelfAuthenticationToken(hostUser) match {
      case Right(token) => result.withHeaders(AUTHORIZATION -> s"JWT $token")
      case Left(error) => {
        logger.error(s"Failed to sign JWT: ${error.getMessage}")
        InternalServerError(error.getMessage)
      }
    }
  }
} 
开发者ID:toolsplus,项目名称:atlassian-connect-play-seed,代码行数:35,代码来源:ApiController.scala


示例13: CameraRelayControllerTest

//设置package包名称以及导入依赖的类
package controllers

import com.intersection.camerarelay.UploadManager
import org.mockito.Matchers._
import org.scalatest.concurrent.{Futures, ScalaFutures}
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{BeforeAndAfter, FunSpec, Matchers}
import play.api.libs.Files
import play.api.mvc.{Request, Result}
import play.api.test.FakeRequest
import play.api.test.Helpers._
import org.mockito.Mockito._

import scala.concurrent.Future

class CameraRelayControllerTest extends FunSpec with Matchers with MockitoSugar with BeforeAndAfter with Futures with ScalaFutures {
  var controller : CameraRelayController = _
  var uploadManager : UploadManager = _

  before {
    uploadManager = mock[UploadManager]
    controller = new CameraRelayController(uploadManager)
  }

  describe(classOf[CameraRelayControllerTest].getName) {
    it("Rejects requests without a valid siteId header : X-Site-Id") {
      val request: Request[Files.TemporaryFile] = FakeRequest().withHeaders(("Content-Type"->"application/octet-stream"), ("X-Link-Time"->"2016-12-12")).withBody(Files.TemporaryFile())
      val result = controller.uploadVideoChunk().apply(request)
      status(result) should equal(400)
    }

    it("Rejects requests without a valid Link-Time header : X-Link-Time") {
      val request: Request[Files.TemporaryFile] = FakeRequest().withHeaders(("Content-Type"->"application/octet-stream"), ("X-Site-Id"->"mn-1234")).withBody(Files.TemporaryFile())
      val result: Future[Result] = controller.uploadVideoChunk().apply(request)
      status(result) should equal(400)
    }

    it("Accepts a fully formed request") {
      import scala.concurrent.ExecutionContext.Implicits.global
      when(uploadManager.handleVideoChunk(any[String],any[String],any[Files.TemporaryFile])).thenReturn(Future(()))
      val request: Request[Files.TemporaryFile] = FakeRequest().withHeaders(("Content-Type"->"application/octet-stream"), ("X-Site-Id"->"mn-1234"), ("X-Link-Time"->"2016-12-12")).withBody(Files.TemporaryFile())
      val result: Future[Result] = controller.uploadVideoChunk().apply(request)
      status(result) should equal(202)
    }

  }
} 
开发者ID:arjunmukherjee,项目名称:camerarelay,代码行数:48,代码来源:CameraRelayControllerTest.scala


示例14: Session

//设置package包名称以及导入依赖的类
package ejisan.play.libs.scalauth

import play.api.mvc.{ Result, RequestHeader }
import play.api.{ Configuration, Logger }

case class Session(id: String, impersonator: Option[String]) {
  def toSeq(SESSION_COOKIE_NAME: String, IMPERSONATING_SESSION_COOKIE_NAME: String): Seq[(String, String)] =
    Seq(SESSION_COOKIE_NAME -> Some(id), IMPERSONATING_SESSION_COOKIE_NAME -> impersonator).collect {
      case (key, Some(value)) => (key, value)
    }
}

class PlaySessionManager(configuration: Configuration) {
  val SESSION_COOKIE_NAME: String =
    configuration.getString("scalauth.play.secure_action.cookie_name").getOrElse("SESSION")
  val IMPERSONATING_SESSION_COOKIE_NAME: String =
    configuration.getString("scalauth.play.secure_action.impersonator_cookie_name").getOrElse("IMPERSONATOR")

  def set(session: Session)(result: => Result)(implicit request: RequestHeader): Result = {
    Logger.debug(s"Set session for ID: `${session.id}` and IMPERSONATOR_ID: `${session.impersonator.getOrElse("N/A")}`.")
    forceEnd(result).addingToSession(session.toSeq(SESSION_COOKIE_NAME, IMPERSONATING_SESSION_COOKIE_NAME):_*)
  }

  def get(implicit request: RequestHeader): Option[Session] =
    request.session.get(SESSION_COOKIE_NAME).map(Session(_, request.session.get(IMPERSONATING_SESSION_COOKIE_NAME)))

  def start(id: String)(result: => Result)(implicit request: RequestHeader): Result =
    set(Session(id, None))(result)

  def restart(result: => Result)(implicit request: RequestHeader): Result =
    get.map(set(_)(result)).getOrElse(result)

  def impersonate(id: String)(result: => Result)(implicit request: RequestHeader): Result = {
    val impersonator = try {
      request.session(SESSION_COOKIE_NAME)
    } catch {
      case _: NoSuchElementException =>
      val e = new IllegalStateException("Impersonator must start main session before impersonating session.")
        Logger.error("Main session not found", e)
        throw e
    }
    set(Session(id, Some(impersonator)))(result)
  }

  def end(result: => Result)(implicit request: RequestHeader): Result = {
    if (request.session.data.keySet.exists(_ == IMPERSONATING_SESSION_COOKIE_NAME)) {
      result.removingFromSession(IMPERSONATING_SESSION_COOKIE_NAME)
    } else if (request.session.data.keySet.exists(_ == SESSION_COOKIE_NAME)) {
      result.removingFromSession(SESSION_COOKIE_NAME)
    } else {
      result
    }
  }

  def forceEnd(result: => Result)(implicit request: RequestHeader): Result =
    result.removingFromSession(SESSION_COOKIE_NAME, IMPERSONATING_SESSION_COOKIE_NAME)
} 
开发者ID:ejisan,项目名称:play-scalauth-secureaction,代码行数:58,代码来源:PlaySessionManager.scala


示例15: TestBuilder

//设置package包名称以及导入依赖的类
package models

import play.api.Application
import play.api.mvc.{AnyContentAsEmpty, Result}
import play.api.test.{FakeHeaders, FakeRequest, Helpers}
import play.mvc.Call

import scala.concurrent.Future

object TestBuilder {

  object anUser {

    import play.api.test.Helpers._
    def GET(call: Call)(implicit app: Application): Option[Future[Result]] =
      route(app, fakeUnauthenticatedRequest(Helpers.GET, call.url(), FakeHeaders(), AnyContentAsEmpty))

    def POST[A](call: Call)(body: A)(implicit w: play.api.http.Writeable[A], app: Application): Option[Future[Result]] =
      route(app, fakeUnauthenticatedRequest(Helpers.POST, call.url(), jsonHeaders, body))

    private def fakeUnauthenticatedRequest[A](method: String, uri: String, headers: FakeHeaders, body: A): FakeRequest[A] = FakeRequest(
      method,
      uri,
      withAjaxHeader(headers),
      body
    )

    private def jsonHeaders = FakeHeaders(
      Seq("Content-Type" -> "application/json")
    )

    private def withAjaxHeader(headers: FakeHeaders): FakeHeaders = headers.copy(data = headers.data :+ ("X-Requested-With" -> "XMLHttpRequest"))
  }

} 
开发者ID:fagossa,项目名称:play-reactive-couchbase,代码行数:36,代码来源:TestBuilder.scala


示例16: generateToken

//设置package包名称以及导入依赖的类
package controllers.stack

import jp.t2v.lab.play2.stackc.{RequestAttributeKey, RequestWithAttributes, StackableController}
import scala.concurrent.Future
import play.api.mvc.{Result, Request, Controller}
import play.api.data._
import play.api.data.Forms._
import scala.util.Random
import java.security.SecureRandom

trait TokenValidateElement extends StackableController {
    self: Controller =>

  private val PreventingCsrfTokenSessionKey = "preventingCsrfToken"

  private val tokenForm = Form(PreventingCsrfToken.FormKey -> text)

  private val random = new Random(new SecureRandom)
  private val table = ('a' to 'z') ++ ('A' to 'Z') ++ ('0' to '9') ++ "^`~:/?,.{[}}|+_()*^%$#@!"

  private def generateToken: PreventingCsrfToken = PreventingCsrfToken {
    Iterator.continually(random.nextInt(table.size)).map(table).take(32).mkString
  }

  case object PreventingCsrfTokenKey extends RequestAttributeKey[PreventingCsrfToken]
  case object IgnoreTokenValidation extends RequestAttributeKey[Boolean]

  private def validateToken(request: Request[_]): Boolean = (for {
    tokenInForm    <- tokenForm.bindFromRequest()(request).value
    tokenInSession <- request.session.get(PreventingCsrfTokenSessionKey)
  } yield tokenInForm == tokenInSession) getOrElse false

  override def proceed[A](request: RequestWithAttributes[A])(f: RequestWithAttributes[A] => Future[Result]): Future[Result] = {
    if (isIgnoreTokenValidation(request) || validateToken(request)) {
      implicit val ctx = StackActionExecutionContext(request)
      val newToken = generateToken
      super.proceed(request.set(PreventingCsrfTokenKey, newToken))(f) map {
        _.withSession(PreventingCsrfTokenSessionKey -> newToken.value)
      }
    } else {
      Future.successful(BadRequest("Invalid preventing CSRF token"))
    }
  }

  implicit def isIgnoreTokenValidation(implicit request: RequestWithAttributes[_]): Boolean =
    request.get(IgnoreTokenValidation).exists(identity)

  implicit def preventingCsrfToken(implicit request: RequestWithAttributes[_]): PreventingCsrfToken =
    request.get(PreventingCsrfTokenKey).get


}

case class PreventingCsrfToken(value: String)

object PreventingCsrfToken {

  val FormKey = "preventingCsrfToken"

} 
开发者ID:bananapianist,项目名称:playfw_sample,代码行数:61,代码来源:TokenValidateElement.scala


示例17: LifecycleActions

//设置package包名称以及导入依赖的类
package io.toolsplus.atlassian.connect.play.actions

import io.toolsplus.atlassian.connect.play.models.LifecycleEvent
import play.api.mvc.{ActionFilter, Request, Result, WrappedRequest}
import play.api.mvc.Results._

import scala.concurrent.Future

object LifecycleActions {

  case class LifecycleRequest[A](event: LifecycleEvent, request: Request[A])
      extends WrappedRequest[A](request)

  case class CheckLifecycleEventTypeAction(expectedEventType: String)
      extends ActionFilter[LifecycleRequest] {
    override def filter[A](
        request: LifecycleRequest[A]): Future[Option[Result]] =
      Future.successful {
        if (request.event.eventType != expectedEventType)
          Some(BadRequest("Invalid lifecycle event type"))
        else
          None
      }
  }

} 
开发者ID:toolsplus,项目名称:atlassian-connect-play,代码行数:27,代码来源:LifecycleActions.scala


示例18: RegExCORSFilter

//设置package包名称以及导入依赖的类
package com.github.dgilling.regexcors

import akka.stream.Materializer
import play.api.Logger
import play.api.http.{DefaultHttpErrorHandler, HttpErrorHandler}
import play.api.mvc.{Result, RequestHeader, Filter}
import play.core.j.JavaHttpErrorHandlerAdapter
import play.filters.cors.{CORSFilter, AbstractCORSPolicy, CORSConfig}

import scala.concurrent.Future


class RegExCORSFilter(
                  override protected val corsConfig: CORSConfig = CORSConfig(),
                  override protected val errorHandler: HttpErrorHandler = DefaultHttpErrorHandler,
                  private val pathPrefixes: Seq[String] = Seq("/"),
                  private val ignoredPathPrefixes: Seq[String] = Seq.empty[String])(override implicit val mat: Materializer)
  extends CORSFilter {

  // Java constructor
  def this(corsConfig: CORSConfig, errorHandler: play.http.HttpErrorHandler, pathPrefixes: java.util.List[String])(mat: Materializer) = {
    this(corsConfig, new JavaHttpErrorHandlerAdapter(errorHandler), Seq(pathPrefixes.toArray.asInstanceOf[Array[String]]: _*))(mat)
  }

  override protected val logger = Logger(classOf[CORSFilter])

  override def apply(f: RequestHeader => Future[Result])(request: RequestHeader): Future[Result] = {
    if (pathPrefixes.exists(request.path.startsWith) &&
      !ignoredPathPrefixes.exists(request.path.startsWith)) {
      filterRequest(f, request)
    } else {
      f(request)
    }
  }
}

object RegExCORSFilter {

  val RequestTag = "CORS_REQUEST"

  def apply(corsConfig: CORSConfig = CORSConfig(), errorHandler: HttpErrorHandler = DefaultHttpErrorHandler,
            pathPrefixes: Seq[String] = Seq("/"))(implicit mat: Materializer) =
    new CORSFilter(corsConfig, errorHandler, pathPrefixes)

} 
开发者ID:dgilling,项目名称:play-regex-cors,代码行数:46,代码来源:RegExCORSFilter.scala


示例19: hash

//设置package包名称以及导入依赖的类
package services

import java.security.MessageDigest
import java.util.UUID

import play.api.libs.json.{JsValue, Json}
import play.api.mvc.Results.Status
import play.api.mvc.{RequestHeader, Result}


trait ApiSecurity {
  val sessionId = "sessionId"
  def hash(s: String) = MessageDigest.getInstance("SHA-256").digest(s.getBytes("UTF-8")).map("%02x".format(_)).mkString("")

  implicit class ResultWithToken(result: Result)(implicit request: RequestHeader) {
    def withToken: Result = {
      request.session.get(sessionId) match {
        case Some(session) => result
        case None => result.withSession(sessionId -> hash(request.remoteAddress + UUID.randomUUID().toString))
      }
    }
  }

  def JsonAnswer(status: Int = 200, jsObject: JsValue)(implicit request: RequestHeader): Result =
    Status(status).apply(
      Json.obj(
        "result" -> Json.obj("status" -> status),
        "data" -> jsObject
      )
    ).withToken
} 
开发者ID:kormoglaz,项目名称:TestTask,代码行数:32,代码来源:ApiSecurity.scala


示例20: UserController

//设置package包名称以及导入依赖的类
package controllers

import javax.inject.Inject

import com.google.inject.Singleton
import exception.BusinessException
import models.User
import play.api.libs.json.Json
import play.api.mvc.{Controller, Result}
import security.OauthDataHandler
import services.UserService
import utils.{Response, Validation}

import scala.concurrent.Future
import scalaoauth2.provider.OAuth2ProviderActionBuilders._


@Singleton
class UserController @Inject()
(userService: UserService,
 oauthDataHandler: OauthDataHandler) extends Controller {

  def getAllUser = AuthorizedAction(oauthDataHandler).async { implicit request =>
    userService.findAllUser().map(x => Ok(Json.toJson(x)))
  }

  def getUserById(id: Long) = AuthorizedAction(oauthDataHandler).async { implicit request =>
    userService.findById(id).map { x =>
      Ok(Json.toJson(x))
    } recover {
      case ex: BusinessException => Response.errorResponse(ex)
    }
  }

  def createUser() = AuthorizedAction(oauthDataHandler).async(parse.json) { implicit request =>
    def create(): (User) => Future[Result] = u => {
      userService.createUser(u).map(x => Created(Json.toJson(x))) recover {
        case ex: BusinessException => Response.errorResponse(ex)
      }
    }
    request.body.validate[User].fold(invalid = Validation.validationError(BAD_REQUEST), valid = create())
  }

  def updateUser() = AuthorizedAction(oauthDataHandler).async(parse.json) { implicit request =>
    def update(): (User) => Future[Result] = u => {
      userService.updateUser(u).map(x => Ok(Json.toJson(x))) recover {
        case ex: BusinessException => Response.errorResponse(ex)
      }
    }
    request.body.validate[User].fold(invalid = Validation.validationError(BAD_REQUEST), valid = update())
  }

  def deleteUser(id: Long) = AuthorizedAction(oauthDataHandler).async {
    userService.deleteUser(id).map(x => Ok(Json.toJson(x))) recover {
      case ex: BusinessException => Response.errorResponse(ex)
    }
  }

} 
开发者ID:satriapribadi,项目名称:satriapribadi.com,代码行数:60,代码来源:UserController.scala



注:本文中的play.api.mvc.Result类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala FunSpec类代码示例发布时间:2022-05-23
下一篇:
Scala Form类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap