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