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

Scala Request类代码示例

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

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



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

示例1: ContactController

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

import javax.inject._

import models.{ContactDB, MongoConnector}
import play.api._
import play.api.i18n.Messages
import play.api.mvc._
import play.api.mvc.{Action, Controller, Flash, Request}
import play.api.data.Form
import play.api.data.Forms._
import play.api.data.Forms.{mapping, nonEmptyText}


import play.api.data.Forms.{longNumber, mapping, nonEmptyText}
import play.api.i18n.Messages.Implicits._
import play.api.Play.current
import scala.concurrent.ExecutionContext.Implicits.global



@Singleton
class ContactController  @Inject() extends Controller{

  val contactForm = Form(tuple(
    "Name" -> text,
      "Email" -> text,
      "Message" -> text
    ))

  def saveContact = Action {
    implicit request =>
      val newContactForm = contactForm.bindFromRequest()
      newContactForm.fold(success = {
        newContact =>
          //Create a contact object using form data
          val newContactID = ContactDB.findNextID()
          print(newContactID)
          println(newContact._2)
          val newContactRequest = new ContactDB(newContactID, newContact._1, newContact._2, newContact._3)

          //Insert into contact collection
          MongoConnector.collectionContact.insert(newContactRequest)
          Ok(views.html.home())
      }, hasErrors = {
        form =>
          Redirect(routes.ContactController.contact()).flashing(Flash(form.data) + ("error" -> Messages("contact.validation.errors")))
      })
      }

  def contact = Action {
    implicit request =>
      val form = if (request2flash.get("error").isDefined)
        contactForm.bind(request2flash.data)
      else
        contactForm
      Ok(views.html.contact(form))
  }


} 
开发者ID:nkaraolis,项目名称:NBGardensNewPlay,代码行数:62,代码来源:ContactController.scala


示例2: UploadZipRecipeForm

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

import models.Password
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import play.api.libs.Files
import play.api.mvc.{MultipartFormData, Request}

case class UploadZipRecipeForm(
    version: String,
    password: String,
    file: MultipartFormData.FilePart[Files.TemporaryFile]
) {
  def passwordRecord = {
    Password(0L, version, MyBCrypt.createHash(password))
  }
}

object UploadZipRecipeForm {
  def fromReq(req: Request[MultipartFormData[Files.TemporaryFile]]): Option[UploadZipRecipeForm] = {
    val data = req.body.dataParts
    for {
      version <- data.get("ver").flatMap(_.headOption)
      password <- data.get("password").flatMap(_.headOption)
      file <- req.body.file("zipFile")
    } yield new UploadZipRecipeForm(version, password, file)
  }
}

object MyBCrypt {
  val bcrypt = new BCryptPasswordEncoder(12)
  def createHash(password: String) = bcrypt.encode(password)
  def authenticate(password: String, hash: String): Boolean =
    bcrypt.matches(password, hash)
} 
开发者ID:ponkotuy,项目名称:FactorioRecipe,代码行数:35,代码来源:UploadZipRecipeForm.scala


示例3: AuthAction

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

import scala.concurrent.Future
import play.api.Logger
import play.api.mvc.{ActionBuilder, Request, Result}
import play.api.mvc.Results.Redirect

import controllers.routes
import values.session

object AuthAction extends ActionBuilder[Request] {
  override def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]): Future[Result] = {
    request.session.get(session.SESSION_KEY) match {
      case Some(userId) =>
        Logger.info("user-id is: " + userId)
        block(request)
      case None =>
        Logger.info("redirect to login page.")
        Future.successful(Redirect(routes.LoginController.index()))
    }
  }
} 
开发者ID:kogai,项目名称:kakei-log,代码行数:23,代码来源:AuthAction.scala


示例4: TokenChecker

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

import play.api.mvc.{ActionBuilder, Request, Result, Results}
import play.mvc.Http.Status
import services.cryptography.{JwtTokenGenerator, JwtTokenGeneratorServices}
import scala.concurrent.ExecutionContext.Implicits.global

import scala.concurrent.Future


object TokenChecker extends ActionBuilder[Request] {
  override def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]): Future[Result] = {
    val token : Option[String] = request.headers.get("token")
    if(token.isDefined) {
      val jwt : JwtTokenGeneratorServices = new JwtTokenGenerator
      val verify = jwt.verifyToken(token.get)
      block(request)
    }
    else {
      Future{ Results.Status(Status.UNAUTHORIZED) }
    }
  }
} 
开发者ID:mubeenahmed,项目名称:MeGuideApi,代码行数:24,代码来源:TokenChecker.scala


示例5: PermissionsViaHttpAuthorizer

//设置package包名称以及导入依赖的类
package auth.http.service.impl.authorization.impl

import auth.core.model.core.{Permission, PermissionToUser, User}
import auth.core.service.authorization.{PermissionAuthorization, PermissionsAuthorizer}
import com.mohiva.play.silhouette.impl.authenticators.JWTAuthenticator
import play.api.Configuration
import play.api.libs.json.{JsError, JsSuccess}
import play.api.libs.ws.WSClient
import play.api.mvc.Request

import scala.concurrent.{ExecutionContext, Future}
import play.api.Logger


class PermissionsViaHttpAuthorizer(configuration: Configuration, ws: WSClient)(
    implicit ec: ExecutionContext)
    extends PermissionsAuthorizer {
  import auth.core.formatting.core.Rest._

  private val logger   = Logger(this.getClass)
  private val endpoint = configuration.underlying.getString("auth.http.user-service.url")
  private def uri(uuid: String): String = s"$endpoint/users/$uuid/permissions"

  override def require(required: Permission): PermissionAuthorization[JWTAuthenticator] =
    new PermissionAuthorization[JWTAuthenticator] {
      override def isAuthorized[B](identity: User, authenticator: JWTAuthenticator)(
          implicit request: Request[B]): Future[Boolean] = {
        val endpoint = uri(identity.uuid.toString)

        val f = ws.url(endpoint).get().map { resp ?
          val permissions = resp.json.validate[Seq[PermissionToUser]]
          permissions match {
            case JsSuccess(ps, _) ?
              ps.map(_.permission).contains(required)
            case JsError(e) ?
              logger.error(e.mkString("\n"))
              false
          }
        }
        logError(f, endpoint)
        f
      }
    }

  @inline private def logError[A](f: Future[_], endpoint: String): Unit =
    f.onFailure {
      case e: Throwable ?
        logger.error(s"Error during request to $endpoint", e)
    }
} 
开发者ID:KadekM,项目名称:play-slick-silhouette-auth-api,代码行数:51,代码来源:PermissionsViaHttpAuthorizer.scala


示例6: MyDynamicResourceHandler

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

import be.objectify.deadbolt.scala.{ DynamicResourceHandler, DeadboltHandler }
import collection.immutable.Map
import play.api.mvc.Request

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future


class MyDynamicResourceHandler extends DynamicResourceHandler {
  def isAllowed[A](name: String, meta: String, handler: DeadboltHandler, request: Request[A]): Future[Boolean] = {
    MyDynamicResourceHandler.handlers(name).isAllowed(name,
      meta,
      handler,
      request)
  }

  // todo implement this when demonstrating permissions
  def checkPermission[A](permissionValue: String, deadboltHandler: DeadboltHandler, request: Request[A]): Future[Boolean] = Future(false)
}

object MyDynamicResourceHandler {
  val handlers: Map[String, DynamicResourceHandler] =
    Map(
      "pureLuck" -> new DynamicResourceHandler() {
        def isAllowed[A](name: String, meta: String, deadboltHandler: DeadboltHandler, request: Request[A]): Future[Boolean] =
          Future(System.currentTimeMillis() % 2 == 0)

        def checkPermission[A](permissionValue: String, deadboltHandler: DeadboltHandler, request: Request[A]): Future[Boolean] = Future(false)
      })
} 
开发者ID:kapit4n,项目名称:hi-stock,代码行数:33,代码来源:MyDynamicResourceHandler.scala


示例7: MyDeadboltHandler

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

import be.objectify.deadbolt.scala.{ DynamicResourceHandler, DeadboltHandler }
import play.api.mvc.{ Request, Result, Results }
import be.objectify.deadbolt.core.models.Subject
import scala.concurrent.{ Future, Await }
import models.UserSecurity
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
import dal._
import javax.inject._
import models._


class MyDeadboltHandler(dynamicResourceHandler: Option[DynamicResourceHandler] = None, var rolesListParam: List[SecurityRole] = List()) extends DeadboltHandler {

  def beforeAuthCheck[A](request: Request[A]) = Future(None)

  override def getDynamicResourceHandler[A](request: Request[A]): Future[Option[DynamicResourceHandler]] = {
    Future(dynamicResourceHandler.orElse(Some(new MyDynamicResourceHandler())))
  }

  override def getSubject[A](request: Request[A]): Future[Option[Subject]] = {
    var rol: String = request.session.get("role").get
    var user1 = new UserSecurity("steve", rol, rolesListParam)

    Future(Some(user1))
  }

  def onAuthFailure[A](request: Request[A]): Future[Result] = {
    Future { Results.Forbidden(views.html.accessFailed()) }
  }
} 
开发者ID:kapit4n,项目名称:hi-stock,代码行数:34,代码来源:MyDeadboltHandler.scala


示例8: TokenCheck

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

import play.api.libs.json.JsValue
import play.api.mvc.{AnyContent, Request}
import services.util.TokenService

import scala.concurrent.ExecutionContext.Implicits.global


object TokenCheck {
  def getTokenfromParam(request: Request[AnyContent]) = {
    val token = request.headers.get("Authorization")
    val tokenValue = token match {
      case Some(t) => t
      case None => ""
    }
    check(tokenValue) map (tkn => {
      if(tkn) LogInStatus("VALID")
      else LogInStatus("INVALID")
    })
  }

  def getToken(request: Request[JsValue]) = {
    val token = request.headers.get("Authorization")
    val tokenValue = token match {
      case Some(t) => t
      case None => ""
    }
    check(tokenValue) map (tkn => {
      if(tkn) LogInStatus("VALID")
      else LogInStatus("INVALID")
    })
  }

  private def check(token: String) = {
    val code = TokenService.apply().getEmail(token)
    TokenService.apply.isTokenValid(token, code)
  }


} 
开发者ID:Masebeni,项目名称:hwork,代码行数:42,代码来源:TokenCheck.scala


示例9: WithRole

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

import com.mohiva.play.silhouette.api.{ Authenticator, Authorization }
import play.api.i18n._
import play.api.mvc.Request

import scala.concurrent.Future

case class WithRole(role: Role) extends Authorization[User, Authenticator] {
  override def isAuthorized[B](user: User, authenticator: Authenticator)(implicit request: Request[B], messages: Messages) = {
    Future.successful(user.roles match {
      case list: Set[Role] => list.contains(role)
      case _ => false
    })
  }
}

sealed trait Role extends Serializable {
  def name: String
}

object Role {
  def apply(role: String): Role = role match {
    case Admin.name => Admin
    case User.name => User
    case _ => Unknown
  }

  def unapply(role: Role): Option[String] = Some(role.name)

  object Admin extends Role {
    val name = "admin"
  }

  object User extends Role {
    val name = "user"
  }

  object Unknown extends Role {
    val name = "-"
  }
} 
开发者ID:laurinka,项目名称:golfmit,代码行数:43,代码来源:Roles.scala


示例10: FrontendGlobal

//设置package包名称以及导入依赖的类
package uk.gov.hmrc.trustregistration

import java.io.File

import com.typesafe.config.Config
import net.ceedubs.ficus.Ficus._
import play.api.Mode._
import play.api.mvc.Request
import play.api.{Application, Configuration, Play}
import play.twirl.api.Html
import uk.gov.hmrc.crypto.ApplicationCrypto
import uk.gov.hmrc.play.audit.filters.FrontendAuditFilter
import uk.gov.hmrc.play.config.{AppName, ControllerConfig, RunMode}
import uk.gov.hmrc.play.frontend.bootstrap.DefaultFrontendGlobal
import uk.gov.hmrc.play.http.logging.filters.FrontendLoggingFilter


object FrontendGlobal
  extends DefaultFrontendGlobal {

  override val auditConnector = FrontendAuditConnector
  override val loggingFilter = LoggingFilter
  override val frontendAuditFilter = AuditFilter

  override def onStart(app: Application) {
    super.onStart(app)
    ApplicationCrypto.verifyConfiguration()
  }

  override def onLoadConfig(config: Configuration, path: File, classloader: ClassLoader, mode: Mode): Configuration = {
    super.onLoadConfig(config, path, classloader, mode)
  }

  override def standardErrorTemplate(pageTitle: String, heading: String, message: String)(implicit rh: Request[_]): Html =
    uk.gov.hmrc.trustregistration.views.html.error_template(pageTitle, heading, message)

  override def microserviceMetricsConfig(implicit app: Application): Option[Configuration] = app.configuration.getConfig(s"microservice.metrics")
}

object ControllerConfiguration extends ControllerConfig {
  lazy val controllerConfigs = Play.current.configuration.underlying.as[Config]("controllers")
}

object LoggingFilter extends FrontendLoggingFilter {
  override def controllerNeedsLogging(controllerName: String) = ControllerConfiguration.paramsForController(controllerName).needsLogging
}

object AuditFilter extends FrontendAuditFilter with RunMode with AppName {

  override lazy val maskedFormFields = Seq("password")

  override lazy val applicationPort = None

  override lazy val auditConnector = FrontendAuditConnector

  override def controllerNeedsAuditing(controllerName: String) = ControllerConfiguration.paramsForController(controllerName).needsAuditing
} 
开发者ID:hmrc,项目名称:trust-registration-frontend,代码行数:58,代码来源:frontendGlobal.scala


示例11: Actions

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

import scala.concurrent.ExecutionContext.Implicits.global

import play.api.libs.json.JsValue
import play.api.mvc.Request

import countries.RequestSerializer.deserialize
import countries.{Validator => CountryValidator}

import scala.concurrent.Future
import scala.concurrent.ExecutionContext

object Actions {
  def update(id: Long, request: Request[JsValue])(implicit ec: ExecutionContext) = {
    val country = Countries.find(id)
    val updatedCountry = deserialize(request.body, country)

    CountryValidator.validate(updatedCountry) map { validator =>
      validator.getOrElse(Future.successful((false, Country.default))) map { existingValidator =>
        val (isValid, updatedRecord) = existingValidator

        if (isValid) {
          Countries.update(updatedRecord.id, updatedRecord)
          (true, updatedRecord)
        } else (false, updatedRecord)
      }
    }
  }

  def create(request: Request[JsValue])(implicit ec: ExecutionContext): Future[(Future[Country], Boolean)] = {
    val record = request.body.as[Country](deserialize())

    CountryValidator.validate(record) map { validator =>
      if (validator) {
        Countries.create(record)
        val countryFromDB = Countries.findByTitle(record.title)

        (countryFromDB, true)
      } else (Future.successful { record }, false)
    }
  }

  def destroy(id: Long)(implicit ec: ExecutionContext): Future[Boolean] = Countries.destroy(id)

  private implicit def intToBoolean(i: Future[Int]): Future[Boolean] = i.map(_ != 0)
} 
开发者ID:dsounded,项目名称:money_exchanger,代码行数:48,代码来源:Actions.scala


示例12: Actions

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

import play.api.libs.json.JsValue
import play.api.mvc.Request

import users.{Validator => UserValidator}
import users.RequestSerializer.deserialize

import scala.concurrent.Future
import scala.concurrent.ExecutionContext

object Actions {
  def create(request: Request[JsValue])(implicit ec: ExecutionContext) = {
    val record = request.body.as[User](deserialize)

    UserValidator.validate(record) map { validator =>
      if (validator) {
        Users.create(record)
        val userFromDB = Users.findByEmail(record.email).map(_.get)

        (userFromDB, true)
      } else (Future.successful(record), false)
    }
  }
} 
开发者ID:dsounded,项目名称:money_exchanger,代码行数:26,代码来源:Actions.scala


示例13: SecureRequest

//设置package包名称以及导入依赖的类
package io.skul.katebin.logic

import io.skul.katebin._
import io.skul.katebin.repo.Repo
import javax.inject.Inject
import play.api.mvc.Results.Status
import play.api.mvc.{ActionBuilder, Request, Result, WrappedRequest}
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

class SecureRequest[A](val user: User, request: Request[A]) extends WrappedRequest[A](request)

class SecureAction @Inject() (repo: Repo) extends ActionBuilder[SecureRequest] {

  def invokeBlock[A](req: Request[A], block: (SecureRequest[A] => Future[Result])): Future[Result] = {
    req.cookies.get(Secure.cookie).map(c => repo.getUserByCookie(c.value)).getOrElse(Future.successful(None)).flatMap {
      case Some(user) =>
        val request = new SecureRequest(user, req)
        block(request)
      case _ =>
        Future.successful(Status(401)("Unauthorized"))
    }
  }
}

object Secure {
  val cookie = "ktb-session"
} 
开发者ID:Saverin-lab,项目名称:katebin-rest,代码行数:29,代码来源:SecurityLogic.scala


示例14: Status2Controller

//设置package包名称以及导入依赖的类
package xyz.mattclifton.play.stringent.test

import play.api.mvc.{Request, AnyContent, Action, Controller}
import xyz.mattclifton.play.stringent.StringentActions
import xyz.mattclifton.play.stringent.test.helpers.FakeParsers._
import xyz.mattclifton.play.stringent.test.models.{TestResponse, TestContent}

import scala.concurrent.{ExecutionContext, Future}

class Status2Controller(implicit executionContext: ExecutionContext) extends Controller with StringentActions {
  def withBodyParser = Action.stringent.withContent[TestContent, OkResult, BadRequestResult](parse.json[TestContent]){ request =>
    Ok
  }

  def anyContent = Action.stringent.anyContent[OkResult, BadRequestResult]{ request =>
    Ok
  }

  def block = Action.stringent[OkResult, BadRequestResult]{
    Ok
  }

  def asyncBlock = Action.stringent.async[OkResult, BadRequestResult]{
    Future(Ok)
  }

  def asyncAnyContent = Action.stringent.anyContentAsync[OkResult, BadRequestResult]{ request =>
    Future(Ok)
  }

  def asyncBodyContent = Action.stringent.withContentAsync[TestContent, OkResult, BadRequestResult](parse.json[TestContent]){ request =>
    Future(Ok)
  }
} 
开发者ID:lynx44,项目名称:play-stringent,代码行数:35,代码来源:Status2Controller.scala


示例15: ResultImplicits

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

import play.api.mvc.{Request, Result}


object ResultImplicits {
  val JSON_CONTENT_TYPE: String = "application/json"

  implicit class MyResult(result: Result){
    def asJsonWithAccessControlHeaders(implicit request: Request[Any]): Result = {
      result.as(JSON_CONTENT_TYPE).withHeaders(
        "Access-Control-Allow-Origin" -> request.headers.get("Origin").getOrElse("*"),
        "Access-Control-Allow-Credentials" -> "true"
      )
    }
  }

} 
开发者ID:jeroenr,项目名称:reactive-mongo-demo,代码行数:19,代码来源:ResultImplicits.scala


示例16: 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


示例17: Route

//设置package包名称以及导入依赖的类
package com.viajobien.busy.models.routing

import com.viajobien.busy.dsl.condition.Condition
import com.viajobien.busy.models.Persistable
import play.api.mvc.{ AnyContent, Request }

abstract class Route(val path: String, endpoint: String,
    condition: Condition) extends Persistable with PathUtil {

  def satisfy(request: Request[AnyContent]): Boolean = {
    this.condition.eval(request)
  }

  def generateEndpoint(pathParameter: String): String = {
    val splittedPath = this.splitPath(this.path)
    val splittedPathParameter = this.splitPath(pathParameter, splittedPath.size)
    val zippedPath = splittedPath zip splittedPathParameter

    val wildcardsPath = zippedPath filter (z => z._1 == PATH_PART_WILDCARD || z._1 == PATH_WILDCARD)

    this.splittedEndpoint(wildcardsPath)
  }

  private def splittedEndpoint(wildcardsPath: List[(String, String)]): String = {
    def splitted(splittedEndpoint: List[String], wildcardsPath: List[(String, String)]): List[String] =
      splittedEndpoint match {
        case Nil                                        => Nil
        case (PATH_PART_WILDCARD | PATH_WILDCARD) :: es => wildcardsPath.head._2 :: splitted(es, wildcardsPath.tail)
        case e :: es                                    => e :: splitted(es, wildcardsPath)
      }

    splitted(this.splitPath(this.endpoint, dropChars = 0), wildcardsPath) mkString "/"
  }

} 
开发者ID:viajobien,项目名称:busy,代码行数:36,代码来源:Route.scala


示例18: route

//设置package包名称以及导入依赖的类
package com.viajobien.busy.models.routing

import com.viajobien.busy.repositories.Repository
import play.api.Logger
import play.api.mvc.{ AnyContent, Request }

import scala.concurrent.duration._
import scala.concurrent.{ Await, ExecutionContext, Future }
import scala.util.{ Failure, Success, Try }


  override def route(implicit req: Request[AnyContent]): Option[Endpoint] = {
    Logger.trace("routing " + req + " with routeTree " + routeTree)
    this.routeTree.find(req) match {
      case Some(rt) => Some(rt.generateEndpoint(req.path))
      case _        => None
    }
  }

}

object BasicRouter {

  var router: Option[EndpointRouter] = None

  def reload[T <: Route](repository: Repository[T])(implicit ec: ExecutionContext): EndpointRouter = {
    val basicRouter = new BasicRouter(repository)
    Await.ready(basicRouter.reload, 5.seconds)
    this.router = Some(basicRouter)
    basicRouter
  }

  def getRouter[T <: Route](repository: Repository[T])(implicit ec: ExecutionContext): EndpointRouter = {
    if (this.router.isEmpty) {
      this.reload(repository)
    }
    this.router.get
  }

} 
开发者ID:viajobien,项目名称:busy,代码行数:41,代码来源:EndpointRouter.scala


示例19: isSuccess

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

import play.api.mvc.{ Request, WrappedRequest }

trait SecureRequest[A] extends WrappedRequest[A] {
  def isSuccess: Boolean
  def isFailure: Boolean = ! isSuccess
  override def toString: String = s"SecureRequest(${SecureRequest.unapply(this).get.toString})"
}

object SecureRequest {
  def apply[A](request: Request[A]): UnauthorizedRequest[A] =
    new UnauthorizedRequest(request)

  def apply[A, S](request: Request[A], subject: S): AuthenticatedRequest[A, S] =
    new AuthenticatedRequest(request, subject)

  def anonymous[A](request: Request[A]): AuthenticatedRequest[A, _] = apply(request, None)

  def unapply[A](request: SecureRequest[A]): Option[(Request[A])]
    = Some((request.map(r => r)))
}

class AuthenticatedRequest[A, S](request: Request[A], subject: S)
  extends WrappedRequest[A](request) with SecureRequest[A] {
  def isSuccess: Boolean = true
  def get: S = subject
  override def toString: String = s"AuthenticatedRequest(${request.toString}, ${subject.toString})"
}

class AnonymousRequest[A](request: Request[A])
  extends WrappedRequest[A](request) with SecureRequest[A] {
  def isSuccess: Boolean = true
  override def toString: String = s"AnonymousRequest(${request.toString})"
}

class UnauthorizedRequest[A](request: Request[A]) extends AnonymousRequest[A](request) {
  override def isSuccess: Boolean = false
  override def toString: String = s"UnauthorizedRequest(${request.toString})"
} 
开发者ID:ejisan,项目名称:play-scalauth-secureaction,代码行数:41,代码来源:SecureRequest.scala


示例20: ChirpDeadboltHandler

//设置package包名称以及导入依赖的类
package org.birdfeed.chirp.auth.handlers

import be.objectify.deadbolt.scala.models.Subject
import be.objectify.deadbolt.scala.{AuthenticatedRequest, DeadboltHandler, DynamicResourceHandler}
import com.github.aselab.activerecord.dsl._
import com.google.inject.Inject
import org.birdfeed.chirp.database.models.AccessToken
import org.birdfeed.chirp.errors.JsonError
import play.api.mvc.{Request, Result, Results}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class ChirpDeadboltHandler @Inject() extends DeadboltHandler with JsonError {

  // TODO: Do we need these?
  override def beforeAuthCheck[A](request: Request[A]): Future[Option[Result]] = Future {None}
  override def getDynamicResourceHandler[A](request: Request[A]): Future[Option[DynamicResourceHandler]] = Future {None}

  override def getSubject[A](request: AuthenticatedRequest[A]): Future[Option[Subject]] = Future {
    for {
      headerToken <- request.headers.get("Chirp-Access-Token")
      databaseToken <- AccessToken.findBy("token", headerToken)
      if databaseToken.stillAlive
    } yield databaseToken.user.get
  }

  // TODO: Permissions error?! NOPE! DEAD ACCESS TOKEN
  // fix this and stop giving this error for everything
  override def onAuthFailure[A](request: AuthenticatedRequest[A]): Future[Result] = getSubject(request).map {
    case Some(subject) => Results.Unauthorized(jsonError("Your access token is expired, please refresh authorization."))
    case _ => Results.BadRequest(jsonError("Your access token is invalid."))
  }
} 
开发者ID:AwesomeIT,项目名称:chirp,代码行数:35,代码来源:ChirpDeadboltHandler.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala DatabaseConfigProvider类代码示例发布时间:2022-05-23
下一篇:
Scala ImplicitSender类代码示例发布时间: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