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

Scala RequestHeader类代码示例

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

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



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

示例1: CustomCORSFilter

//设置package包名称以及导入依赖的类
package filters

import javax.inject.{Inject, Singleton}

import akka.stream.Materializer
import play.api.http.HeaderNames
import play.api.mvc.{Filter, RequestHeader, Result}
import play.filters.cors.CORSFilter

import scala.concurrent.{ExecutionContext, Future}


@Singleton
class CustomCORSFilter @Inject()(corsFilter: CORSFilter)
                                (implicit override val mat: Materializer,
                                 exec: ExecutionContext) extends Filter {

  override def apply(nextFilter: RequestHeader => Future[Result])
                    (requestHeader: RequestHeader): Future[Result] = {
    requestHeader.headers.get(HeaderNames.ORIGIN) match {
      case (Some("null")) =>
        val newHeaders = requestHeader.headers
          .remove(HeaderNames.ORIGIN)
          .add(HeaderNames.ORIGIN -> "http://file.url.local.null")
        val mappedOrigin = requestHeader.copy(headers = newHeaders)
        corsFilter(nextFilter)(mappedOrigin)
          .map { result =>
            result.withHeaders(HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN -> "null")
          }
      case _ => corsFilter(nextFilter)(requestHeader)
    }
  }
} 
开发者ID:umbc-cmcs447-grp,项目名称:rest-api,代码行数:34,代码来源:CustomCORSFilter.scala


示例2: UserFeedback

//设置package包名称以及导入依赖的类
package controllers

import play.api.data.Form
import play.api.mvc.{Flash, RequestHeader}
import UserFeedback.{Feedback, Success, Yes, No}

case class UserFeedback(message: String, isError: Boolean) {
  def toSeq: Seq[(String, String)] = Seq(
    Feedback -> message,
    Success -> (if (isError) No else Yes)
  )
}

object UserFeedback {
  val Feedback = "feedback"
  val Success = "success"
  val Yes = "yes"
  val No = "no"

  def success(message: String) = UserFeedback(message, isError = false)

  def error(message: String) = UserFeedback(message, isError = true)

  def flashed(request: RequestHeader): Option[UserFeedback] =
    flashed(request.flash)

  def flashed(flash: Flash, textKey: String = Feedback): Option[UserFeedback] =
    for {
      message <- flash get textKey
      isError = (flash get Success) contains No
    } yield UserFeedback(message, isError)

  def formed(form: Form[_]) =
    form.globalError.orElse(form.errors.headOption)
      .map(formError => error(formError.message))
} 
开发者ID:malliina,项目名称:logstreams,代码行数:37,代码来源:UserFeedback.scala


示例3: HelpController

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

import controllers.{ HasVisitLogging, WebJarAssets }
import javax.inject.{ Inject, Singleton }
import models.visit.VisitService
import play.api.mvc.{ Action, Controller, RequestHeader }
import play.twirl.api.HtmlFormat

@Singleton
class HelpController @Inject() (
    implicit val visits: VisitService,
    implicit val webjars: WebJarAssets
  ) extends Controller with HasVisitLogging {

  private def result(template: HtmlFormat.Appendable)(implicit request: RequestHeader) = {
    logPageView()
    Ok(template)
  }

  def index = Action { Redirect(routes.HelpController.showTutorial()) }

  def showTutorial  = Action { implicit request => result(views.html.help.tutorial()) }

  def showLocalizedTutorial(lang: String) = Action { implicit request =>
    lang.toUpperCase match {
      case "DE" => result(views.html.help.tutorial_de())
      case "ES" => result(views.html.help.tutorial_es())
      case "IT" => result(views.html.help.tutorial_it())
      case _ => NotFound(views.html.error404())
    }
  }

  def showFAQ = Action { implicit request => result(views.html.help.faq()) }

  def showAbout = Action { implicit request => result(views.html.help.about()) }

} 
开发者ID:pelagios,项目名称:recogito2,代码行数:38,代码来源:HelpController.scala


示例4: toResult

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

import ApiResponse._
import ApiError._
import models.ApiLog
import play.api.mvc.Results._
import play.api.mvc.{ Result, RequestHeader }
import play.api.libs.json._
import play.api.libs.json.Json._
import play.api.i18n.Lang


  def toResult[R <: RequestHeader](implicit request: R, lang: Lang): Result = {
    val envelope = request.getQueryString("envelope") == Some("true")
    toResult(envelope)
  }
  def toResult(envelope: Boolean = false)(implicit lang: Lang): Result = {
    val js = if (envelope) envelopedJson else json
    (status match {
      case STATUS_CREATED => if (js == JsNull) Created else Created(js)
      case STATUS_ACCEPTED => if (js == JsNull) Accepted else Accepted(js)
      case STATUS_NOCONTENT => NoContent
      case s if s < 300 => if (js == JsNull) Ok else Ok(js)

      case STATUS_BADREQUEST => BadRequest(js)
      case STATUS_UNAUTHORIZED => Unauthorized(js)
      case STATUS_FORBIDDEN => Forbidden(js)
      case STATUS_NOTFOUND => NotFound(js)
      case s if s > 400 && s < 500 => BadRequest(js)
      case _ => InternalServerError(js)
    }).withHeaders((headers ++ Api.basicHeaders): _*)
  }
} 
开发者ID:fvthree,项目名称:play-rest-api-2.4-anorm-mysql,代码行数:34,代码来源:ApiResult.scala


示例5: ErrorHandler

//设置package包名称以及导入依赖的类
package common

import org.slf4j.MDC
import play.api.Logger
import play.api.http.HttpErrorHandler
import play.api.libs.json.Json
import play.api.mvc.Results._
import play.api.mvc.{Result, RequestHeader}

import scala.concurrent.Future
import scala.util.Try

class ErrorHandler extends HttpErrorHandler {

  def onClientError(request: RequestHeader, statusCode: Int, m: String): Future[Result] = {
    val message = if(m.isEmpty) "there was a problem in the request, please check the path and the headers" else m
    Logger.warn(s"There was a client error with statusCode $statusCode in ${request.method} ${request.path} with message: $message")
    Future.successful(Status(statusCode)(Json.obj("error" -> true, "message" -> message)))
  }

  def onServerError(request: RequestHeader, exception: Throwable): Future[Result] = {
    val requestId = Try(MDC.get("requestId")).getOrElse{Logger.warn("couldnt get the requestId from MDC");""}
    val message = s"There was a server error in ${request.method} ${request.path} with requestId $requestId"
    Logger.error(message, exception)
    Future.successful(InternalServerError(Json.obj("error" -> true, "message" -> exception.getMessage)))
  }

} 
开发者ID:dtambussi,项目名称:pedidos,代码行数:29,代码来源:ErrorHandler.scala


示例6: ErrorHandler

//设置package包名称以及导入依赖的类
package utils

import javax.inject.{Inject, Provider}

import com.mohiva.play.silhouette.api.actions.SecuredErrorHandler
import play.api.http.DefaultHttpErrorHandler
import play.api.i18n.{I18nSupport, Messages, MessagesApi}
import play.api.mvc.Results._
import play.api.mvc.{RequestHeader, Result}
import play.api.routing.Router
import play.api.{Configuration, OptionalSourceMapper}

import scala.concurrent.Future
import controllers.{WebJarAssets, routes}

class ErrorHandler @Inject() (
                               val messagesApi: MessagesApi,
                               env: play.api.Environment,
                               config: Configuration,
                               sourceMapper: OptionalSourceMapper,
                               router: javax.inject.Provider[Router],
                               p: Provider[WebJarAssets])
  extends DefaultHttpErrorHandler(env, config, sourceMapper, router)
    with SecuredErrorHandler with I18nSupport {

  // https://www.playframework.com/documentation/2.5.x/Migration25#Handling-legacy-components
  implicit lazy val webJarAssets = p.get()

  override def onNotAuthenticated(implicit request: RequestHeader): Future[Result] =
    Future.successful(Redirect(routes.Auth.signIn()))

  override def onNotAuthorized(implicit request: RequestHeader): Future[Result] =
    Future.successful(Redirect(routes.Auth.signIn()).flashing("error" -> Messages("error.accessDenied")))

  override def onNotFound(request: RequestHeader, message: String): Future[Result] =
    Future.successful(Ok(views.html.errors.notFound(request)))

  override def onServerError(request:RequestHeader, exception:Throwable):Future[Result] =
    Future.successful(Ok(views.html.errors.serverError(request, exception)))
} 
开发者ID:tm-sukehiro,项目名称:play-hands-on,代码行数:41,代码来源:ErrorHandler.scala


示例7: CorrelationContext

//设置package包名称以及导入依赖的类
package filters

import java.util.UUID

import play.api.mvc.RequestHeader

case class CorrelationContext(correlationId: String = CorrelationContext.newCorrelationId)

object CorrelationContext {
  val correlationIdTag: String = "correlationId"

  def fromRequest(request: RequestHeader): CorrelationContext = CorrelationContext(
    correlationId = correlationId(request).getOrElse(newCorrelationId)
  )

  def newCorrelationId: String = {
    UUID.randomUUID().toString.toLowerCase
  }

  private def correlationId(request: RequestHeader): Option[String] = {
    if (request.tags.contains(correlationIdTag))
      Some(request.tags(correlationIdTag))
    else
      None
  }
} 
开发者ID:mriehl,项目名称:play-bug,代码行数:27,代码来源:CorrelationContext.scala


示例8: CorrelationIdFilter

//设置package包名称以及导入依赖的类
package filters

import akka.actor.ActorSystem
import akka.stream.{ ActorMaterializer, Materializer }
import javax.inject.Inject
import play.api.mvc.{ Filter, RequestHeader, Result }

import scala.concurrent.{ ExecutionContext, Future }

class CorrelationIdFilter @Inject() (implicit val executionContext: ExecutionContext, implicit val actorSystem: ActorSystem) extends Filter {

  val mat: Materializer = ActorMaterializer()
  def apply(nextFilter: (RequestHeader) => Future[Result])(requestHeader: RequestHeader): Future[Result] = {
    nextFilter(requestHeader.copy(
      tags = requestHeader.tags +
      (CorrelationContext.correlationIdTag ->
        requestRefNum(requestHeader).map(_.toString.toLowerCase).getOrElse(CorrelationContext.newCorrelationId))
    ))
  }

  private def requestRefNum(requestHeader: RequestHeader): Option[String] = {
    requestHeader.headers.get("L-IS24-RequestRefnum").map(_.trim).filter(!_.isEmpty)
  }
} 
开发者ID:mriehl,项目名称:play-bug,代码行数:25,代码来源:CorrelationIdFilter.scala


示例9: MessageDigestController

//设置package包名称以及导入依赖的类
package controllers

import javax.inject._

import play.api.libs.streams.Accumulator
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc.{Action, Controller, RequestHeader}
import play.core.parsers.Multipart.{FileInfo, FilePartHandler}
import services.MessageDigestService

import scala.concurrent.{ExecutionContext, Future}


@Singleton
class MessageDigestController @Inject()(digestService: MessageDigestService)(implicit exec: ExecutionContext) extends  Controller{


  def index = Action.async {
    Future.successful( Ok(views.html.MessageDigest.index(digestService.algorithms)) )
  }

  def upload = Action(Utility.multipartFormData(digest)){ implicit  request =>
    val digest = request.body.files.map(f => (f.filename, f.ref))
    Ok(views.html.MessageDigest.digest(digest))
  }

  def digest(rh: RequestHeader): FilePartHandler[String] = {
    case FileInfo(key, fileName, contentType) =>
      val Some(Seq(algo, _*)) = rh.queryString.get("algorithm")
      Accumulator(digestService.sink(algo)).map{ d =>
       FilePart(key, fileName, contentType, d)
     }
  }
} 
开发者ID:ejosiah,项目名称:crypto-utility,代码行数:35,代码来源:MessageDigestController.scala


示例10: Utility

//设置package包名称以及导入依赖的类
package controllers

import play.api.Play
import play.api.mvc.{BodyParser, MultipartFormData, RequestHeader}
import play.core.parsers.Multipart


object Utility {

  import play.api.mvc.BodyParsers.parse._


  def multipartFormData[A](filePartHandler: RequestHeader => Multipart.FilePartHandler[A], maxLength: Long = DefaultMaxDiskLength): BodyParser[MultipartFormData[A]] = {
    BodyParser("multipartFormData") { request =>
      val app = play.api.Play.current // throw exception
    implicit val mat = app.materializer
      val bodyAccumulator = Multipart.multipartParser(DefaultMaxTextLength, filePartHandler(request)).apply(request)
     // TODO enforceMaxLength(request, maxLength, bodyAccumulator) or maybe not
      bodyAccumulator
    }
  }
} 
开发者ID:ejosiah,项目名称:crypto-utility,代码行数:23,代码来源:Utility.scala


示例11: SecuredSpec

//设置package包名称以及导入依赖的类
package controllers

import db.scalikejdbc.{InMemDb, UserJdbc}
import org.intracer.wmua.User
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import play.api.mvc.{RequestHeader, Security, Session}

class SecuredSpec extends Specification with Mockito with InMemDb {

  sequential

  val userDao = UserJdbc

  def mockRequest(username: String): RequestHeader = {
    val request = mock[RequestHeader]
    val session = mock[Session]
    session.get(Security.username) returns Some(username)
    request.session returns session
    request
  }

  "user" should {
    "load from db" in {
      inMemDbApp {
        val username = "[email protected]"
        val user = User("fullname", username, None, Set("jury"), Some("password hash"), Some(10))

        val created = userDao.create(user)

        val request: RequestHeader = mockRequest(username)
        new Secured {}.userFromRequest(request) === Some(created)
      }
    }

    "be None if not in db" in {
      inMemDbApp {
        val username = "user login"
        val user = User("fullname", username, None, Set("jury"), Some("password hash"), Some(10))

        val created = userDao.create(user)

        val request: RequestHeader = mockRequest(username + " other")
        new Secured {}.userFromRequest(request) === None
      }
    }

  }

} 
开发者ID:intracer,项目名称:wlxjury,代码行数:51,代码来源:SecuredSpec.scala


示例12: AccessLog

//设置package包名称以及导入依赖的类
package httpmock

import play.api.mvc.RequestHeader

final case class AccessLog(
  request: RequestHeader,
  bodyOpt: Option[ArrayByte] = None
) {

  override def equals(other: Any): Boolean = other match {
    case that: AccessLog =>
      this.===(that)
    case _ =>
      false
  }

  def ===(that: AccessLog): Boolean = (this.bodyOpt, that.bodyOpt) match {
    case (Some(body1), Some(body2)) =>
      (this.request == that.request) && body1 == body2
    case (None, None) =>
      this.request == that.request
    case _ =>
      false
  }

  override def hashCode = {
    (request.hashCode() * 31) + bodyOpt.map(_.hashCode).getOrElse(7)
  }

} 
开发者ID:xuwei-k,项目名称:httpmock,代码行数:31,代码来源:AccessLog.scala


示例13: SettingSpec

//设置package包名称以及导入依赖的类
package httpmock

import play.api.mvc.{RequestHeader, Result, Results}

class SettingSpec extends TestHelper {
  describe("Setting()") {
    it("can start http service on some port") {
      val setting = Setting()
      start(setting) { server =>
        assert(server.port > 0)
      }
    }
  }

  describe("Setting(methods = Set(GET))") {
    val setting = Setting(methods = Set(GET))
    it("accepts GET [200]") {
      start(setting) { server =>
        assert(get(server.url).getStatusCode === 200)
      }
    }

    it("rejects POST [404]") {
      start(setting) { server =>
        assert(post(server.url, "body").getStatusCode === 404)
      }
    }
  }

  describe("Setting(handler = ???") {
    val handler: PartialFunction[RequestHeader, Result] = {
      case h: RequestHeader if h.method == "POST" => Results.Unauthorized
      case h: RequestHeader if h.uri.contains("rerorero") => Results.InternalServerError
    }

    it("responses matched handler results") {
      start(Setting(methods = Set(GET, POST), handler = handler)) { server =>
        assert(post(server.url, "body").getStatusCode === 401)
        assert(get(server.url + "rerorero").getStatusCode === 500)
      }
    }

    it("responses according to methods property if not matched") {
      start(Setting(methods = Set(GET), handler = handler)) { server =>
        assert(post(server.url, "body").getStatusCode === 404)
        assert(get(server.url + "rorerore").getStatusCode === 200)
      }
    }
  }
} 
开发者ID:xuwei-k,项目名称:httpmock,代码行数:51,代码来源:SettingSpec.scala


示例14: CapabilityDisjunctionOps

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

import play.api.mvc.RequestHeader

package object auth {

  implicit class CapabilityDisjunctionOps(firstCapability: Capability) {
    def ||(secondCapability: Capability) = Disjunction(firstCapability, secondCapability)
  }

  implicit class CapabilityConjunctionOps(firstCapability: Capability) {
    def &&(secondCapability: Capability) = Conjunction(firstCapability, secondCapability)
  }

  implicit def token2Capability(token: Token): Capability = new CapabilityByToken {
    def predicate = _ == token
  }

  implicit def isAuthenticated(implicit request: RequestHeader) =
    request match {
      case _: AuthenticatedRequest[_, _] | _: AuthorizedRequest[_, _] => true
      case _ => false
    }

  implicit def isAuthorized(capabilities: Capability*)(implicit request: RequestHeader) =
    request match {
      case authorizedRequest: AuthorizedRequest[_, _] => authorizedRequest.isAuthorized(capabilities.toSet)
      case _ => false
    }

} 
开发者ID:jasperdenkers,项目名称:play-auth,代码行数:32,代码来源:package.scala


示例15: Session

//设置package包名称以及导入依赖的类
package ejisan.play.libs.scalauth

import play.api.mvc.{ Result, RequestHeader }
import play.api.{ Configuration, Logger }

case class Session(id: String, impersonator: Option[String]) {
  def toSeq(SESSION_COOKIE_NAME: String, IMPERSONATING_SESSION_COOKIE_NAME: String): Seq[(String, String)] =
    Seq(SESSION_COOKIE_NAME -> Some(id), IMPERSONATING_SESSION_COOKIE_NAME -> impersonator).collect {
      case (key, Some(value)) => (key, value)
    }
}

class PlaySessionManager(configuration: Configuration) {
  val SESSION_COOKIE_NAME: String =
    configuration.getString("scalauth.play.secure_action.cookie_name").getOrElse("SESSION")
  val IMPERSONATING_SESSION_COOKIE_NAME: String =
    configuration.getString("scalauth.play.secure_action.impersonator_cookie_name").getOrElse("IMPERSONATOR")

  def set(session: Session)(result: => Result)(implicit request: RequestHeader): Result = {
    Logger.debug(s"Set session for ID: `${session.id}` and IMPERSONATOR_ID: `${session.impersonator.getOrElse("N/A")}`.")
    forceEnd(result).addingToSession(session.toSeq(SESSION_COOKIE_NAME, IMPERSONATING_SESSION_COOKIE_NAME):_*)
  }

  def get(implicit request: RequestHeader): Option[Session] =
    request.session.get(SESSION_COOKIE_NAME).map(Session(_, request.session.get(IMPERSONATING_SESSION_COOKIE_NAME)))

  def start(id: String)(result: => Result)(implicit request: RequestHeader): Result =
    set(Session(id, None))(result)

  def restart(result: => Result)(implicit request: RequestHeader): Result =
    get.map(set(_)(result)).getOrElse(result)

  def impersonate(id: String)(result: => Result)(implicit request: RequestHeader): Result = {
    val impersonator = try {
      request.session(SESSION_COOKIE_NAME)
    } catch {
      case _: NoSuchElementException =>
      val e = new IllegalStateException("Impersonator must start main session before impersonating session.")
        Logger.error("Main session not found", e)
        throw e
    }
    set(Session(id, Some(impersonator)))(result)
  }

  def end(result: => Result)(implicit request: RequestHeader): Result = {
    if (request.session.data.keySet.exists(_ == IMPERSONATING_SESSION_COOKIE_NAME)) {
      result.removingFromSession(IMPERSONATING_SESSION_COOKIE_NAME)
    } else if (request.session.data.keySet.exists(_ == SESSION_COOKIE_NAME)) {
      result.removingFromSession(SESSION_COOKIE_NAME)
    } else {
      result
    }
  }

  def forceEnd(result: => Result)(implicit request: RequestHeader): Result =
    result.removingFromSession(SESSION_COOKIE_NAME, IMPERSONATING_SESSION_COOKIE_NAME)
} 
开发者ID:ejisan,项目名称:play-scalauth-secureaction,代码行数:58,代码来源:PlaySessionManager.scala


示例16: ErrorHandler

//设置package包名称以及导入依赖的类
import scala.concurrent._

import play.api.Logger
import play.api.http.HttpErrorHandler
import play.api.mvc.RequestHeader
import play.api.mvc.Results.{InternalServerError, Status}

class ErrorHandler extends HttpErrorHandler {

  def onClientError(request: RequestHeader, statusCode: Int, message: String) = {
    Logger.error(s"${request.method} ${request.uri} returned $statusCode - $message")
    Future.successful(
      Status(statusCode)(message)
    )
  }

  def onServerError(request: RequestHeader, exception: Throwable) = {
    Future.successful(
      InternalServerError(exception.getMessage)
    )
  }
} 
开发者ID:sebtomba,项目名称:wordcount-akka-streams,代码行数:23,代码来源:ErrorHandler.scala


示例17: sessionTimeoutInSeconds

//设置package包名称以及导入依赖的类
package authes

import jp.t2v.lab.play2.auth._
import models.Account
import play.api.mvc.{RequestHeader, Result}

import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
import scala.reflect.ClassTag

trait AuthConfigImpl extends AuthConfig {
  import controllers.Responses._

  override type Id = Long
  override type User = Account
  override type Authority = Role

  override lazy val idContainer = AsyncIdContainer(new SessionContainer())

  override val idTag: ClassTag[Id] = implicitly[ClassTag[Id]]

  override def sessionTimeoutInSeconds: Int = 7.days.toSeconds.toInt

  override def resolveUser(id: Id)(implicit context: ExecutionContext): Future[Option[User]] =
    Future.successful(Account.findById(id))

  override def loginSucceeded(request: RequestHeader)(implicit context: ExecutionContext): Future[Result] =
    Future.successful(Success)

  override def logoutSucceeded(request: RequestHeader)(implicit context: ExecutionContext): Future[Result] =
    Future.successful(Success)

  override def authenticationFailed(request: RequestHeader)(implicit context: ExecutionContext): Future[Result] =
    Future.successful(Forbidden("Authentication failed"))

  override def authorizationFailed(request: RequestHeader, user: User, authority: Option[Role])(implicit context: ExecutionContext): Future[Result] =
    Future.successful(Forbidden("Authorization failed"))

  override def authorize(user: User, authority: Authority)(implicit context: ExecutionContext): Future[Boolean] = Future.successful {
    (user.role, authority) match {
      case (Role.Disabled, _) => false
      case (Role.Administrator, _) => true
      case (Role.NormalUser, Role.NormalUser) => true
      case _ => false
    }
  }

  override lazy val tokenAccessor = new CookieTokenAccessor(
    cookieSecureOption = false,
    cookieMaxAge = Some(sessionTimeoutInSeconds)
  )
} 
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:53,代码来源:AuthConfigImpl.scala


示例18: AuthService

//设置package包名称以及导入依赖的类
package services

import java.security.MessageDigest
import java.util.UUID
import java.util.concurrent.TimeUnit

import model.User
import org.apache.commons.codec.binary.Base64
import org.mindrot.jbcrypt.BCrypt
import play.api.cache.SyncCacheApi
import play.api.mvc.{Cookie, RequestHeader}
import scalikejdbc._

import scala.concurrent.duration.Duration


class AuthService(cacheApi: SyncCacheApi) {

  def login(userCode: String, password: String): Option[Cookie] = {
    for {
      user <- checkUser(userCode, password)
      cookie <- Some(createCookie(user))
    } yield {
      cookie
    }
  }

  def checkCookie(header: RequestHeader): Option[User] = {
    for {
      cookie <- header.cookies.get(cookieHeader)
      user <- cacheApi.get[User](cookie.value)
    } yield {
      user
    }
  }

  private def checkUser(userCode: String, password: String): Option[User] =
    DB.readOnly { implicit session =>
    val maybeUser = sql"select * from users where user_code = $userCode".
      map(User.fromRS).single().apply()
    maybeUser.flatMap { user =>
      if (BCrypt.checkpw(password, user.password)) {
        Some(user)
      } else None
    }
  }

  val mda = MessageDigest.getInstance("SHA-512")
  val cookieHeader = "X-Auth-Token"

  private def createCookie(user: User): Cookie = {
    val randomPart = UUID.randomUUID().toString.toUpperCase
    val userPart = user.userId.toString.toUpperCase
    val key = s"$randomPart|$userPart"
    val token = Base64.encodeBase64String(mda.digest(key.getBytes))
    val duration = Duration.create(10, TimeUnit.HOURS)
    cacheApi.set(token, user, duration)
    Cookie(cookieHeader, token, maxAge = Some(duration.toSeconds.toInt))
  }
} 
开发者ID:denisftw,项目名称:modern-web-scala,代码行数:61,代码来源:AuthService.scala


示例19: JwtFilter

//设置package包名称以及导入依赖的类
package filters

import akka.stream.Materializer
import com.google.inject.Inject
import model.JwtUser
import play.api.Logger
import play.api.libs.json.Json
import play.api.mvc.{Filter, RequestHeader, Result}
import play.api.mvc.Results._
import utils.JwtUtils

import scala.concurrent.{ExecutionContext, Future}

class JwtFilter @Inject()(implicit val mat: Materializer, implicit val ec: ExecutionContext) extends Filter {

  val logger: Logger = Logger(this.getClass())

  import utils.DefaultJsonParsers._

  override def apply(next: (RequestHeader) => Future[Result])(rh: RequestHeader): Future[Result] = {
    if (!JwtUtils.unsecuredEndpoints.contains(rh.path)) {
      logger.debug("Checking JWT token")
      val jwtToken = JwtUtils.getToken(rh.headers.get(JwtUtils.tokenHdr).getOrElse(""))
      if (jwtToken.isFailure) Future(Unauthorized)
      else next(rh.addAttr[JwtUser](JwtUtils.tokenAttr, Json.fromJson[JwtUser](Json.parse(jwtToken.get)).get))
    } else {
      logger.debug("Allowed in with no token")
      next(rh)
    }
  }

} 
开发者ID:olo-b,项目名称:FoodService,代码行数:33,代码来源:JwtFilter.scala


示例20: RegExCORSFilter

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

import akka.stream.Materializer
import play.api.Logger
import play.api.http.{DefaultHttpErrorHandler, HttpErrorHandler}
import play.api.mvc.{Result, RequestHeader, Filter}
import play.core.j.JavaHttpErrorHandlerAdapter
import play.filters.cors.{CORSFilter, AbstractCORSPolicy, CORSConfig}

import scala.concurrent.Future


class RegExCORSFilter(
                  override protected val corsConfig: CORSConfig = CORSConfig(),
                  override protected val errorHandler: HttpErrorHandler = DefaultHttpErrorHandler,
                  private val pathPrefixes: Seq[String] = Seq("/"),
                  private val ignoredPathPrefixes: Seq[String] = Seq.empty[String])(override implicit val mat: Materializer)
  extends CORSFilter {

  // Java constructor
  def this(corsConfig: CORSConfig, errorHandler: play.http.HttpErrorHandler, pathPrefixes: java.util.List[String])(mat: Materializer) = {
    this(corsConfig, new JavaHttpErrorHandlerAdapter(errorHandler), Seq(pathPrefixes.toArray.asInstanceOf[Array[String]]: _*))(mat)
  }

  override protected val logger = Logger(classOf[CORSFilter])

  override def apply(f: RequestHeader => Future[Result])(request: RequestHeader): Future[Result] = {
    if (pathPrefixes.exists(request.path.startsWith) &&
      !ignoredPathPrefixes.exists(request.path.startsWith)) {
      filterRequest(f, request)
    } else {
      f(request)
    }
  }
}

object RegExCORSFilter {

  val RequestTag = "CORS_REQUEST"

  def apply(corsConfig: CORSConfig = CORSConfig(), errorHandler: HttpErrorHandler = DefaultHttpErrorHandler,
            pathPrefixes: Seq[String] = Seq("/"))(implicit mat: Materializer) =
    new CORSFilter(corsConfig, errorHandler, pathPrefixes)

} 
开发者ID:dgilling,项目名称:play-regex-cors,代码行数:46,代码来源:RegExCORSFilter.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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