安全的社交websockets游戏框架

时间:2014-04-19 06:45:56

标签: scala playframework securestring

如何使用scala securesocial在play框架中保护websocket调用?

def statusfeed() = WebSocket.using[String] { implicit request =>
    if (logged in) {
      ...
    else {
    }
}

谢谢,

编辑1:

试过这个但是没有用,总是“没有登录”

def statusfeed() = WebSocket.using[String] { implicit request =>
  var in = Iteratee.ignore[String]
  var out = Enumerator.empty[String]
  session.get("userId").map { sessionId =>
      //sessionId is now userId in session
      //check he is authorise to view page or not   
      //  Ok("user in session")
      def getLoadAverage = {
          "%1.2f" format
            ManagementFactory.getOperatingSystemMXBean.getSystemLoadAverage()
      }

      in = Iteratee.ignore[String]
      out = Enumerator.repeatM {
          Promise.timeout(getLoadAverage, 3 seconds)
      }

  }.getOrElse {
      log.info("not logged in")
      //any thing that you want when he is not in session
      Redirect("/") //NOT IN SESSION REDIRECT TO LOGIN PAGE
  }
  (in, out)
}

编辑2: 用SecureSocial.USER_KEY替换userId无法正常工作

1 个答案:

答案 0 :(得分:2)

这有效,但不是惯用的scala

def getUser(req: RequestHeader):String = {
  val authenticator = SecureSocial.authenticatorFromRequest(req)
  if (authenticator.isEmpty) {
    return null
  } 
  val auth = UserService.find(authenticator.get.identityId)
  auth.get.identityId.userId
}

def statusfeed() = WebSocket.using[String] { implicit request =>
    implicit val req = request
    val user = getUser(req)

...

然后测试用户!= null


或更简单

def statusfeed() = WebSocket.using[String] { implicit request =>
  SecureSocial.currentUser(request) match {
    case Some(userid) => ... success
    case None => ... failed
  }
}