本文整理汇总了Scala中play.api.mvc.ActionBuilder类的典型用法代码示例。如果您正苦于以下问题:Scala ActionBuilder类的具体用法?Scala ActionBuilder怎么用?Scala ActionBuilder使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ActionBuilder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: 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()))
}
}
}
示例2: 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) }
}
}
}
示例3: 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"
}
示例4: aultRedirectTarget
//设置package包名称以及导入依赖的类
package controllers
import com.gu.googleauth.{Actions, UserIdentity}
import play.api.Logger
import play.api.mvc.ActionBuilder
import play.api.mvc.Security.{AuthenticatedBuilder, AuthenticatedRequest}
import Auth.AuthRequest
trait AuthActions extends Actions {
override val loginTarget = routes.AuthController.login()
override val defaultRedirectTarget = routes.MainController.index()
override val failureRedirectTarget = routes.AuthController.authError()
def enableAuth: Boolean
object DummyAuthAction
extends AuthenticatedBuilder[UserIdentity](userinfo = _ => {
Logger.info("Skipping authentication because auth is disabled")
Some(
UserIdentity(sub = "dummy.user",
email = "dummy.email",
firstName = "Dummy",
lastName = "User",
exp = Long.MaxValue,
avatarUrl = None))
})
def Authenticated: ActionBuilder[AuthRequest] =
if (enableAuth) {
AuthAction andThen LogRequest
} else
DummyAuthAction andThen LogRequest
}
示例5: AuthRequest
//设置package包名称以及导入依赖的类
package uk.gov.bis.levyApiMock.actions
import play.api.mvc.Results._
import play.api.mvc.{ActionBuilder, Request, Result, WrappedRequest}
import uk.gov.bis.levyApiMock.data.oauth2.AuthRecord
import scala.concurrent.{ExecutionContext, Future}
case class AuthRequest[+A](authRecord: AuthRecord, request: Request[A]) extends WrappedRequest(request)
trait AuthAction extends ActionBuilder[AuthRequest] {
implicit val ec: ExecutionContext
override def invokeBlock[A](request: Request[A], next: (AuthRequest[A]) => Future[Result]): Future[Result] = {
val BearerToken = "Bearer (.+)".r
request.headers.get("Authorization") match {
case Some(BearerToken(accessToken)) => validateToken(accessToken).flatMap {
case Some(authRecord) => next(AuthRequest(authRecord, request))
case None => unauthorized("Bearer token does not grant access to the requested resource")
}
case Some(h) => unauthorized("Authorization header should be a Bearer token")
case None => unauthorized("No Authorization header found")
}
}
def validateToken(accessToken: String): Future[Option[AuthRecord]]
private def unauthorized(message: String): Future[Result] = Future.successful(Unauthorized(message))
}
示例6: ConditionalLayoutRequest
//设置package包名称以及导入依赖的类
package helpers
import play.api.mvc.{ActionBuilder, WrappedRequest, Request, ActionTransformer}
import scala.concurrent.Future
trait ConditionalLayout {
class ConditionalLayoutRequest[A](val requiresLayout: Boolean,
request: Request[A]) extends WrappedRequest[A](request)
object ConditionalLayoutAction extends ActionBuilder[ConditionalLayoutRequest] with ActionTransformer[Request, ConditionalLayoutRequest] {
override protected def transform[A](request: Request[A]) = Future.successful {
val layoutRequired = request.headers.get("X-PJAX") != Some("true")
new ConditionalLayoutRequest[A](requiresLayout = layoutRequired, request)
}
}
}
示例7: MockEntityAuthController
//设置package包名称以及导入依赖的类
package scala
import com.google.inject.Inject
import com.sharecare.lib.play.authentication.EntityAuthenticatedFactory
import com.sharecare.lib.play.controllers.EntityAuthController
import com.sharecare.lib.play.security.models.{AuthenticatedRequest, EntityUser, Permissions}
import play.api.mvc.{ActionBuilder, Request, Result}
import scala.concurrent.Future
class MockEntityAuthController @Inject()(eaf: EntityAuthenticatedFactory)
extends EntityAuthController(eaf) {
object MockAuthentication extends ActionBuilder[AuthenticatedRequest] {
// only non-Option values are named
private val entityUser = EntityUser(firstName = "mock-EntityUser.firstName", None,
None, None, None, None, None, None, None, None, None, None, None, None, None, None,
None, `type` = "mock-EntityUser.type", None, None)
override def invokeBlock[A](request: Request[A],
block: (AuthenticatedRequest[A]) => Future[Result])
: Future[Result] = block(AuthenticatedRequest(Some(entityUser), request))
}
override def Entity(entityId: String, logAction: String, roles: Permissions*)
: ActionBuilder[AuthenticatedRequest] = MockAuthentication
}
开发者ID:Sharecare,项目名称:health-profile-phr-common-service-api,代码行数:29,代码来源:MockEntityAuthController.scala
示例8: UserRequest
//设置package包名称以及导入依赖的类
package controllers.security
import scala.concurrent.Future
import models.User
import play.api.mvc.{ActionBuilder, Request, Result, Results, WrappedRequest}
import services.UserService
case class UserRequest[A](val userName: String, val request: Request[A])
extends WrappedRequest[A](request)
object SecuredAction extends ActionBuilder[UserRequest] {
override def invokeBlock[A](request: Request[A],
block: (UserRequest[A]) => Future[Result]): Future[Result] = {
val userName = request.headers.get("username").fold("")(identity)
if (UserService.getAllUsers().contains(User(userName))) {
block(UserRequest(userName, request))
} else {
Future.successful(Results.Unauthorized("Unauthorized access !!"))
}
}
}
示例9: TodoRequest
//设置package包名称以及导入依赖的类
package todo
import javax.inject.{Inject, Singleton}
import play.api.http.HttpVerbs
import play.api.mvc.{ActionBuilder, Request, Result, WrappedRequest}
import scala.concurrent.{ExecutionContext, Future}
class TodoRequest[A](request: Request[A])
extends WrappedRequest(request)
@Singleton
class TodoAction @Inject()(implicit ec: ExecutionContext)
extends ActionBuilder[TodoRequest]
with HttpVerbs {
override def invokeBlock[A](request: Request[A], block: (TodoRequest[A]) => Future[Result]) = {
val future = block(new TodoRequest(request))
future.map(result => {
request.method match {
case GET | HEAD =>
result.withHeaders("Cache-Control" -> s"max-age: 1000")
case other =>
result
}
})
}
}
示例10: CheckedAction
//设置package包名称以及导入依赖的类
package microtools.actions
import microtools.models.{Problem, Problems, RequestContext}
import play.api.http.Status
import play.api.mvc.{ActionBuilder, Request, RequestHeader, Result}
import play.mvc.Http.HeaderNames
import scala.concurrent.Future
object CheckedAction {
case class RequestCondition(condition: RequestHeader => Boolean, problem: Problem)
case class CheckedAction(requirements: RequestCondition*) extends ActionBuilder[Request] {
override def invokeBlock[A](
request: Request[A],
block: (Request[A]) => Future[Result]
): Future[Result] = {
requirements
.find(!_.condition(request))
.map { failedCondition =>
Future.successful(failedCondition.problem.asResult(RequestContext.forRequest(request)))
}
.getOrElse {
block(request)
}
}
}
val RequireInternal = RequestCondition(
rh => rh.headers.get("x-zone").contains("internal"),
Problems.FORBIDDEN.withDetails("Only internal requests are allowed")
)
val RequireTLS = RequestCondition(
rh =>
rh.secure || rh.headers
.get(HeaderNames.X_FORWARDED_PROTO)
.contains("https"),
Problem
.forStatus(Status.UPGRADE_REQUIRED, "Upgrade required")
.withDetails("Require secure https")
)
}
示例11: aultRedirectTarget
//设置package包名称以及导入依赖的类
package controllers
import com.gu.googleauth.{Actions, UserIdentity}
import play.api.Logger
import play.api.mvc.ActionBuilder
import play.api.mvc.Security.{AuthenticatedBuilder, AuthenticatedRequest}
import Auth.AuthRequest
trait AuthActions extends Actions {
override val loginTarget = routes.AuthController.login()
override val defaultRedirectTarget = routes.MainController.index()
override val failureRedirectTarget = routes.AuthController.authError()
def enableAuth: Boolean
object DummyAuthAction
extends AuthenticatedBuilder[UserIdentity](userinfo = _ => {
Logger.info("Skipping authentication because auth is disabled")
Some(
UserIdentity(sub = "dummy.user",
email = "dummy.email",
firstName = "Dummy",
lastName = "User",
exp = Long.MaxValue,
avatarUrl = None))
})
def Authenticated: ActionBuilder[AuthRequest] =
if (enableAuth) {
AuthAction andThen LogRequest
} else
DummyAuthAction
}
示例12: ValidatedAuthedRequest
//设置package包名称以及导入依赖的类
package actions
import models.User
import play.api.libs.json.{JsObject, JsValue}
import play.api.mvc.{ActionBuilder, Request, Result, WrappedRequest}
import services.Response._
import services.ValidationType._
import services.{RequiredProp, Sync, Validator}
import scala.concurrent.Future
case class ValidatedAuthedRequest[A](request: Request[A], user: User) extends WrappedRequest[A](request) {}
case class ValidatedAuthedAction(validators:List[RequiredProp]) extends ActionBuilder[ValidatedAuthedRequest] {
def invokeBlock[A](request: Request[A], block: ValidatedAuthedRequest[A] => Future[Result]) = {
val validatedAction = ValidatedAction(validators)
val authedAction = AuthedAction()
request.body match {
case body:JsObject =>
val token = authedAction.getTokenFromHeaders(request)
Sync.await(authedAction.start(token)) match {
case Some(user) =>
validatedAction.start(body) match {
case Nil => block(new ValidatedAuthedRequest(request, user))
case errors => Future.successful(precondition(errors.mkString(",")))
}
case None => Future.successful(unauthorized("Authentication Failed"))
}
case default => Future.successful(precondition(""))
}
}
}
示例13: ValidatedRequest
//设置package包名称以及导入依赖的类
package actions
import play.api.Logger
import play.api.libs.json.{JsObject, JsValue, Json}
import play.api.mvc.{ActionBuilder, Request, Result, WrappedRequest}
import services.Response._
import services.ValidationType.ValidationType
import services.{RequiredProp, Validator}
import scala.concurrent.Future
case class ValidatedRequest[A](request: Request[A]) extends WrappedRequest[A](request) {}
case class ValidatedAction(requiredProps:List[RequiredProp]) extends ActionBuilder[ValidatedRequest] {
def invokeBlock[A](request: Request[A], block: ValidatedRequest[A] => Future[Result]) = {
request.body match {
case body:JsObject =>
start(body) match {
case Nil => block(new ValidatedRequest(request))
case err => Future.successful(errors(Json.toJson(err)))
}
case default => Future.successful(precondition())
}
}
def start(body:JsObject): List[String] = {
val missingPropertyErrors = validateKeys(body, requiredProps.map(_.propName))
if(missingPropertyErrors.nonEmpty) missingPropertyErrors
else validateProps(body)
}
def validateKeys(body: JsValue, validators:List[String]): List[String] = {
validators.map(propThatShouldExist => {
(body \ propThatShouldExist).asOpt[String] match {
case Some(prop) => ""
case None => "Missing Property: " + propThatShouldExist
}
}).filterNot(_.isEmpty)
}
def validateProps(body: JsValue): List[String] = {
val typedValidators = jsonBody(body)
Validator(typedValidators).validate
}
def jsonBody(body: JsValue): Map[String, (String, List[ValidationType])] = {
requiredProps.foldLeft(Map[String, (String, List[ValidationType])]()){ (onGoing, propertyAndType) =>
onGoing + (propertyAndType.propName -> ((body \ propertyAndType.propName).as[String], propertyAndType.propValidators))
}
}
}
示例14: AuthedRequest
//设置package包名称以及导入依赖的类
package actions
import database.couchbase.Buckets
import models.{AuthToken, User}
import play.api.Logger
import play.api.libs.json.{JsObject, JsValue}
import play.api.mvc.{ActionBuilder, Request, Result, WrappedRequest}
import services.Response._
import services.ValidationType.ValidationType
import services.{Sync, Validator}
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
case class AuthedRequest[A](request: Request[A], user:User) extends WrappedRequest[A](request) {}
case class AuthedAction() extends ActionBuilder[AuthedRequest] {
def invokeBlock[A](request: Request[A], block: AuthedRequest[A] => Future[Result]) = {
val token = getTokenFromHeaders[A](request)
Sync.await(start(token)) match {
case Some(user) => block(new AuthedRequest(request, user))
case None => Future.successful(unauthorized("Authentication Failed"))
}
}
def start(token:String): Future[Option[User]] = {
if(token.isEmpty) return Future.successful(None)
Sync.await(checkToken(token)) match {
case Some(id) =>
Sync.await(getUser(id)) match {
case Some(user) => Future.successful(Option{user})
case None => Future.successful(None)
}
case None => Future.successful(None)
}
}
def getTokenFromHeaders[A](request: Request[A]): String = request.headers.toSimpleMap.getOrElse("X-Requested-With", "")
def checkToken(token:String): Future[Option[Long]] = {
val exists = Sync.await(Buckets.primaryBucket.exists(AuthToken.documentKey(token)))
if(!exists) return Future.successful(Option.empty)
for(userIdDocument <- Buckets.primaryBucket.getId(AuthToken.documentKey(token)))
yield userIdDocument match {
case Some(doc) => Option{doc.content()}
case None => None
}
}
def getUser(id:Long): Future[Option[User]] = {
for (userDocument <- Buckets.primaryBucket.get(User.documentKey(id)))
yield userDocument match {
case Some(doc) => Option{User.from(doc.content())}
case None => None
}
}
}
示例15: LoggingAction
//设置package包名称以及导入依赖的类
package actions
import scala.concurrent.Future
import scala.util.{Failure, Success}
import play.api.mvc.{Result, Request, ActionBuilder}
import play.api.Logger
object LoggingAction extends ActionBuilder[Request] {
import scala.concurrent.ExecutionContext.Implicits.global
override def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = {
val now = System.currentTimeMillis()
Logger.info("Start action")
val result = block(request)
result.andThen {
case Success(r) =>
Logger.info(s"End action\nDuration: ${System.currentTimeMillis()-now}, Result: ${r.toString}")
case Failure(t) =>
Logger.info(s"Failed action\nDuration: ${System.currentTimeMillis()-now}, Result: ${t.getMessage}")
}
}
}