本文整理汇总了Scala中play.api.mvc.ActionBuilder类的典型用法代码示例。如果您正苦于以下问题:Scala ActionBuilder类的具体用法?Scala ActionBuilder怎么用?Scala ActionBuilder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ActionBuilder类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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()))
}
}
}
开发者ID:kogai,项目名称:kakei-log,代码行数:23,代码来源:AuthAction.scala
示例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) }
}
}
}
开发者ID:mubeenahmed,项目名称:MeGuideApi,代码行数:24,代码来源:TokenChecker.scala
示例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"
}
开发者ID:Saverin-lab,项目名称:katebin-rest,代码行数:29,代码来源:SecurityLogic.scala
示例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
}
开发者ID:ovotech,项目名称:comms-template-manager,代码行数:35,代码来源:AuthActions.scala
示例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))
}
开发者ID:UKGovernmentBEIS,项目名称:das-alpha-hmrc-api-mock,代码行数:31,代码来源:AuthAction.scala
示例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)
}
}
}
开发者ID:tobnee,项目名称:sirenator,代码行数:19,代码来源:ConditionalLayout.scala
示例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 !!"))
}
}
}
开发者ID:geetikagupta16,项目名称:PlayAuthentication,代码行数:24,代码来源:SecuredAction.scala
示例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
}
})
}
}
开发者ID:jeroenbellen,项目名称:todo-app,代码行数:33,代码来源:TodoAction.scala
示例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")
)
}
开发者ID:21re,项目名称:play-micro-tools,代码行数:46,代码来源:CheckedAction.scala
示例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
}
开发者ID:ovotech,项目名称:comms-audit-log,代码行数:35,代码来源:AuthActions.scala
示例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(""))
}
}
}
开发者ID:ShaiJames,项目名称:Play-Couchbase-Template,代码行数:32,代码来源:ValidatedAuthedAction.scala
示例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))
}
}
}
开发者ID:ShaiJames,项目名称:Play-Couchbase-Template,代码行数:52,代码来源:ValidatedAction.scala
示例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
}
}
}
开发者ID:ShaiJames,项目名称:Play-Couchbase-Template,代码行数:59,代码来源:AuthedAction.scala
示例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}")
}
}
}
开发者ID:hideto0710,项目名称:play-2_3-action_composition,代码行数:24,代码来源:LoggingAction.scala
示例16: User
//设置package包名称以及导入依赖的类
package actions
import play.api.mvc.{ActionBuilder, Request, Result}
import scala.concurrent.Future
case class User(name: String)
case class UserRequest[A](val user: User, r: Request[A]) extends Request[A] {
override def id = r.id
override def tags = r.tags
override def uri = r.uri
override def path = r.path
override def method = r.method
override def version = r.version
override def queryString = r.queryString
override def headers = r.headers
override def secure = r.secure
override lazy val remoteAddress = r.remoteAddress
override val body = r.body
}
object UserAction extends ActionBuilder[UserRequest] {
def invokeBlock[A](request: Request[A], block: (UserRequest[A]) => Future[Result]) = {
block(UserRequest(User("mike"), request))
}
}
开发者ID:hideto0710,项目名称:play-2_3-action_composition,代码行数:27,代码来源:UserAction.scala
示例17: AppLoader
//设置package包名称以及导入依赖的类
package com.malliina.app
import buildinfo.BuildInfo
import com.malliina.logstreams.auth.{Auths, UserService}
import com.malliina.logstreams.db.{DatabaseAuth, UserDB}
import com.malliina.logstreams.tags.Htmls
import com.malliina.oauth.{GoogleOAuthCredentials, GoogleOAuthReader}
import com.malliina.play.ActorExecution
import com.malliina.play.app.DefaultApp
import controllers._
import play.api.ApplicationLoader.Context
import play.api._
import play.api.mvc.{ActionBuilder, AnyContent, Request}
import play.api.routing.Router
import play.filters.HttpFiltersComponents
import router.Routes
import scala.concurrent.{ExecutionContext, Future}
class AppLoader extends DefaultApp(new ProdAppComponents(_))
class ProdAppComponents(ctx: Context)
extends AppComponents(ctx, GoogleOAuthReader.load, ec => UserDB.default()(ec)) {
override lazy val auth = new WebAuth(authImpl)
}
abstract class AppComponents(context: Context,
creds: GoogleOAuthCredentials,
db: ExecutionContext => UserDB)
extends BuiltInComponentsFromContext(context)
with HttpFiltersComponents
with AssetsComponents {
implicit val ec = materializer.executionContext
def auth: LogAuth
val actions: ActionBuilder[Request, AnyContent] = controllerComponents.actionBuilder
// Services
lazy val isProd = environment.mode == Mode.Prod
lazy val htmls = Htmls.forApp(BuildInfo.frontName, isProd)
val database = db(ec)
lazy val users: UserService = DatabaseAuth(database)
lazy val listenerAuth = Auths.viewers(auth)
lazy val sourceAuth = Auths.sources(users)
lazy val oauth = new OAuth(actions, creds, materializer)
lazy val authImpl = new OAuthCtrl(oauth)
lazy val deps = ActorExecution(actorSystem, materializer)
// Controllers
lazy val home = new Logs(htmls, auth, users, deps, controllerComponents)
lazy val sockets = new SocketsBundle(listenerAuth, sourceAuth, deps)
override lazy val router: Router = new Routes(httpErrorHandler, home, sockets, oauth, assets)
applicationLifecycle.addStopHook(() => Future.successful {
database.close()
})
}
开发者ID:malliina,项目名称:logstreams,代码行数:59,代码来源:AppLoader.scala
示例18: TestAuth
//设置package包名称以及导入依赖的类
package tests
import com.malliina.play.auth.InvalidCredentials
import com.malliina.play.models.Username
import controllers.{LogAuth, UserRequest}
import play.api.mvc.{ActionBuilder, _}
import scala.concurrent.Future
class TestAuth(actions: ActionBuilder[Request, AnyContent]) extends LogAuth {
val testUser = Username("testuser")
override def authAction(f: UserRequest => EssentialAction): EssentialAction =
EssentialAction { rh =>
f(UserRequest(testUser, rh)).apply(rh)
}
override def withAuthAsync(f: UserRequest => Future[Result]) =
actions.async { req =>
f(UserRequest(testUser, req))
}
override def withAuth(f: UserRequest => Result): EssentialAction =
actions { req =>
f(UserRequest(testUser, req))
}
override def authenticateSocket(rh: RequestHeader): Future[Either[InvalidCredentials, UserRequest]] =
Future.successful(Right(UserRequest(testUser, rh)))
}
开发者ID:malliina,项目名称:logstreams,代码行数:31,代码来源:TestAuth.scala
示例19: AdminAction
//设置package包名称以及导入依赖的类
package controllers.composition
import javax.inject.Inject
import controllers.routes
import play.api.Logger
import play.api.db.Database
import play.api.mvc.{ActionBuilder, Request, Result, Results}
import services.intern.database.{AdminUser, User, UserService}
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
class AdminAction @Inject()(implicit db: Database) extends ActionBuilder[AdminRequest] {
override def invokeBlock[A](request: Request[A], block: (AdminRequest[A]) => Future[Result]): Future[Result] = {
def handleForbidden(user: Option[User] = None): Future[Result] = {
Future {
user match {
case Some(u) => Logger
.info(s"${request.uri} redirected to login page cause user: ${u.login} is not admin: ${u.admin}")
case None => Logger.info(s"${request.uri} redirected to login page cause no user")
}
Results.Redirect(controllers.authentication.routes.AuthenticationController.login())
.flashing("actionRequested" -> s"${request.uri}")
}
}
val userId = getUserFromRequest(request)
userId match {
case Some(id) =>
db.withConnection { implicit conn =>
val user = UserService.findById(id)
user match {
case Some(u) =>
u match {
case admin: AdminUser => block(new AdminRequest[A](admin, request));
case _ => handleForbidden(user)
}
case None => handleForbidden()
}
}
case None =>
handleForbidden()
}
}
}
开发者ID:tweissbeck,项目名称:guild-forum,代码行数:49,代码来源:AdminAction.scala
示例20: TenantAction
//设置package包名称以及导入依赖的类
package controllers
import models.TenantKey
import play.api.libs.json.Json
import play.api.mvc.{ActionBuilder, Request, Result, Results}
import scala.concurrent.Future
object TenantAction extends ActionBuilder[Request] with Results with Logging {
override def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]): Future[Result] = {
val token = request.headers.get("tenant-key")
//Todo : Secret to be retrieved from Database based on the device_id passed in
val secret = "secret"
token match {
case Some(strToken) => {
val tenantKey = new TenantKey(strToken, secret)
println("Tenant Token ::: " + tenantKey.claim.get.toString)
if (tenantKey.validate()) block(request) else Future.successful(Unauthorized(Json.obj("message" -> "Invalid Tenant Key")))
}
case None => {
Future.successful(Unauthorized(Json.obj("message" -> "Tenant Key Not Found")))
}
}
}
}
开发者ID:a605269,项目名称:play-multitenant,代码行数:30,代码来源:TenantAction.scala
注:本文中的play.api.mvc.ActionBuilder类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论