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

Scala Directive1类代码示例

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

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



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

示例1: extractBearerToken

//设置package包名称以及导入依赖的类
package com.github.cupenya.microservices.sdk.authentication

import akka.http.scaladsl.model.headers.{Authorization, OAuth2BearerToken}
import akka.http.scaladsl.server.{AuthorizationFailedRejection, Directive1, Directives}
import com.github.cupenya.microservices.sdk.logging.Logging

import scala.concurrent.ExecutionContext

trait AuthorizationDirectives extends Logging {
  self: Directives =>

  implicit val ec: ExecutionContext

  // TODO: dep injection
  private val tokenVerifier = new JwtTokenVerifier

  private def extractBearerToken(authHeader: Option[Authorization]): Option[String] =
    authHeader.collect {
      case Authorization(OAuth2BearerToken(token)) => token
    }

  def authorized: Directive1[AuthInfo] = {
    optionalHeaderValueByType(classOf[Authorization]).map(extractBearerToken).flatMap {
      case Some(token) =>
        onComplete(tokenVerifier.verifyToken(token)).flatMap { x =>
          x.map(authInfo => provide(authInfo))
            .recover {
              case ex =>
                log.error("Couldn't log in using provided authorization token", ex)
                reject(AuthorizationFailedRejection).toDirective[Tuple1[AuthInfo]]
            }
            .get
        }
      case None =>
        reject(AuthorizationFailedRejection)
    }
  }
} 
开发者ID:cupenya,项目名称:microservices-sdk,代码行数:39,代码来源:AuthorizationDirectives.scala


示例2: In

//设置package包名称以及导入依赖的类
package akka.http.documenteddsl.directives

import akka.http.documenteddsl.PreprocessedFromEntityUnmarshaller
import akka.http.documenteddsl.documentation.RouteDocumentation
import akka.http.scaladsl.server.Directive1
import akka.http.scaladsl.unmarshalling._
import org.coursera.autoschema.AutoSchema
import play.api.libs.json.{Reads, Writes}

import scala.reflect.runtime.{universe => ru}

trait MarshallingDDirectives {

  final class In[T](example: Option[T] = None)(implicit um: PreprocessedFromEntityUnmarshaller[T], ev: ru.TypeTag[T], writes: Writes[T], reads: Reads[T]) extends DDirective1[T] {
    import akka.http.scaladsl.server.directives.MarshallingDirectives._
    import um.fsu
    def describe(w: RouteDocumentation)(implicit as: AutoSchema): RouteDocumentation = w.in[T](example map writes.writes)
    def delegate: Directive1[T] = entity(as[T])
  }

  object In {
    def apply[T](implicit um: PreprocessedFromEntityUnmarshaller[T], ev: ru.TypeTag[T], writes: Writes[T], reads: Reads[T]): In[T] = new In()
    def apply[T](example: T)(implicit um: PreprocessedFromEntityUnmarshaller[T], ev: ru.TypeTag[T], writes: Writes[T], reads: Reads[T]): In[T] = new In(Some(example))
  }
}

object MarshallingDDirectives extends MarshallingDDirectives 
开发者ID:evolution-gaming,项目名称:akka-http-documenteddsl,代码行数:28,代码来源:MarshallingDDirectives.scala


示例3: authenticate

//设置package包名称以及导入依赖的类
package com.noedominguez.class_orchestration.restapi.http

import akka.http.scaladsl.server.directives.{BasicDirectives, FutureDirectives, HeaderDirectives, RouteDirectives}
import akka.http.scaladsl.server.Directive1
import com.noedominguez.class_orchestration.restapi.models.UserEntity
import com.noedominguez.class_orchestration.restapi.services.AuthService

trait SecurityDirectives {

  import BasicDirectives._
  import HeaderDirectives._
  import RouteDirectives._
  import FutureDirectives._

  def authenticate: Directive1[UserEntity] = {
    headerValueByName("Token").flatMap { token =>
      onSuccess(authService.authenticate(token)).flatMap {
        case Some(user) => provide(user)
        case None       => reject
      }
    }
  }

  protected val authService: AuthService

} 
开发者ID:poguez,项目名称:class_orchestration_api,代码行数:27,代码来源:SecurityDirectives.scala


示例4: authenticate

//设置package包名称以及导入依赖的类
package de.innfactory.bootstrap.http

import akka.http.scaladsl.server.Directive1
import akka.http.scaladsl.server.directives.{BasicDirectives, FutureDirectives, HeaderDirectives, RouteDirectives}
import de.innfactory.bootstrap.services.AuthService
import de.innfactory.bootstrap.utils.Configuration

trait SecurityDirectives extends Configuration {

  import BasicDirectives._
  import FutureDirectives._
  import HeaderDirectives._
  import RouteDirectives._

  def authenticate: Directive1[Map[String, AnyRef]] = {
    if(allowAll){
      provide(Map())
    }else {
      headerValueByName("Authorization").flatMap { token =>
        onSuccess(authService.authenticate(token)).flatMap {
          case Some(user) => provide(user)
          case None => reject
        }
      }
    }
  }

  protected val authService: AuthService

} 
开发者ID:innFactory,项目名称:bootstrap-akka-http,代码行数:31,代码来源:SecurityDirectives.scala


示例5: authenticate

//设置package包名称以及导入依赖的类
package me.archdev.restapi.http

import akka.http.scaladsl.server.directives.{ RouteDirectives, BasicDirectives, HeaderDirectives, FutureDirectives }
import akka.http.scaladsl.server.Directive1
import me.archdev.restapi.models.UserEntity
import me.archdev.restapi.services.AuthService

trait SecurityDirectives {

  import BasicDirectives._
  import HeaderDirectives._
  import RouteDirectives._
  import FutureDirectives._

  def authenticate: Directive1[UserEntity] = {
    headerValueByName("Token").flatMap { token =>
      onSuccess(AuthService.authenticate(token)).flatMap {
        case Some(user) => provide(user)
        case None       => reject
      }
    }
  }

} 
开发者ID:samuelmartingc,项目名称:Akka-REST-service,代码行数:25,代码来源:SecurityDirectives.scala


示例6: Page

//设置package包名称以及导入依赖的类
package de.choffmeister.microserviceutils.http

import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{Directive1, MalformedQueryParamRejection}

final case class Page(number: Int, length: Int, totalLength: Option[Int] = None) {
  require(length > 0, "Page length must be positive")

  def firstNumber = 0
  def previousNumber = if (number > 0) Some(number - 1) else None
  def nextNumber = totalLength match {
    case None =>
      Some(number + 1)
    case Some(0) =>
      None
    case Some(tl) =>
      val pageCount = ceilIntDivision(tl, length)
      if (number < pageCount - 1) Some(number + 1)
      else None
  }
  def lastNumber = totalLength.flatMap {
    case 0 => None
    case tl => Some(ceilIntDivision(tl, length) - 1)
  }

  private def ceilIntDivision(a: Int, b: Int): Int =
    a % b match {
      case 0 => a / b
      case _ => a / b + 1
    }
}

trait PagingDirective {
  def paging(defaultLength: Int, totalLength: Option[Int] = None): Directive1[Page] = {
    require(defaultLength > 0, "Default page length must be positive")

    parameters('page.as[Int].?, 'length.as[Int].?)
      .tmap {
        case (page, length) => (page.getOrElse(0), length.getOrElse(defaultLength))
      }
      .tflatMap {
        case (page, _) if page < 0 => reject(MalformedQueryParamRejection("page", "Page number must not be negative"))
        case (_, length) if length < 1 => reject(MalformedQueryParamRejection("length", "Page length must be positive"))
        case (page, length) => provide(Page(page, length, totalLength))
      }
  }
} 
开发者ID:choffmeister,项目名称:microservice-utils,代码行数:48,代码来源:PagingDirective.scala


示例7: withBlock

//设置package包名称以及导入依赖的类
package scorex.api.http

import akka.http.scaladsl.server.Directive1
import com.wavesplatform.state2.ByteStr
import scorex.block.Block
import scorex.transaction.{History, TransactionParser}


trait CommonApiFunctions { this: ApiRoute =>
  protected[api] def withBlock(history: History, encodedSignature: String): Directive1[Block] =
  if (encodedSignature.length > TransactionParser.SignatureStringLength) complete(InvalidSignature) else {
    ByteStr.decodeBase58(encodedSignature).toOption.toRight(InvalidSignature)
        .flatMap(s => history.blockById(s).toRight(BlockNotExists)) match {
      case Right(b) => provide(b)
      case Left(e) => complete(e)
    }
  }
} 
开发者ID:wavesplatform,项目名称:Waves,代码行数:19,代码来源:CommonApiFunctions.scala


示例8: authenticate

//设置package包名称以及导入依赖的类
package smarthouse.restapi.http

import akka.http.scaladsl.server.directives.{BasicDirectives, FutureDirectives, HeaderDirectives, RouteDirectives}
import akka.http.scaladsl.server.Directive1
import smarthouse.restapi.models.UserEntity
import smarthouse.restapi.services.AuthService

trait SecurityDirectives {

  import BasicDirectives._
  import HeaderDirectives._
  import RouteDirectives._
  import FutureDirectives._

  def authenticate: Directive1[UserEntity] = {
    headerValueByName("Token").flatMap { token =>
      onSuccess(authService.authenticate(token)).flatMap {
        case Some(user) => provide(user)
        case None       => reject
      }
    }
  }

  protected val authService: AuthService

} 
开发者ID:andrewobukhov,项目名称:smart-house,代码行数:27,代码来源:SecurityDirectives.scala


示例9: auth0VerifierActor

//设置package包名称以及导入依赖的类
package org.dohrm.auth0.directives

import akka.actor.{ActorRef, ActorSystem}
import akka.http.scaladsl.model.headers.HttpChallenge
import akka.http.scaladsl.server.{AuthenticationFailedRejection, Directive1, Rejection}
import akka.pattern._
import akka.stream.ActorMaterializer
import akka.util.Timeout
import org.dohrm.auth0.actors.Auth0VerifierRequest
import org.dohrm.auth0.models.Auth0User

import scala.concurrent.ExecutionContext
import scala.util.{Failure, Success}


trait Auth0 {

  implicit val ec: ExecutionContext
  implicit val as: ActorSystem
  implicit val am: ActorMaterializer
  implicit val actorTimeout: Timeout

  import akka.http.scaladsl.server.Directives._

  def auth0VerifierActor: ActorRef

  private def bearerToken: Directive1[Option[String]] =
    for {
      authBearerHeader <- optionalHeaderValueByName("Authorization").map(extractBearerToken)
      xAuthCookie <- optionalCookie("X-Authorization-Token").map(_.map(_.value))
    } yield authBearerHeader.orElse(xAuthCookie)

  private def extractBearerToken(authHeader: Option[String]): Option[String] =
    authHeader.filter(_.startsWith("Bearer ")).map(token => token.substring("Bearer ".length))

  private def authRejection: Rejection = AuthenticationFailedRejection(AuthenticationFailedRejection.CredentialsRejected, HttpChallenge("", ""))

  def authorized: Directive1[Auth0User] = {
    bearerToken.flatMap {
      case Some(token) =>
        onComplete((auth0VerifierActor ? Auth0VerifierRequest(token)).mapTo[Auth0User]).flatMap {
          case Success(token: Auth0User) =>
            provide(token)
          case Failure(ex) =>
            //logger.error(ex, "Couldn't log in using provided authorization token")
            reject(authRejection).toDirective[Tuple1[Auth0User]]
          case _ =>
            reject(authRejection).toDirective[Tuple1[Auth0User]]
        }
      case None =>
        reject(authRejection)
    }
  }

} 
开发者ID:dohr-michael,项目名称:storyline,代码行数:56,代码来源:Auth0.scala


示例10: authenticate

//设置package包名称以及导入依赖的类
package app.board.http

import akka.http.scaladsl.server.directives.{ RouteDirectives, BasicDirectives, HeaderDirectives, FutureDirectives }
import akka.http.scaladsl.server.Directive1
import app.board.models.UserEntity
import app.board.services.AuthService
import app.board.services.ArticlesService

trait SecurityDirectives {

  import BasicDirectives._
  import HeaderDirectives._
  import RouteDirectives._
  import FutureDirectives._

  def authenticate: Directive1[UserEntity] = {
    headerValueByName("Token").flatMap { token =>
      onSuccess(authService.authenticate(token)).flatMap {
        case Some(user) => provide(user)
        case None       => reject
      }
    }
  }

  protected val authService: AuthService
//  protected val articlesService: ArticlesService

} 
开发者ID:hwshim0810,项目名称:scalable-board,代码行数:29,代码来源:SecurityDirectives.scala


示例11: requireSession

//设置package包名称以及导入依赖的类
package nl.tradecloud.common.utils.session

import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{AuthorizationFailedRejection, Directive1}

trait SessionDirectives[T <: AnyRef] {
  val sessionManager: SessionManager[T]

  protected[this] def requireSession: Directive1[T] = {
    optionalHeaderValueByName(sessionManager.headerName).flatMap {
      case Some(token: String) =>
        sessionManager.decode(token)
          .map(provide)
          .getOrElse(reject(AuthorizationFailedRejection))
      case _ =>
        reject(AuthorizationFailedRejection)
    }
  }

} 
开发者ID:tradecloud,项目名称:tradecloud-microservices-demo,代码行数:21,代码来源:SessionDirectives.scala


示例12: Route

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

import akka.http.scaladsl.model.{StatusCodes, HttpEntity, ContentTypes}
import akka.http.scaladsl.server.{Directive1, Directives}
import com.example.model.Post
import com.example.service.{Health, HealthCheckService, PostService}

import scala.concurrent.Future

class Route(postService: PostService, healthCheckService: HealthCheckService) extends Directives {

  private[this] def fetchPosts: Directive1[Seq[Post]] = {
    import scala.concurrent.ExecutionContext.Implicits.global

    onSuccess(Future(postService.all()))
  }

  private[this] def createPost(title: String, content: String): Directive1[Seq[Post]] = {
    import scala.concurrent.ExecutionContext.Implicits.global

    onSuccess {
      Future(postService.create(title, content)).map(_ => postService.all())
    }
  }

  private[this] def index(posts: Seq[Post]) = {
    complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, html.index.render(posts).body))
  }

  val route = pathSingleSlash {
    fetchPosts(index)
  } ~ path("post") {
    post {
      formFields('title, 'content) { (title, content) =>
        createPost(title, content)(index)
      }
    } ~ get {
      fetchPosts(index)
    }
  } ~ path("health") {
    healthCheckService.health() match {
      case Health.Healthy => complete("ok")
      case Health.Unhealthy => complete(StatusCodes.ServiceUnavailable)
    }
  }
} 
开发者ID:ocadaruma,项目名称:introduction-to-kubernetes,代码行数:47,代码来源:Route.scala


示例13: authenticate

//设置package包名称以及导入依赖的类
package synahive.restapi.http

import akka.http.scaladsl.server.directives.{ RouteDirectives, BasicDirectives, HeaderDirectives, FutureDirectives }
import akka.http.scaladsl.server.Directive1
import synahive.restapi.models.UserEntity
import synahive.restapi.services.AuthService

trait SecurityDirectives {

  import BasicDirectives._
  import HeaderDirectives._
  import RouteDirectives._
  import FutureDirectives._

  def authenticate: Directive1[UserEntity] = {
    headerValueByName("Token").flatMap { token =>
      onSuccess(AuthService.authenticate(token)).flatMap {
        case Some(user) => provide(user)
        case None       => reject
      }
    }
  }

} 
开发者ID:synahive,项目名称:synahive-server,代码行数:25,代码来源:SecurityDirectives.scala


示例14: authHeaders

//设置package包名称以及导入依赖的类
package com.wehkamp.basket.auth

import AuthHeaders._
import akka.http.scaladsl.server.{Directive1, Directives}
import akka.shapeless.HNil

trait AuthDirectives extends Directives {
  
  def authHeaders: Directive1[Identity] = {
    val shopper = headerValueByName(AuthShopperHeader.Name)
    val anonymousShopper = optionalHeaderValueByName(AuthAnonymousShopperHeader.Name)
    val level = headerValueByName(AuthLevelHeader.Name)
    val tokenId = headerValueByName(AuthTokenIdHeader.Name)
    val ipAddress = extractClientIP

    val a = shopper & anonymousShopper & level & tokenId & ipAddress
    a tflatMap  {
      case shopperId :: Some(anonymousShopperId) :: authLevel :: tokenId :: clientIp :: HNil if (anonymousShopperId.isEmpty) ? provide(Identity(shopperId, None, authLevel, tokenId, clientIp))
      case shopperId :: anonymousShopperId :: authLevel :: tokenId :: clientIp :: HNil                                       ? provide(Identity(shopperId, anonymousShopperId, authLevel, tokenId, clientIp))
    }

  }

} 
开发者ID:octavz,项目名称:cart,代码行数:25,代码来源:AuthDirectives.scala


示例15: authenticate

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

import akka.http.scaladsl.server.Directive1
import akka.http.scaladsl.server.directives.{BasicDirectives, FutureDirectives, HeaderDirectives, RouteDirectives}
import $package$.services.AuthService
import $package$.utils.Configuration

trait SecurityDirectives extends Configuration {

  import BasicDirectives._
  import FutureDirectives._
  import HeaderDirectives._
  import RouteDirectives._

  def authenticate: Directive1[Map[String, AnyRef]] = {
    if(allowAll){
      provide(Map())
    }else {
      headerValueByName("Authorization").flatMap { token =>
        onSuccess(authService.authenticate(token)).flatMap {
          case Some(user) => provide(user)
          case None => reject
        }
      }
    }
  }

  protected val authService: AuthService

} 
开发者ID:innFactory,项目名称:bootstrap-akka-http.g8,代码行数:31,代码来源:SecurityDirectives.scala


示例16: ValidationDirective

//设置package包名称以及导入依赖的类
package io.akka.http.validation

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.server.{Directive1, ValidationRejection}
import spray.json.DefaultJsonProtocol
import akka.http.scaladsl.server.Directives._

import scala.util.{Failure, Success, Try}


object ValidationDirective extends SprayJsonSupport with DefaultJsonProtocol {

  import akka.http.scaladsl.server.Rejection

  final case class FieldRule[-M](fieldName: String, isInvalid: M => Boolean, errorMsg: String)
  final case class FieldErrorInfo(name: String, error: String)
  final case class ModelValidationRejection(invalidFields: Set[FieldErrorInfo]) extends Rejection

  implicit val validatedFieldFormat = jsonFormat2(FieldErrorInfo)

  private def caseClassFields[M <: Any](obj: AnyRef): Seq[(String, M)] = {
    val metaClass = obj.getClass
    metaClass.getDeclaredFields.map {
      field => {
        field.setAccessible(true)
        (field.getName, field.get(obj).asInstanceOf[M])
      }
    }
  }

  def validateModel[T, M <: Any](model: T, rules: FieldRule[M]*): Directive1[T] = {
    import scala.collection.mutable.Set
    val errorsSet: Set[FieldErrorInfo] = Set[FieldErrorInfo]()
    val keyValuePairs: Seq[(String, M)] = caseClassFields(model.asInstanceOf[AnyRef])
    Try {
      rules.map { rule =>
        keyValuePairs.find(_._1 == rule.fieldName) match {
          case None => throw new IllegalArgumentException(s"No such field for validation: ${rule.fieldName}")
          case Some(pair) => {
            if (rule.isInvalid(pair._2)) errorsSet += FieldErrorInfo(rule.fieldName, rule.errorMsg)
          }
        }
      }
      errorsSet.toSet[FieldErrorInfo]
    } match {
      case Success(set) => if (set.isEmpty) provide(model) else reject(ModelValidationRejection(set))
      case Failure(ex) => reject(ValidationRejection(ex.getMessage))
    }
  }
} 
开发者ID:Fruzenshtein,项目名称:akka-http-validation,代码行数:51,代码来源:ValidationDirective.scala


示例17: withBlock

//设置package包名称以及导入依赖的类
package scorex.api.http

import akka.http.scaladsl.server.Directive1
import com.wavesplatform.state2.ByteStr
import scorex.block.Block
import scorex.crypto.encode.Base58
import scorex.transaction.{History, TransactionParser}


trait CommonApiFunctions { this: ApiRoute =>
  protected[api] def withBlock(history: History, encodedSignature: String): Directive1[Block] =
  if (encodedSignature.length > TransactionParser.SignatureStringLength) complete(InvalidSignature) else {
    ByteStr.decodeBase58(encodedSignature).toOption.toRight(InvalidSignature)
        .flatMap(s => history.blockById(s).toRight(BlockNotExists)) match {
      case Right(b) => provide(b)
      case Left(e) => complete(e)
    }
  }
} 
开发者ID:mikepijn,项目名称:wavesnode,代码行数:20,代码来源:CommonApiFunctions.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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