本文整理汇总了Scala中play.api.mvc.Session类的典型用法代码示例。如果您正苦于以下问题:Scala Session类的具体用法?Scala Session怎么用?Scala Session使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Session类的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: saveChanges
//设置package包名称以及导入依赖的类
package controllers
import javax.inject._
import models._
import play.api._
import play.api.data.Forms._
import play.api.data.Forms.{longNumber, mapping, nonEmptyText}
import play.api.i18n.Messages
import play.api.i18n.Messages.Implicits._
import play.api.mvc._
import play.api.mvc.{Action, Controller, Flash, Request}
import play.api.Play.current
import play.api.data.Form
import play.api.mvc.Session
import scala.concurrent.ExecutionContext.Implicits.global
def saveChanges = Action {
implicit request =>
val editCustomerForm = updateForm.bindFromRequest()
editCustomerForm.fold(hasErrors = {
form =>
Redirect(routes.UpdateAccountController.updateAccount()).flashing(Flash(form.data) + ("error" -> Messages("updateAccount.validation.errors")))
}, success = {
editCustomer =>
val currentUsername = CustomerDB.findByUsername(request.session.get("username").get).head.getAs[String]("username").get
if (!(editCustomerForm.data("First Name").length == 0)) {
CustomerDB.updateUserField(currentUsername, "fName", editCustomerForm.data("First Name"))
}
if (!(editCustomerForm.data("Last Name").length == 0)) {
CustomerDB.updateUserField(currentUsername, "lName", editCustomerForm.data("Last Name"))
}
if (!(editCustomerForm.data("Email").length == 0)) {
CustomerDB.updateUserField(currentUsername, "email", editCustomerForm.data("Email"))
}
if (!(editCustomerForm.data("Telephone").length == 0)) {
CustomerDB.updateUserField(currentUsername, "phone", editCustomerForm.data("Telephone"))
}
if (!(editCustomerForm.data("Username").length == 0)) {
CustomerDB.updateUserField(currentUsername, "username", editCustomerForm.data("Username"))
}
if (!(editCustomerForm.data("Password").length == 0)) {
CustomerDB.updateUserField(currentUsername, "password", editCustomerForm.data("Password"))
}
val currentCustomer = CustomerDB.findByUsername(currentUsername).head
val customerSession = request.session +
("customerID" -> currentCustomer.getAs[Int]("customerID").get.toString) +
("firstName" -> currentCustomer.getAs[String]("fName").get) +
("lastName" -> currentCustomer.getAs[String]("lName").get) +
("email" -> currentCustomer.getAs[String]("email").get) +
("phone" -> currentCustomer.getAs[String]("phone").get) +
("username" -> currentCustomer.getAs[String]("username").get)
Redirect(routes.UserAccountController.userAccount()).withSession(customerSession)
})
}
}
示例2: 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
}
}
}
}
示例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
)
}
示例4: SessionHandler
//设置package包名称以及导入依赖的类
package controllers
import play.api.mvc.Session
class SessionHandler(private val request: Session) {
private val key = "session"
private var session = None : Option[Session]
def getSession: Session = {
if (request.isEmpty || request.data.get(key).isEmpty) {
session = Some(Session(Map(key -> createSessionId)))
} else {
session = Some(Session(request.data))
}
session.get
}
private def createSessionId: String = {
val chars = ('a' to 'z') ++ ('A' to 'Z') ++ ('0' to '9')
val length = 32
val sb = new StringBuilder
for (_ <- 1 to length) {
val randomNum = util.Random.nextInt(chars.length)
sb.append(chars(randomNum))
}
sb.toString
}
def getSessionId: String = {
session match {
case None =>
getSession.data(key)
case Some(value) =>
value.data(key)
}
}
}
示例5: AuthController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import auth.AuthHelpers
import play.api.libs.json.JsValue
import play.api.libs.ws.WSClient
import play.api.mvc.{Action, Controller, Session}
import repositories.MonzoRepository
import play.api.{Configuration, Logger}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
class AuthController @Inject() (ws: WSClient, configuration: Configuration) extends Controller {
val monzoRepository = MonzoRepository
def oauthCallback(code: String, state: String) = Action.async { implicit request =>
AuthHelpers.exchangeAuthForAccessToken(code).flatMap { authStuff =>
val authDataFuture = AuthHelpers.getAccountId(authStuff.accessToken).map { accountId =>
authStuff.copy(accountId = accountId)
}
authDataFuture.map { authData =>
monzoRepository.save(authData.encrypt).map {
a =>
if (a.nModified == 0) {
registerForWebhook(authData.accountId, authData.accessToken)
}
}
Redirect(controllers.routes.MoneyboxController.enterDetails)
.withSession(Session(authData.toMap))
}
}
}
def registerForWebhook(accountId: String, accessToken: String): Future[JsValue] = {
val webhookUrl = configuration.getString("webhook.callback.url").getOrElse("http://localhost:9000")
val formData = Map(
"account_id" -> Seq(accountId),
"url" -> Seq(webhookUrl + "/callback/transaction")
)
ws.url("https://api.monzo.com/webhooks").withHeaders(("Authorization", s"Bearer $accessToken")).post(formData).map {
response =>
Logger.info(s"[AuthController][registerForWebhook] - Status code: ${response.status}")
Logger.info(s"[AuthController][registerForWebhook] - Response body: ${response.body}")
Logger.info(s"[AuthController][registerForWebhook] - created webhook for $accountId at $webhookUrl")
response.json
}
}
}