本文整理汇总了Scala中play.api.mvc.Request类的典型用法代码示例。如果您正苦于以下问题:Scala Request类的具体用法?Scala Request怎么用?Scala Request使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Request类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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))
}
}
示例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)
}
示例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()))
}
}
}
示例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) }
}
}
}
示例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)
}
}
示例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)
})
}
示例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()) }
}
}
示例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)
}
}
示例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 = "-"
}
}
示例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
}
示例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)
}
示例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)
}
}
}
示例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"
}
示例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)
}
}
示例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"
)
}
}
}