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

Scala Cookie类代码示例

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

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



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

示例1: 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


示例2: getUserNick

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

import helpers.ConfigHelper
import play.api.libs.Crypto
import play.api.mvc.{Cookie, DiscardingCookie, RequestHeader, Result}

trait CookieSupport {

  import CookieSupport._

  def getUserNick(request: RequestHeader): Option[String] = {
    request.cookies.get(SessionKey).map {
      case cookie =>
        val user = Crypto.decryptAES(cookie.value)
        user
    }
  }
}

object CookieSupport{
  private lazy val CookieMaxAge = ConfigHelper.getCookieMaxAge
  private lazy val SessionKey = ConfigHelper.getSessionCookieName

  implicit class ResponseWithSessionCookies(val response: Result){

    def addSessionCookie(user: String) = {
      //seems to be ignoring httpOnly flag for some reason
      val cookie = Cookie(name = SessionKey, value = Crypto.encryptAES(user), maxAge = Some(CookieMaxAge), httpOnly = true)
      response.withCookies(cookie)
    }

    def updateSessionCookie(request: RequestHeader) = {
        val oldCookie = request.cookies(SessionKey)
        val newCookie = oldCookie.copy(maxAge = Some(CookieMaxAge))
        response.withCookies(newCookie)
    }

    def destroySession = {
      response.discardingCookies(DiscardingCookie(SessionKey))
    }
  }
} 
开发者ID:rok21,项目名称:kc_web,代码行数:43,代码来源:CookieSupport.scala


示例3: LilaCookie

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

import java.util.regex.Matcher.quoteReplacement

import ornicar.scalalib.Random
import play.api.mvc.{ Cookie, Session, RequestHeader }

object LilaCookie {

  private val domainRegex = """^.+(\.[^\.]+\.[^\.]+)$""".r

  private def domain(req: RequestHeader): String =
    domainRegex.replaceAllIn(req.domain, m => quoteReplacement(m group 1))

  val sessionId = "sid"

  def makeSessionId(implicit req: RequestHeader) = session(sessionId, Random secureString 10)

  def session(name: String, value: String)(implicit req: RequestHeader): Cookie = withSession { s =>
    s + (name -> value)
  }

  def newSession(implicit req: RequestHeader): Cookie = withSession(identity)

  def withSession(op: Session => Session)(implicit req: RequestHeader): Cookie = cookie(
    Session.COOKIE_NAME,
    Session.encode(Session.serialize(op(req.session)))
  )

  def cookie(name: String, value: String, maxAge: Option[Int] = None, httpOnly: Option[Boolean] = None)(implicit req: RequestHeader): Cookie = Cookie(
    name,
    value,
    maxAge orElse Session.maxAge orElse 86400.some,
    "/",
    domain(req).some,
    Session.secure || req.headers.get("X-Forwarded-Proto").contains("https"),
    httpOnly | Session.httpOnly
  )
} 
开发者ID:DrNixx,项目名称:line,代码行数:40,代码来源:LilaCookie.scala


示例4: SessionController

//设置package包名称以及导入依赖的类
//
// Copyright © [2010-2016] Visier Solutions Inc. All rights reserved.
//
package v1.session

import com.github.scribejava.core.model.{OAuth1AccessToken, OAuth1RequestToken}
import play.api.libs.json.Json
import play.api.mvc.{Action, Controller, Cookie}
import services.RedisService._
import services.YahooOauthService

class SessionController extends Controller{

  def index = Action { implicit request =>
    val yahooService = YahooOauthService.initService()
    redis.set(yahooService.token.getToken, yahooService.token.getTokenSecret)
    Redirect(yahooService.url())
  }

  def callback(oauth_token: String, oauth_verifier: String) = Action { implicit request =>
    val token: OAuth1RequestToken = new OAuth1RequestToken(oauth_token, redis.get(oauth_token).get)
    val yahooService = YahooOauthService.initService(token)
    (token, oauth_verifier) match {
      case (oauthToken: OAuth1RequestToken, oauthSecret: String) => {
        val token: OAuth1AccessToken = yahooService.accessToken(oauthSecret)
        redis.set(token.getToken, token.getTokenSecret)
        Ok(views.html.stats()).withCookies(Cookie("auth_token", token.getToken, maxAge = Some(20), httpOnly = false))
      }
      case _ => Ok(Json.toJson(Map("error" -> "Couldn't get token.")))
    }
  }
} 
开发者ID:cregg,项目名称:flhserver,代码行数:33,代码来源:SessionController.scala


示例5: fetch

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

import com.google.inject.Inject
import play.api.Logger
import play.api.http.HeaderNames
import play.api.i18n.Lang
import play.api.libs.json.{JsError, JsSuccess, Json, Reads}
import play.api.libs.ws.{WSClient, WSRequest}
import play.api.mvc.{Cookie, Cookies}

import scala.concurrent.{ExecutionContext, Future}
import scala.concurrent.duration._
import scala.util.control.NonFatal


trait WsConsumer {
  def fetch[T](url: String, timeout: FiniteDuration = 2.seconds)(implicit ec:ExecutionContext, r: Reads[T], lang: Lang): Future[T]
}

class WsConsumerImpl @Inject()(ws: WSClient) extends WsConsumer {
  val log = Logger("WsConsumer")

  override def fetch[T](url: String, timeout: FiniteDuration = 2.seconds)(implicit ec:ExecutionContext, r: Reads[T], lang: Lang) =
    ws.url(url).
      withCookies(Cookie("PLAY_LANG", lang.language)).
      withRequestTimeout(timeout).
      get().flatMap { result =>
      Json.fromJson(result.json) match {
        case JsSuccess(s, _) =>
          Future.successful(s)
        case JsError(e) =>
          val errors = JsError.toJson(e).fields.foldLeft("")((acc, next) => acc + next + "\n")
          Future.failed(new RuntimeException(s"Failed to unmarshal:\n $errors"))
      }
    }.recoverWith {
      case NonFatal(t) =>
        log.warn(s"Failed to fetch '$url'")
        Future.failed(new RuntimeException(t))
    }

  implicit class WithCookiesOps(requestHolder: WSRequest) {
    def withCookies(cookies: Cookie*): WSRequest = {
      val encoded = Cookies.encodeSetCookieHeader(cookies.toSeq)
      requestHolder.withHttpHeaders(HeaderNames.COOKIE -> encoded)
    }
  }

} 
开发者ID:splink,项目名称:pagelets-seed,代码行数:49,代码来源:WsConsumer.scala


示例6: Api

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

import com.google.inject.Inject
import models.{Channel, ChannelContent, ChannelSeries}
import play.api.db.Database
import play.api.libs.json.{JsArray, JsValue, Json}
import play.api.mvc.{Action, Controller, Cookie, DiscardingCookie}
import reference.JsonReference._
import reference.MatchMethod

import scala.collection.mutable.ArrayBuffer
import scala.util.Random

class Api @Inject()(implicit db: Database) extends Controller {

    val rand: Random = new Random(System.nanoTime())

    def getRandomVideo(channelId: String) = Action {
        val content = ChannelContent.getBy(classOf[Channel], 'channelId -> channelId)
        val c = content(rand.nextInt(content.length))
        Ok(if (c != null) Json.toJson(c) else Json.obj()).as("application/json")
    }

    def getRandomPlaylist(channelId: String) = Action {
        val series = ChannelSeries.getBy(classOf[Channel], 'channelId -> channelId)
        val s: ChannelSeries = series(rand.nextInt(series.length))
        Ok(if (s != null) Json.toJson(s) else Json.obj()).as("application/json")
    }

    def getPlaylistQueue(channelId: String): Action[JsValue] = Action(parse.json) { request => {
        val series: Array[String] = (request.body \ "series").as[JsArray].value.map(s => s.as[String]).toArray
        val filters: Array[String] = (request.body \ "filters").as[JsArray].value.map(f => f.as[String]).toArray
        val filterOptions: JsValue = (request.body \ "options").get
        var contentPool: List[ChannelContent] = List()
        if (series.isEmpty)
            if (filters.isEmpty)
                contentPool ++= Channel.get(channelId).get.getContent
            else
                contentPool ++= ChannelContent.getWithTags(channelId, "%", filters, MatchMethod.withName((filterOptions \ "matchMethod").as[String]))
        else {
            if (filters.isEmpty)
                series.foreach(seriesId => contentPool ++= ChannelContent.getBy(classOf[ChannelSeries], 'seriesId -> seriesId))
            else
                series.foreach(seriesId => contentPool ++= ChannelContent.getWithTags(channelId, seriesId, filters, MatchMethod.withName((filterOptions \ "matchMethod").as[String])))
        }
        val indexes: ArrayBuffer[Int] = new ArrayBuffer[Int]()
        while (indexes.length < Math.min(contentPool.length, (filterOptions \ "videoCount").as[Int])) {
            val i = rand.nextInt(contentPool.length)
            if (!indexes.contains(i)) indexes += i
        }
        Ok(Json.toJson(indexes.map(i => Json.toJson(contentPool(i)))))
    }
    }

    def setChannelCookie(channelId: String) = Action {
        Redirect(routes.Application.index()).discardingCookies(DiscardingCookie("channel")).withCookies(Cookie("channel", channelId, httpOnly = false))
    }

} 
开发者ID:Cobbleopolis,项目名称:RandomHaus,代码行数:60,代码来源:Api.scala


示例7:

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

import play.api.http.HeaderNames
import play.api.mvc.{Cookie, Cookies}
import play.api.test.{FakeHeaders, FakeRequest}
import toguru.api.ClientInfo

trait RequestHelpers {
  val client: PlayClientProvider = { implicit request =>
    import PlaySupport._
    ClientInfo(uuidFromCookieValue("myVisitor"), forcedToggle)
      .withAttribute(fromCookie("culture"))
      .withAttribute(fromHeader(UserAgent))
  }

  val UserAgent = HeaderNames.USER_AGENT

  val fakeHeaders = FakeHeaders(
    Seq(
      UserAgent -> "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36",
      "X-toguru" -> "feature1-Forced-By-Header=true|feature2-Forced-By-Header=true",
      HeaderNames.COOKIE ->
        Cookies.encodeCookieHeader(Seq(
          Cookie("culture", "de-DE"),
          Cookie("myVisitor", "a5f409eb-2fdd-4499-b65b-b22bd7e51aa2"),
          Cookie(
            "toguru",
            "feature1-Forced-By-Cookie=true|feature2-Forced-By-Cookie=true")
        ))
    ))

  val request = FakeRequest.apply(
    "GET",
    "http://priceestimation.autoscout24.de?toguru=feature-forced-by-query-param%3Dtrue",
    fakeHeaders,
    "body")
  val requestWithToggleIdUpppercased = FakeRequest.apply(
    "GET",
    "http://priceestimation.autoscout24.de?toguru=feature-FORCED-by-query-param%3Dtrue",
    fakeHeaders,
    "body")
  val requestWithTwoTogglesInQueryString = FakeRequest.apply(
    "GET",
    "http://priceestimation.autoscout24.de?toguru=feature1-forced-by-query-param%3Dtrue%7Cfeature2-forced-by-query-param%3Dfalse",
    fakeHeaders,
    "body"
  )
} 
开发者ID:AutoScout24,项目名称:toguru-scala-client,代码行数:49,代码来源:RequestHelpers.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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