播放框架 - 如何在此代码play2 scala zentasks中为经过身份验证的用户调用此函数

时间:2012-11-06 00:09:52

标签: scala forms-authentication action playframework-2.0

在play2 scala zentasks示例应用程序中,代码片段如下所示

def IsAuthenticated(f: => String => Request[AnyContent] => Result) = 
    Security.Authenticated(username, onUnauthorized) { user =>
    Action(request => f(user)(request))
  }

我需要做的是在模型中调用此函数

def AddOnline(email: String, contact: Contact) = {
DB.withConnection { implicit connection =>
  SQL(
    """
      update contact
      set online_status = {'online'} //I want to write the value contact.status=online
      where email = {email}
    """
  ).on(
    'email -> contact.email,
    'online_status -> contact.online_status
  ).executeUpdate()
}

}

但我的挑战是每次某个用户通过上面的代码进行身份验证时调用此AddOnline函数。有人可以建议我应该怎么做?我是这方面的新手,我会绕圈而不做任何进展

1 个答案:

答案 0 :(得分:2)

您可以像addOnline这样调用IsAuthenticated方法:

 def IsAuthenticated(f: => String => Request[AnyContent] => Result) = 
   Security.Authenticated(username, onUnauthorized) { user =>
   // Do what you need to do here before the action is called
   Contact.addOnline(user)
   Action(request => f(user)(request))
 }

请注意,user不是用户对象,而只是经过身份验证的用户的电子邮件。

此外,由于您只是添加了user的在线状态,因此您可以将AddOnline方法简化为类似的内容。

def addOnline(email: String) = {
  DB.withConnection { implicit connection =>
    SQL(
      """
        update contact
        set online_status = 'online'
        where email = {email}
      """
    ).on(
      'email -> email,
  ).executeUpdate()
}