0

我是 scala play 框架的新手。如果找不到会话值并且用户尝试主页或任何其他页面的 url,我想重定向到登录页面。希望你明白我想要什么。如果用户试图去,在 scala 播放框架中没有登录的主页然后显示错误。我不想显示这些错误,我希望该用户自动重定向到登录页面。提前感谢帮助

4

4 回答 4

2

如果需要的会话值存在,您可以使用全局对象检查每个请求,并在其他情况下重定向到登录页面。

这很容易实现,无论如何不能向您展示 Scala 示例,因为我只使用 Java,在我的情况下,最简单的方法是(为演示而简化):

@Override
public Action onRequest(Http.Request request, Method method) {

    if (request.cookie("logged_user") == null && !request.path().startsWith("/login")) {
        return new Action.Simple() {
            public Result call(Http.Context ctx) throws Throwable {
                return temporaryRedirect("/login");
            }
        };
    }

    return super.onRequest(request, method);
}
于 2013-10-08T13:20:33.867 回答
0

我有一个解决方案,但不知道它是否是正确的方法。

def generalAccountSetting()=Action{
implicit request=>
  try{
    val result=User.getResult(session.get("userId").get)// this makes exception, if user not logged in.
  if(!result.isEmpty){
    Ok(html.general(result(0)))
  }
  else
    Ok(html.onError())
  }catch{
   case e:Exception=>
            println(e.toString)
            Redirect("/").withNewSession
  }

}//end generalAccountSetting

编辑:5天后

有更好的方法

def generalAccountSetting() = Action { implicit request =>
try{
    session.get("userId").map{user=>
        val result=User.getResult(session.get("userId").get)// this makes exception, if user not logged in.
  if(!result.isEmpty){
Ok(html.general(result(0)))
}
else
Ok(html.onError())
    }.getOrElse{
        Redirect("/")
      }
}catch{
    case e=>
    Ok(html.onError())
}
 }//end generalAccountSetting
于 2013-10-15T04:31:53.013 回答
0

有很多方法可以做到这一点,这是一个选择问题。尽管我在会话管理松散耦合的情况下制作了我的个人。

import play.api.mvc._
import play.api.Logger

/**
 * Trait to convert cookie to something which makes sense literally.
 * @tparam A Session Object type.
 */
trait DecryptSession[A] {

  /**
   * Retrieve the connected user email.
   */
  protected final def username(request: RequestHeader): Option[String] = request.session.get(sessionId)

  /**
   * Takes the parameter obtained from cookie (after decyphering) and then converts it to type A
   * @param the string obtained from Session Cookie
   * @return Left(err) err: is the error string if something is wrong with Cookie. Right(Option[A])
   */
  protected def fromSession(param: String): Either[String, A]

  /**
   * Saves a session object and returns a Session tuple containign key-value pair of
   * Cookie-key and Cookie-value. This can be directly used for result.
   * Example:
   * {{{
   *    Ok("hey").withNewSession(toSession(userObject))
   *  }}}
   */
  def toSession(param: A): (String, String)

  protected val sessionId = "sessionId";
}

/**
 * Provide security features
 */
trait WebSecurity[A] extends DecryptSession[A] {

  import play.api.mvc.BodyParsers._
  import views._

  /**
   * Redirect to login if the user in not authorized.
   */
  private def onUnauthorized(request: RequestHeader) =
    play.api.mvc.Results.Redirect(controllers.routes.Assets.at("public/signup.html"))


  /**
   * Checks if the user is a authenticated/logged in User. If yes, then executes "f" body.
   * Else does action based on onAuthFailure.withNewSession
   *
   * @tparam T the content type
   * @param bodyParser the `BodyParser` to use to parse the request body
   * @param onAuthFailure function used to generate alternative result if the user is not authenticated
   * @param f Body. It gets User and request object as arguments and returns a Result. Just like any other Action
   */
  def GeneralFilter[T](bodyParser: BodyParser[T] = parse.anyContent)(onAuthFailure: RequestHeader => SimpleResult)(f: => A => Request[T] => Result) =
    Security.Authenticated(username, onAuthFailure) { id =>
      Action(bodyParser) { request =>
        fromSession(id) match {
          case Left(err) => {
            Logger.error(s"A session value from a request is inconsistent to protocol: $err . Session in header: $id")
            onAuthFailure(request).withNewSession
          }
          case Right(x) => f(x)(request)
        }
      }
    }
}

sealed trait DashboardSecurity extends WebSecurity[User] {

  import play.api.mvc.Results.Redirect

  override protected def fromSession(param: String): Either[String, User] = Users.getUser(param).map(Right(_)).getOrElse(Left("Invalid Session Id"))
  }

  def toSession(param: User): (String, String) = (sessionId, param.id.toString)

}

object Dashboard extends Controller with DashboardSecurity {
/**
   * Home page of the User
   */
  def homePage = GeneralFilter()(loginPage) { id =>
    implicit request =>
      Ok("Welcome home - " + id)
  }
}

上面的homePage,如果用户没有通过认证,那么直接重定向到loginPage

于 2013-10-08T18:08:32.473 回答
0

看看播放文档www.playframework.com/documentation/2.0.x/ScalaSecurity在这里你有示例如何使用 Secured trait 来执行授权

于 2013-10-08T13:38:31.637 回答