├── .gitignore ├── README.md ├── action-cont-lib └── src │ └── main │ └── scala │ └── com │ └── github │ └── hexx │ └── play │ └── cont │ └── play2auth │ ├── AsyncAuthCont.scala │ └── AuthElementCont.scala ├── action-cont-simple └── src │ └── main │ └── scala │ └── com │ └── github │ └── hexx │ └── play │ └── cont │ └── simple │ ├── ActionCont.scala │ ├── Cont.scala │ ├── FlowCont.scala │ ├── LoginController.scala │ └── package.scala ├── action-cont └── src │ ├── main │ └── scala │ │ └── com │ │ └── github │ │ └── hexx │ │ └── play │ │ └── cont │ │ ├── ActionCont.scala │ │ ├── FlowCont.scala │ │ ├── FormCont.scala │ │ └── package.scala │ └── test │ └── scala │ └── com │ └── github │ └── hexx │ └── play │ └── cont │ └── FormContTest.scala ├── build.sbt ├── play2-auth-cont-sample ├── app │ ├── Global.scala │ ├── controllers │ │ ├── BaseAuthConfig.scala │ │ ├── basic │ │ │ ├── AuthConfigImpl.scala │ │ │ ├── BasicAuthIdContainer.scala │ │ │ ├── BasicAuthTokenAccessor.scala │ │ │ └── Messages.scala │ │ ├── builder │ │ │ ├── AuthConfigImpl.scala │ │ │ ├── Messages.scala │ │ │ └── Sessions.scala │ │ ├── cont │ │ │ ├── MessageCont.scala │ │ │ ├── PjaxCont.scala │ │ │ └── TokenValidateElementCont.scala │ │ ├── csrf │ │ │ ├── AuthConfigImpl.scala │ │ │ ├── PreventingCsrfSample.scala │ │ │ └── Sessions.scala │ │ ├── ephemeral │ │ │ ├── AuthConfigImpl.scala │ │ │ ├── Messages.scala │ │ │ └── Sessions.scala │ │ ├── rememberme │ │ │ ├── AuthConfigImpl.scala │ │ │ ├── Messages.scala │ │ │ ├── RememberMeTokenAccessor.scala │ │ │ └── Sessions.scala │ │ ├── stack │ │ │ ├── Pjax.scala │ │ │ └── TokenValidateElement.scala │ │ ├── standard │ │ │ ├── AuthConfigImpl.scala │ │ │ ├── Messages.scala │ │ │ └── Sessions.scala │ │ └── stateless │ │ │ ├── AuthConfigImpl.scala │ │ │ ├── Messages.scala │ │ │ └── Sessions.scala │ ├── jp │ │ └── t2v │ │ │ └── lab │ │ │ └── play2 │ │ │ └── auth │ │ │ └── sample │ │ │ ├── Account.scala │ │ │ └── Role.scala │ └── views │ │ ├── basic │ │ └── fullTemplate.scala.html │ │ ├── builder │ │ ├── fullTemplate.scala.html │ │ └── login.scala.html │ │ ├── csrf │ │ ├── formWithToken.scala.html │ │ ├── formWithoutToken.scala.html │ │ ├── fullTemplate.scala.html │ │ └── login.scala.html │ │ ├── ephemeral │ │ ├── fullTemplate.scala.html │ │ └── login.scala.html │ │ ├── message │ │ ├── detail.scala.html │ │ ├── list.scala.html │ │ ├── main.scala.html │ │ └── write.scala.html │ │ ├── pjaxTemplate.scala.html │ │ ├── rememberme │ │ ├── fullTemplate.scala.html │ │ └── login.scala.html │ │ ├── standard │ │ ├── fullTemplate.scala.html │ │ └── login.scala.html │ │ └── stateless │ │ ├── fullTemplate.scala.html │ │ └── login.scala.html ├── conf │ ├── application.conf │ ├── db │ │ └── migration │ │ │ └── default │ │ │ └── V1__create_tables.sql │ ├── play.plugins │ └── routes ├── public │ ├── images │ │ └── favicon.png │ ├── javascripts │ │ ├── jquery-1.7.1.min.js │ │ └── jquery.pjax.js │ └── stylesheets │ │ └── main.css └── test │ ├── ApplicationSpec.scala │ └── IntegrationSpec.scala └── project ├── build.properties └── plugins.sbt /.gitignore: -------------------------------------------------------------------------------- 1 | logs 2 | project/project 3 | target 4 | .idea 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ActionCont 2 | 3 | 継続モナドを使ってPlay FrameworkのActionを組み立てるためのライブラリです。 4 | 5 | これは説明のために書かれたライブラリであり、今後メンテナンスしていく予定はありません。 6 | 7 | ## ライセンス 8 | 9 | public domain 10 | 11 | ## 概要 12 | 13 | 個人的な考えですが、継続モナドはWebアプリケーションのコントローラーを書くのに非常に適したものだと考えています。 14 | 15 | おおまかなイメージを話しますと、継続モナドはコールバック関数を受け取り、その前後に処理を挟むことができます。 16 | この動作をWebアプリケーションのコントローラーで考えてみますと、リクエストを受け取りレスポンスを返す関数を受け取り、その前後に処理を挟むことができるということになります。 17 | これはコントローラを構成する部品を作る上で便利な性質になります。 18 | たとえばJava EEのServlet Filterはまさにそういう動作をする仕組みです。 19 | それに加えて、継続モナドはモナドなのでScalaのfor構文を使い、自由に組み立てることができます。 20 | そう言われると、なんとなく継続モナドが便利な予感がしてきたでしょうか。 21 | 22 | 今回比較のために、がくぞ(@gakuzzzz)さんの [t2v/play2-auth](https://github.com/t2v/play2-auth) のサンプルのActionの合成部分を継続モナドを使って再実装させていただきました。 23 | play2-authのサンプルには、がくぞさん自身が作られた [t2v/stackable-controller](https://github.com/t2v/stackable-controller) を使ったActionの合成と、Play標準のActionBuilderを使ったActionの合成のサンプルが書かれています。 24 | 今回の継続モナドを使った手法と見比べていただければと思います。 25 | 26 | 以下、簡単にプロジェクトの説明をさせていただきます。 27 | また後日、詳しいブログ記事などを書く予定ですので、軽く雰囲気だけを掴んでください。 28 | 29 | ## action-cont 30 | 31 | 継続モナドの中心部分が入っているプロジェクトです。 32 | 今回 `ContT[Future, Result, A]` を `ActionCont[A]` と名付けました。 33 | 34 | ```scala 35 | type ActionCont[A] = ContT[Future, Result, A] 36 | ``` 37 | 38 | Scalazの `ContT` が使われていますが、今回のやり方ではもっと簡単な継続モナドでもかまいません。 39 | 40 | ```scala 41 | case class Cont[R, A](run: (A => R) => R) { 42 | def map[B](f: A => B): Cont[R, B] = Cont(k => run(a => k(f(a)))) 43 | def flatMap[B](f: A => Cont[R, B]): Cont[R, B] = Cont(k => run(a => f(a).run(k))) 44 | } 45 | 46 | type ActionCont[A] = Cont[Future[Result], A] 47 | ``` 48 | 49 | Scalazではなく、以上のような簡単なコードでも同じように動作します。 50 | 51 | ## action-cont-lib 52 | 53 | 既存のライブラリを使って `ActionCont` の形の部品を作ったライブラリにする予定なのですが、今のところplay2-auth関連のものしかありません。 54 | 55 | - `AsyncAuthCont` はplay2-authの `AsyncAuth` に対応しています。 56 | - `AuthElementCont` はplay2-authの `AuthElement` に対応しています。 57 | 58 | どちらも後ろにContを付けただけです。 59 | 60 | ## play2-auth-cont-sample 61 | 62 | play2-authのsampleに対応しています。と言っても全部が再実装されているわけではなく、以下のものだけが継続モナドを使った実装になっています。 63 | 64 | - [play2-auth-cont-sample/app/controllers/cont/PjaxCont.scala](https://github.com/hexx/action-cont/blob/master/play2-auth-cont-sample/app/controllers/cont/PjaxCont.scala) 65 | - [play2-auth-cont-sample/app/controllers/cont/TokenValidateElementCont.scala](https://github.com/hexx/action-cont/blob/master/play2-auth-cont-sample/app/controllers/cont/TokenValidateElementCont.scala) 66 | - [play2-auth-cont-sample/app/controllers/cont/MessageCont.scala](https://github.com/hexx/action-cont/blob/master/play2-auth-cont-sample/app/controllers/cont/MessageCont.scala) 67 | - [play2-auth-cont-sample/app/controllers/standard/Messages.scala](https://github.com/hexx/action-cont/blob/master/play2-auth-cont-sample/app/controllers/standard/Messages.scala) 68 | - [play2-auth-cont-sample/app/controllers/csrf/PreventingCsrfSample.scala](https://github.com/hexx/action-cont/blob/master/play2-auth-cont-sample/app/controllers/csrf/PreventingCsrfSample.scala) 69 | 70 | この他の部分はStackable ControllerやActionBuilderで作られているので見比べてみてください。 71 | -------------------------------------------------------------------------------- /action-cont-lib/src/main/scala/com/github/hexx/play/cont/play2auth/AsyncAuthCont.scala: -------------------------------------------------------------------------------- 1 | package com.github.hexx.play.cont.play2auth 2 | 3 | import com.github.hexx.play.cont.ActionCont 4 | import jp.t2v.lab.play2.auth.AuthConfig 5 | import play.api.mvc.RequestHeader 6 | 7 | import scala.concurrent.ExecutionContext 8 | 9 | trait AsyncAuthCont extends AuthConfig { 10 | def authorizedCont(authority: Authority)(implicit request: RequestHeader, ec: ExecutionContext): ActionCont[User] = 11 | ActionCont(f => 12 | restoreUserCont.run { 13 | case None => authenticationFailed(request) 14 | case Some(user) => 15 | authorize(user, authority).flatMap { 16 | case true => f(user) 17 | case _ => authorizationFailed(request, user, Some(authority)) 18 | } 19 | } 20 | ) 21 | 22 | private[play2auth] def restoreUserCont(implicit request: RequestHeader, ec: ExecutionContext): ActionCont[Option[User]] = 23 | ActionCont(f => 24 | (for { 25 | token <- tokenAccessor.extract(request) 26 | } yield for { 27 | Some(userId) <- idContainer.get(token) 28 | Some(user) <- resolveUser(userId) 29 | _ <- idContainer.prolongTimeout(token, sessionTimeoutInSeconds) 30 | result <- f(Option(user)) 31 | } yield tokenAccessor.put(token)(result) 32 | ) getOrElse f(Option.empty) 33 | ) 34 | } 35 | -------------------------------------------------------------------------------- /action-cont-lib/src/main/scala/com/github/hexx/play/cont/play2auth/AuthElementCont.scala: -------------------------------------------------------------------------------- 1 | package com.github.hexx.play.cont.play2auth 2 | 3 | import com.github.hexx.play.cont.ActionCont 4 | import play.api.mvc.RequestHeader 5 | 6 | import scala.concurrent.ExecutionContext 7 | 8 | trait AuthElementCont extends AsyncAuthCont { 9 | def authElementCont(authority: Authority)(implicit request: RequestHeader, ec: ExecutionContext): ActionCont[User] = 10 | authorizedCont(authority) 11 | 12 | def authElementCont(implicit request: RequestHeader, ec: ExecutionContext): ActionCont[User] = 13 | ActionCont(_ => 14 | restoreUserCont.run { 15 | case Some(user) => authorizationFailed(request, user, None) 16 | case None => authenticationFailed(request) 17 | } 18 | ) 19 | } 20 | -------------------------------------------------------------------------------- /action-cont-simple/src/main/scala/com/github/hexx/play/cont/simple/ActionCont.scala: -------------------------------------------------------------------------------- 1 | package com.github.hexx.play.cont.simple 2 | 3 | import play.api.mvc.Result 4 | import scala.concurrent.ExecutionContext 5 | import scala.concurrent.Future 6 | 7 | object ActionCont { 8 | def apply[A](f: (A => Future[Result]) => Future[Result]): ActionCont[A] = 9 | Cont(f) 10 | 11 | def fromFuture[A](future: => Future[A])(implicit ec: ExecutionContext): ActionCont[A] = 12 | Cont(future.flatMap) 13 | 14 | def successful[A](a: A)(implicit ec: ExecutionContext): ActionCont[A] = 15 | fromFuture(Future.successful(a)) 16 | 17 | def failed[A](throwable: Throwable)(implicit ec: ExecutionContext): ActionCont[A] = 18 | fromFuture(Future.failed(throwable)) 19 | 20 | def recover[A](actionCont: ActionCont[A])(pf: PartialFunction[Throwable, Future[Result]]) 21 | (implicit executor: ExecutionContext): ActionCont[A] = 22 | ActionCont(f => actionCont.run(f).recoverWith(pf)) 23 | } 24 | -------------------------------------------------------------------------------- /action-cont-simple/src/main/scala/com/github/hexx/play/cont/simple/Cont.scala: -------------------------------------------------------------------------------- 1 | package com.github.hexx.play.cont.simple 2 | 3 | case class Cont[R, A](run: (A => R) => R) { 4 | def map[B](f: A => B): Cont[R, B] = 5 | Cont(k => run(a => k(f(a)))) 6 | 7 | def flatMap[B](f: A => Cont[R, B]): Cont[R, B] = 8 | Cont(k => run(a => f(a).run(k))) 9 | 10 | def withFilter(f: A => Boolean): Cont[R, A] = 11 | Cont(k => run(a => if (f(a)) k(a) else throw new NoSuchElementException("Cont must not fail to filter."))) 12 | } 13 | -------------------------------------------------------------------------------- /action-cont-simple/src/main/scala/com/github/hexx/play/cont/simple/FlowCont.scala: -------------------------------------------------------------------------------- 1 | package com.github.hexx.play.cont.simple 2 | 3 | import play.api.mvc.AnyContent 4 | import play.api.mvc.Request 5 | import play.api.mvc.Result 6 | import scala.concurrent.ExecutionContext 7 | import scala.concurrent.Future 8 | 9 | object FlowCont { 10 | def apply[WholeRequestContext, NormalRequestContext]( 11 | request: Request[AnyContent], 12 | wholeCont: Request[AnyContent] => ActionCont[WholeRequestContext], 13 | normalCont: WholeRequestContext => ActionCont[NormalRequestContext], 14 | handlerCont: NormalRequestContext => ActionCont[Result], 15 | errorCont: WholeRequestContext => Throwable => ActionCont[Result]) 16 | (implicit executionContext: ExecutionContext): ActionCont[Result] = { 17 | 18 | for { 19 | // 正常系と異常系共通で適用される処理 20 | wholeRequestContext <- wholeCont(request) 21 | wholeResult <- ActionCont.recover( 22 | for { 23 | // 正常系だけで適用される処理 24 | normalRequestContext <- normalCont(wholeRequestContext) 25 | // コントローラーの処理本体 26 | result <- handlerCont(normalRequestContext) 27 | } yield result) { 28 | // 異常系の処理 29 | case e => errorCont(wholeRequestContext)(e).run(Future.successful) 30 | } 31 | } yield wholeResult 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /action-cont-simple/src/main/scala/com/github/hexx/play/cont/simple/LoginController.scala: -------------------------------------------------------------------------------- 1 | package com.github.hexx.play.cont.simple 2 | 3 | import play.api.mvc.Action 4 | import play.api.mvc.AnyContent 5 | import play.api.mvc.Controller 6 | import play.api.mvc.Request 7 | import play.api.mvc.Result 8 | import play.api.data.Form 9 | import play.api.data.Forms._ 10 | import play.api.libs.json.Json 11 | import scala.concurrent.ExecutionContext 12 | import scala.concurrent.Future 13 | 14 | // 説明用のログイン処理 15 | // 説明用なので実装されていないところが多いです 16 | // より実践的な例は play2-auth-cont-sample を参考にしてください 17 | object LoginController extends Controller { 18 | case class AuthParam(name: String, password: String) 19 | 20 | val authParamForm = Form( 21 | mapping( 22 | "name" -> text, 23 | "password" -> text 24 | )(AuthParam.apply)(_ => None) 25 | ) 26 | 27 | case class User(id: Int, name: String) 28 | 29 | def authParamCont(request: Request[AnyContent]): ActionCont[AuthParam] = 30 | ActionCont((f: AuthParam => Future[Result]) => 31 | authParamForm.bindFromRequest()(request).fold( 32 | error => Future.successful(BadRequest), 33 | authParam => f(authParam) 34 | ) 35 | ) 36 | 37 | def corsCont: Request[AnyContent] => ActionCont[Unit] = ??? 38 | 39 | def loginCont: AuthParam => ActionCont[User] = ??? 40 | 41 | def combinedCont(request: Request[AnyContent]): ActionCont[User] = 42 | for { 43 | _ <- corsCont(request) 44 | authParam <- authParamCont(request) 45 | user <- loginCont(authParam) 46 | } yield user 47 | 48 | def login = Action.async { request => 49 | 50 | val cont: ActionCont[Result] = for { 51 | user <- combinedCont(request) 52 | } yield Ok(Json.obj("id" -> user.id)) 53 | 54 | cont.run(Future.successful) 55 | } 56 | 57 | class FormErrorException extends Throwable 58 | 59 | class UserNotFoundException extends Throwable 60 | 61 | def loginFlow = Action.async { request => 62 | implicit val ec: ExecutionContext = play.api.libs.concurrent.Execution.defaultContext 63 | FlowCont( 64 | request = request, 65 | wholeCont = corsCont, 66 | normalCont = (_: Unit) => authParamCont(request), 67 | handlerCont = loginCont(_: AuthParam).map(user => Ok(Json.obj("id" -> user.id))), 68 | errorCont = (_: Unit) => ((_: Throwable) match { 69 | case e: FormErrorException => BadRequest 70 | case e: UserNotFoundException => NotFound 71 | case _ => InternalServerError 72 | }).andThen(ActionCont.successful) 73 | ).run(Future.successful) 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /action-cont-simple/src/main/scala/com/github/hexx/play/cont/simple/package.scala: -------------------------------------------------------------------------------- 1 | package com.github.hexx.play.cont 2 | 3 | import play.api.mvc.Result 4 | import scala.concurrent.Future 5 | 6 | package object simple { 7 | type ActionCont[A] = Cont[Future[Result], A] 8 | } 9 | -------------------------------------------------------------------------------- /action-cont/src/main/scala/com/github/hexx/play/cont/ActionCont.scala: -------------------------------------------------------------------------------- 1 | package com.github.hexx.play.cont 2 | 3 | import play.api.mvc.Action 4 | import play.api.mvc.AnyContent 5 | import play.api.mvc.Request 6 | import play.api.mvc.Result 7 | import scala.concurrent.ExecutionContext 8 | import scala.concurrent.Future 9 | import scalaz._ 10 | import scalaz.contrib.std.scalaFuture._ 11 | 12 | object ActionCont extends IndexedContsTInstances with IndexedContsTFunctions { 13 | def apply[A](f: (A => Future[Result]) => Future[Result]): ActionCont[A] = 14 | ContT(f) 15 | 16 | def fromFuture[A](future: => Future[A])(implicit ec: ExecutionContext): ActionCont[A] = 17 | ActionCont(future.flatMap) 18 | 19 | def successful[A](a: A)(implicit ec: ExecutionContext): ActionCont[A] = 20 | fromFuture(Future.successful(a)) 21 | 22 | def failed[A](throwable: Throwable)(implicit ec: ExecutionContext): ActionCont[A] = 23 | fromFuture(Future.failed(throwable)) 24 | 25 | def run(f: Request[AnyContent] => ActionCont[Result])(implicit ec: ExecutionContext): Action[AnyContent] = 26 | Action.async(f(_).run_) 27 | 28 | def recover[A](actionCont: ActionCont[A])(pf: PartialFunction[Throwable, Future[Result]])(implicit executor: ExecutionContext): ActionCont[A] = 29 | ActionCont(f => actionCont.run(f).recoverWith(pf)) 30 | } 31 | -------------------------------------------------------------------------------- /action-cont/src/main/scala/com/github/hexx/play/cont/FlowCont.scala: -------------------------------------------------------------------------------- 1 | package com.github.hexx.play.cont 2 | 3 | import play.api.mvc.AnyContent 4 | import play.api.mvc.Request 5 | import play.api.mvc.Result 6 | import scala.concurrent.ExecutionContext 7 | import scalaz.contrib.std.scalaFuture._ 8 | 9 | object FlowCont { 10 | def apply[WholeRequestContext, NormalRequestContext]( 11 | request: Request[AnyContent], 12 | wholeCont: Request[AnyContent] => ActionCont[WholeRequestContext], 13 | normalCont: WholeRequestContext => ActionCont[NormalRequestContext], 14 | handlerCont: NormalRequestContext => ActionCont[Result], 15 | errorCont: WholeRequestContext => Throwable => ActionCont[Result]) 16 | (implicit executionContext: ExecutionContext): ActionCont[Result] = { 17 | 18 | for { 19 | wholeRequestContext <- wholeCont(request) 20 | wholeResult <- ActionCont.recover( 21 | for { 22 | normalRequestContext <- normalCont(wholeRequestContext) 23 | result <- handlerCont(normalRequestContext) 24 | } yield result) { 25 | case e => errorCont(wholeRequestContext)(e).run_ 26 | } 27 | } yield wholeResult 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /action-cont/src/main/scala/com/github/hexx/play/cont/FormCont.scala: -------------------------------------------------------------------------------- 1 | package com.github.hexx.play.cont 2 | 3 | import play.api.data.Form 4 | import play.api.mvc.Result 5 | import play.api.mvc.Request 6 | import scala.concurrent.Future 7 | 8 | case class FormErrorException[A]( 9 | message: String = null, 10 | cause: Throwable = null, 11 | form: Form[A] 12 | ) extends Exception(message, cause) 13 | 14 | object FormCont { 15 | def apply[A](form: Form[A], request: Request[_]): ActionCont[A] = 16 | ActionCont(form.bindFromRequest()(request).fold(form => Future.failed(FormErrorException(form = form)), _)) 17 | 18 | def hasErrors[A](form: Form[A], request: Request[_])(hasErrors: Form[A] => Future[Result]): ActionCont[A] = 19 | ActionCont(form.bindFromRequest()(request).fold(hasErrors, _)) 20 | } 21 | -------------------------------------------------------------------------------- /action-cont/src/main/scala/com/github/hexx/play/cont/package.scala: -------------------------------------------------------------------------------- 1 | package com.github.hexx.play 2 | 3 | import play.api.mvc.Result 4 | import scala.concurrent.Future 5 | import scalaz.ContT 6 | 7 | package object cont { 8 | type ActionCont[A] = ContT[Future, Result, A] 9 | 10 | implicit class ActionContWithFilter[A](val actionCont: ActionCont[A]) extends AnyVal { 11 | def withFilter(f: A => Boolean): ActionCont[A] = 12 | ActionCont(k => 13 | actionCont.run(a => 14 | if (f(a)) { 15 | k(a) 16 | } else { 17 | throw new NoSuchElementException("ActionCont must not fail to filter.") 18 | } 19 | ) 20 | ) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /action-cont/src/test/scala/com/github/hexx/play/cont/FormContTest.scala: -------------------------------------------------------------------------------- 1 | package com.github.hexx.play.cont 2 | 3 | import org.scalatest.FunSpec 4 | import play.api.data.Form 5 | import play.api.data.Forms._ 6 | import play.api.mvc.Action 7 | import play.api.mvc.AnyContent 8 | import play.api.mvc.Request 9 | import play.api.mvc.Result 10 | import play.api.mvc.Results._ 11 | import play.api.test.FakeRequest 12 | import play.api.test.Helpers._ 13 | import scala.concurrent.ExecutionContext.Implicits.global 14 | import scala.concurrent.Future 15 | 16 | import scala.concurrent.Await 17 | import scala.concurrent.duration._ 18 | 19 | class FormContSpec extends FunSpec { 20 | case class AuthenticationParameter( 21 | name: String, 22 | password: String 23 | ) 24 | 25 | val authenticationParameterForm: Form[AuthenticationParameter] = Form( 26 | mapping( 27 | "name" -> text, 28 | "password" -> text 29 | )(AuthenticationParameter.apply)(_ => None) 30 | ) 31 | 32 | def cont(request: Request[AnyContent]): ActionCont[Result] = 33 | for { 34 | a <- FormCont(authenticationParameterForm, request) 35 | } yield Ok(s"name: ${a.name}, password: ${a.password}") 36 | 37 | def contBadRequestIfError(request: Request[AnyContent]): ActionCont[Result] = 38 | for { 39 | a <- FormCont.hasErrors(authenticationParameterForm, request)(_ => Future.successful(BadRequest)) 40 | } yield Ok(s"name: ${a.name}, password: ${a.password}") 41 | 42 | describe("FormCont") { 43 | it("result in Ok") { 44 | val action = ActionCont.run(cont) 45 | val request = FakeRequest("POST", "/").withFormUrlEncodedBody("name" -> "hexx", "password" -> "hogeika") 46 | val result = call(action, request) 47 | 48 | assert(status(result) === OK) 49 | assert(contentAsString(result) === "name: hexx, password: hogeika") 50 | } 51 | 52 | it("produce FormErrorException by an insufficient request") { 53 | val action = ActionCont.run(cont) 54 | val request = FakeRequest("POST", "/").withFormUrlEncodedBody("name" -> "hexx") 55 | val result = call(action, request) 56 | 57 | intercept[FormErrorException[AuthenticationParameter]] { 58 | status(result) 59 | } 60 | } 61 | 62 | it("result in BadRequest by an insufficient request") { 63 | val action = ActionCont.run(contBadRequestIfError) 64 | val request = FakeRequest("POST", "/").withFormUrlEncodedBody("name" -> "hexx") 65 | val result = call(action, request) 66 | 67 | assert(status(result) === BAD_REQUEST) 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /build.sbt: -------------------------------------------------------------------------------- 1 | val commonSettings = Seq( 2 | scalaVersion := "2.10.5", 3 | scalacOptions ++= Seq("-deprecation", "-feature", "-unchecked", "-Xlint", "-language:_"), 4 | resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/" 5 | ) 6 | 7 | lazy val root = (project in file(".")).aggregate( 8 | actionCont, 9 | actionContSimple, 10 | actionContLib, 11 | play2AuthContSample 12 | ) 13 | 14 | lazy val actionCont = (project in file("action-cont")).settings( 15 | commonSettings ++ Seq( 16 | name := "action-cont", 17 | organization := "com.github.hexx", 18 | libraryDependencies ++= Seq( 19 | "com.typesafe.play" %% "play" % play.core.PlayVersion.current % "provided", 20 | "org.scalaz" %% "scalaz-core" % "7.0.7", 21 | "org.typelevel" %% "scalaz-contrib-210" % "0.1.5", 22 | "com.typesafe.play" %% "play-test" % play.core.PlayVersion.current % "test", 23 | "org.scalatest" %% "scalatest" % "2.2.4" % "test" 24 | ) 25 | ):_* 26 | ) 27 | 28 | lazy val actionContSimple = (project in file("action-cont-simple")).settings( 29 | commonSettings ++ Seq( 30 | libraryDependencies ++= Seq( 31 | "com.typesafe.play" %% "play" % play.core.PlayVersion.current % "provided" 32 | ) 33 | ):_* 34 | ) 35 | 36 | lazy val actionContLib = (project in file("action-cont-lib")).settings( 37 | commonSettings ++ Seq( 38 | libraryDependencies ++= Seq( 39 | "jp.t2v" %% "play2-auth" % "0.13.2" 40 | ) 41 | ):_* 42 | ).dependsOn(actionCont) 43 | 44 | lazy val play2AuthContSample = (project in file("play2-auth-cont-sample")).settings( 45 | commonSettings ++ Seq( 46 | libraryDependencies ++= Seq( 47 | jdbc, 48 | "org.mindrot" % "jbcrypt" % "0.3m", 49 | "org.scalikejdbc" %% "scalikejdbc" % "2.2.6", 50 | "org.scalikejdbc" %% "scalikejdbc-config" % "2.2.6", 51 | "org.scalikejdbc" %% "scalikejdbc-syntax-support-macro" % "2.2.6", 52 | "org.scalikejdbc" %% "scalikejdbc-test" % "2.2.6" % "test", 53 | "org.scalikejdbc" %% "scalikejdbc-play-plugin" % "2.3.6", 54 | "com.github.tototoshi" %% "play-flyway" % "1.2.1", 55 | "jp.t2v" %% "play2-auth-test" % "0.13.2" % "test" 56 | ), 57 | TwirlKeys.templateImports += "jp.t2v.lab.play2.auth.sample._" 58 | ) 59 | ).enablePlugins(play.PlayScala).dependsOn(actionContLib) 60 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/Global.scala: -------------------------------------------------------------------------------- 1 | import play.api._ 2 | 3 | import jp.t2v.lab.play2.auth.sample._ 4 | import jp.t2v.lab.play2.auth.sample.Role._ 5 | import scalikejdbc._ 6 | 7 | object Global extends GlobalSettings { 8 | 9 | override def onStart(app: Application) { 10 | if (Account.findAll.isEmpty) { 11 | Seq( 12 | Account(1, "alice@example.com", "secret", "Alice", Administrator), 13 | Account(2, "bob@example.com", "secret", "Bob", NormalUser), 14 | Account(3, "chris@example.com", "secret", "Chris", NormalUser) 15 | ) foreach Account.create 16 | } 17 | 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/BaseAuthConfig.scala: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import jp.t2v.lab.play2.auth.AuthConfig 4 | import jp.t2v.lab.play2.auth.sample.{Role, Account} 5 | import jp.t2v.lab.play2.auth.sample.Role._ 6 | import play.api.mvc.RequestHeader 7 | import play.api.mvc.Results._ 8 | 9 | import scala.concurrent.{Future, ExecutionContext} 10 | import scala.reflect._ 11 | import play.Logger 12 | 13 | trait BaseAuthConfig extends AuthConfig { 14 | 15 | type Id = Int 16 | type User = Account 17 | type Authority = Role 18 | 19 | val idTag: ClassTag[Id] = classTag[Id] 20 | val sessionTimeoutInSeconds = 3600 21 | 22 | def resolveUser(id: Id)(implicit ctx: ExecutionContext) = Future.successful(Account.findById(id)) 23 | def authorizationFailed(request: RequestHeader)(implicit ctx: ExecutionContext) = throw new AssertionError("don't use") 24 | override def authorizationFailed(request: RequestHeader, user: User, authority: Option[Authority])(implicit ctx: ExecutionContext) = { 25 | Logger.info(s"authorizationFailed. userId: ${user.id}, userName: ${user.name}, authority: $authority") 26 | Future.successful(Forbidden("no permission")) 27 | } 28 | def authorize(user: User, authority: Authority)(implicit ctx: ExecutionContext) = Future.successful((user.role, authority) match { 29 | case (Administrator, _) => true 30 | case (NormalUser, NormalUser) => true 31 | case _ => false 32 | }) 33 | 34 | } 35 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/basic/AuthConfigImpl.scala: -------------------------------------------------------------------------------- 1 | package controllers.basic 2 | 3 | import play.api.mvc.RequestHeader 4 | import play.api.mvc.Results._ 5 | 6 | import scala.concurrent.{Future, ExecutionContext} 7 | import jp.t2v.lab.play2.auth.AuthConfig 8 | import jp.t2v.lab.play2.auth.sample.{Role, Account} 9 | import jp.t2v.lab.play2.auth.sample.Role._ 10 | import scala.reflect.{ClassTag, classTag} 11 | 12 | trait AuthConfigImpl extends AuthConfig { 13 | 14 | type Id = Account 15 | type User = Account 16 | type Authority = Role 17 | 18 | val idTag: ClassTag[Id] = classTag[Id] 19 | val sessionTimeoutInSeconds = 3600 20 | 21 | def resolveUser(id: Id)(implicit ctx: ExecutionContext) = Future.successful(Some(id)) 22 | def authorize(user: User, authority: Authority)(implicit ctx: ExecutionContext) = Future.successful((user.role, authority) match { 23 | case (Administrator, _) => true 24 | case (NormalUser, NormalUser) => true 25 | case _ => false 26 | }) 27 | 28 | def loginSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext) = throw new AssertionError("don't use application Login") 29 | def logoutSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext) = throw new AssertionError("don't use application Logout") 30 | def authenticationFailed(request: RequestHeader)(implicit ctx: ExecutionContext) = Future.successful { 31 | Unauthorized.withHeaders("WWW-Authenticate" -> """Basic realm="SECRET AREA"""") 32 | } 33 | def authorizationFailed(request: RequestHeader)(implicit ctx: ExecutionContext) = Future.successful(Forbidden("no permission")) 34 | 35 | override lazy val idContainer = new BasicAuthIdContainer 36 | 37 | override lazy val tokenAccessor = new BasicAuthTokenAccessor 38 | 39 | } -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/basic/BasicAuthIdContainer.scala: -------------------------------------------------------------------------------- 1 | package controllers.basic 2 | 3 | import jp.t2v.lab.play2.auth.{AuthenticityToken, AsyncIdContainer} 4 | import play.api.mvc.RequestHeader 5 | import scala.concurrent.{Future, ExecutionContext} 6 | import jp.t2v.lab.play2.auth.sample.Account 7 | 8 | class BasicAuthIdContainer extends AsyncIdContainer[Account] { 9 | override def prolongTimeout(token: AuthenticityToken, timeoutInSeconds: Int)(implicit request: RequestHeader, context: ExecutionContext): Future[Unit] = { 10 | Future.successful(()) 11 | } 12 | 13 | override def get(token: AuthenticityToken)(implicit context: ExecutionContext): Future[Option[Account]] = Future { 14 | val Pattern = "(.*?):(.*)".r 15 | PartialFunction.condOpt(token) { 16 | case Pattern(user, pass) => Account.authenticate(user, pass) 17 | }.flatten 18 | } 19 | 20 | override def remove(token: AuthenticityToken)(implicit context: ExecutionContext): Future[Unit] = { 21 | Future.successful(()) 22 | } 23 | 24 | override def startNewSession(userId: Account, timeoutInSeconds: Int)(implicit request: RequestHeader, context: ExecutionContext): Future[AuthenticityToken] = { 25 | throw new AssertionError("don't use") 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/basic/BasicAuthTokenAccessor.scala: -------------------------------------------------------------------------------- 1 | package controllers.basic 2 | 3 | import jp.t2v.lab.play2.auth.{AuthenticityToken, TokenAccessor} 4 | import play.api.mvc.{Result, RequestHeader} 5 | import org.apache.commons.codec.binary.Base64 6 | import java.nio.charset.Charset 7 | 8 | class BasicAuthTokenAccessor extends TokenAccessor { 9 | 10 | override def delete(result: Result)(implicit request: RequestHeader): Result = result 11 | 12 | override def put(token: AuthenticityToken)(result: Result)(implicit request: RequestHeader): Result = result 13 | 14 | override def extract(request: RequestHeader): Option[AuthenticityToken] = { 15 | val encoded = for { 16 | h <- request.headers.get("Authorization") 17 | if h.startsWith("Basic ") 18 | } yield h.substring(6) 19 | encoded.map(s => new String(Base64.decodeBase64(s), Charset.forName("UTF-8"))) 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/basic/Messages.scala: -------------------------------------------------------------------------------- 1 | package controllers.basic 2 | 3 | import controllers.stack.Pjax 4 | import jp.t2v.lab.play2.auth.AuthElement 5 | import play.api.mvc.Controller 6 | import views.html 7 | import jp.t2v.lab.play2.auth.sample.Role._ 8 | import play.twirl.api.Html 9 | 10 | trait Messages extends Controller with AuthElement with AuthConfigImpl { 11 | 12 | def main = StackAction(AuthorityKey -> NormalUser) { implicit request => 13 | val title = "message main" 14 | Ok(html.message.main(title)) 15 | } 16 | 17 | def list = StackAction(AuthorityKey -> NormalUser) { implicit request => 18 | val title = "all messages" 19 | Ok(html.message.list(title)) 20 | } 21 | 22 | def detail(id: Int) = StackAction(AuthorityKey -> NormalUser) { implicit request => 23 | val title = "messages detail " 24 | Ok(html.message.detail(title + id)) 25 | } 26 | 27 | def write = StackAction(AuthorityKey -> Administrator) { implicit request => 28 | val title = "write message" 29 | Ok(html.message.write(title)) 30 | } 31 | 32 | protected implicit def template(implicit user: User): String => Html => Html = html.basic.fullTemplate(user) 33 | 34 | } 35 | object Messages extends Messages 36 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/builder/AuthConfigImpl.scala: -------------------------------------------------------------------------------- 1 | package controllers.builder 2 | 3 | import controllers.BaseAuthConfig 4 | import play.api.mvc.RequestHeader 5 | import play.api.mvc.Results._ 6 | 7 | import scala.concurrent.{Future, ExecutionContext} 8 | 9 | trait AuthConfigImpl extends BaseAuthConfig { 10 | 11 | def loginSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext) = Future.successful(Redirect(routes.Messages.main)) 12 | 13 | def logoutSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext) = Future.successful(Redirect(routes.Sessions.login)) 14 | 15 | def authenticationFailed(request: RequestHeader)(implicit ctx: ExecutionContext) = Future.successful(Redirect(routes.Sessions.login)) 16 | 17 | } -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/builder/Messages.scala: -------------------------------------------------------------------------------- 1 | package controllers.builder 2 | 3 | import jp.t2v.lab.play2.auth.AuthActionBuilders 4 | import jp.t2v.lab.play2.auth.sample.Account 5 | import jp.t2v.lab.play2.auth.sample.Role._ 6 | import play.api.mvc._ 7 | import play.twirl.api.Html 8 | import scalikejdbc.{DB, DBSession} 9 | import views.html 10 | 11 | import scala.concurrent.Future 12 | 13 | class TransactionalRequest[A](val dbSession: DBSession, request: Request[A]) extends WrappedRequest[A](request) 14 | object TransactionalAction extends ActionBuilder[TransactionalRequest] { 15 | override def invokeBlock[A](request: Request[A], block: (TransactionalRequest[A]) => Future[Result]): Future[Result] = { 16 | import scalikejdbc.TxBoundary.Future._ 17 | implicit val ctx = executionContext 18 | DB.localTx { session => 19 | block(new TransactionalRequest(session, request)) 20 | } 21 | } 22 | } 23 | 24 | trait Messages extends Controller with AuthActionBuilders with AuthConfigImpl { 25 | 26 | type AuthTxRequest[A] = GenericAuthRequest[A, TransactionalRequest] 27 | final def AuthorizationTxAction(authority: Authority): ActionBuilder[AuthTxRequest] = composeAuthorizationAction(TransactionalAction)(authority) 28 | 29 | class PjaxAuthRequest[A](val template: String => Html => Html, val authRequest: AuthTxRequest[A]) extends WrappedRequest[A](authRequest) 30 | object PjaxRefiner extends ActionTransformer[AuthTxRequest, PjaxAuthRequest] { 31 | override protected def transform[A](request: AuthTxRequest[A]): Future[PjaxAuthRequest[A]] = { 32 | val template: String => Html => Html = if (request.headers.keys("X-Pjax")) html.pjaxTemplate.apply else html.builder.fullTemplate.apply(request.user) 33 | Future.successful(new PjaxAuthRequest(template, request)) 34 | } 35 | } 36 | 37 | def MyAction(authority: Authority): ActionBuilder[PjaxAuthRequest] = AuthorizationTxAction(authority) andThen PjaxRefiner 38 | 39 | def main = MyAction(NormalUser) { implicit request => 40 | val title = "message main" 41 | println(Account.findAll()(request.authRequest.underlying.dbSession)) 42 | Ok(html.message.main(title)(request.template)) 43 | } 44 | 45 | def list = MyAction(NormalUser) { implicit request => 46 | val title = "all messages" 47 | Ok(html.message.list(title)(request.template)) 48 | } 49 | 50 | def detail(id: Int) = MyAction(NormalUser) {implicit request => 51 | val title = "messages detail " 52 | Ok(html.message.detail(title + id)(request.template)) 53 | } 54 | 55 | def write = MyAction(Administrator) { implicit request => 56 | val title = "write message" 57 | Ok(html.message.write(title)(request.template)) 58 | } 59 | 60 | } 61 | object Messages extends Messages 62 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/builder/Sessions.scala: -------------------------------------------------------------------------------- 1 | package controllers.builder 2 | 3 | import jp.t2v.lab.play2.auth.LoginLogout 4 | import jp.t2v.lab.play2.auth.sample.Account 5 | import play.api.data.Form 6 | import play.api.data.Forms._ 7 | import play.api.mvc.{Action, Controller} 8 | import views.html 9 | 10 | import scala.concurrent.Future 11 | import play.api.libs.concurrent.Execution.Implicits.defaultContext 12 | 13 | object Sessions extends Controller with LoginLogout with AuthConfigImpl { 14 | 15 | val loginForm = Form { 16 | mapping("email" -> email, "password" -> text)(Account.authenticate)(_.map(u => (u.email, ""))) 17 | .verifying("Invalid email or password", result => result.isDefined) 18 | } 19 | 20 | def login = Action { implicit request => 21 | Ok(html.builder.login(loginForm)) 22 | } 23 | 24 | def logout = Action.async { implicit request => 25 | gotoLogoutSucceeded.map(_.flashing( 26 | "success" -> "You've been logged out" 27 | )) 28 | } 29 | 30 | def authenticate = Action.async { implicit request => 31 | loginForm.bindFromRequest.fold( 32 | formWithErrors => Future.successful(BadRequest(html.builder.login(formWithErrors))), 33 | user => gotoLoginSucceeded(user.get.id) 34 | ) 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/cont/MessageCont.scala: -------------------------------------------------------------------------------- 1 | package controllers.cont 2 | 3 | import com.github.hexx.play.cont.ActionCont 4 | import com.github.hexx.play.cont.play2auth.AuthElementCont 5 | import jp.t2v.lab.play2.auth.AuthConfig 6 | import play.api.mvc.Request 7 | import play.api.mvc.Result 8 | import play.api.mvc.Results.Ok 9 | import play.twirl.api.Html 10 | import scala.concurrent.ExecutionContext 11 | 12 | trait MessageCont extends AuthElementCont with AuthConfig { 13 | type Template = controllers.cont.PjaxCont.Template 14 | 15 | def messageCont[A](authority: Authority, fullTemplate: User => Template, templateToHtml: Template => Html) 16 | (implicit request: Request[A], ec: ExecutionContext): ActionCont[Result] = 17 | for { 18 | user <- authElementCont(authority) 19 | template <- PjaxCont(fullTemplate(user)) 20 | } yield Ok(templateToHtml(template)) 21 | } 22 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/cont/PjaxCont.scala: -------------------------------------------------------------------------------- 1 | package controllers.cont 2 | 3 | import com.github.hexx.play.cont.ActionCont 4 | import play.api.mvc.RequestHeader 5 | import play.twirl.api.Html 6 | import views.html 7 | import scala.concurrent.ExecutionContext 8 | 9 | object PjaxCont { 10 | type Template = String => Html => Html 11 | 12 | def apply(fullTemplate: Template)(implicit request: RequestHeader, ec: ExecutionContext): ActionCont[Template] = 13 | ActionCont.successful(if (request.headers.keys("X-Pjax")) html.pjaxTemplate.apply else fullTemplate) 14 | } 15 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/cont/TokenValidateElementCont.scala: -------------------------------------------------------------------------------- 1 | package controllers.cont 2 | 3 | import com.github.hexx.play.cont.ActionCont 4 | import scala.concurrent.ExecutionContext 5 | import scala.concurrent.Future 6 | import play.api.mvc.Request 7 | import play.api.data._ 8 | import play.api.data.Forms._ 9 | import play.api.mvc.Results.BadRequest 10 | import scala.util.Random 11 | import java.security.SecureRandom 12 | import controllers.stack.PreventingCsrfToken 13 | 14 | trait TokenValidateElementCont { 15 | private[this] val PreventingCsrfTokenSessionKey = "preventingCsrfToken" 16 | 17 | private[this] val tokenForm = Form(PreventingCsrfToken.FormKey -> text) 18 | 19 | private[this] val random = new Random(new SecureRandom) 20 | 21 | private[this] val table = ('a' to 'z') ++ ('A' to 'Z') ++ ('0' to '9') ++ "^`~:/?,.{[}}|+_()*^%$#@!" 22 | 23 | private[this] def generateToken: PreventingCsrfToken = PreventingCsrfToken { 24 | Iterator.continually(random.nextInt(table.size)).map(table).take(32).mkString 25 | } 26 | 27 | private[this] def validateToken(request: Request[_]): Boolean = (for { 28 | tokenInForm <- tokenForm.bindFromRequest()(request).value 29 | tokenInSession <- request.session.get(PreventingCsrfTokenSessionKey) 30 | } yield tokenInForm == tokenInSession) getOrElse false 31 | 32 | def tokenValidateElementCont[A](ignoreTokenValidation: Boolean)(implicit request: Request[A], ec: ExecutionContext): ActionCont[PreventingCsrfToken] = 33 | ActionCont(f => 34 | if (ignoreTokenValidation || validateToken(request)) { 35 | val newToken = generateToken 36 | f(newToken).map(_.withSession(PreventingCsrfTokenSessionKey -> newToken.value)) 37 | } else { 38 | Future.successful(BadRequest("Invalid preventing CSRF token")) 39 | } 40 | ) 41 | 42 | } 43 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/csrf/AuthConfigImpl.scala: -------------------------------------------------------------------------------- 1 | package controllers.csrf 2 | 3 | import controllers.BaseAuthConfig 4 | import play.api.mvc.RequestHeader 5 | import play.api.mvc.Results._ 6 | 7 | import scala.concurrent.{Future, ExecutionContext} 8 | 9 | trait AuthConfigImpl extends BaseAuthConfig { 10 | 11 | def loginSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext) = Future.successful(Redirect(routes.PreventingCsrfSample.formWithToken)) 12 | def logoutSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext) = Future.successful(Redirect(routes.Sessions.login)) 13 | def authenticationFailed(request: RequestHeader)(implicit ctx: ExecutionContext) = Future.successful(Redirect(routes.Sessions.login)) 14 | 15 | } 16 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/csrf/PreventingCsrfSample.scala: -------------------------------------------------------------------------------- 1 | package controllers.csrf 2 | 3 | import com.github.hexx.play.cont._ 4 | import com.github.hexx.play.cont.play2auth.AuthElementCont 5 | import controllers.stack.PreventingCsrfToken 6 | import controllers.cont.TokenValidateElementCont 7 | import jp.t2v.lab.play2.auth.sample.Role._ 8 | import play.api.data.Form 9 | import play.api.data.Forms._ 10 | import play.api.mvc.Controller 11 | import play.api.mvc.AnyContent 12 | import play.api.mvc.Request 13 | import scala.concurrent.ExecutionContext 14 | 15 | trait PreventingCsrfSample extends Controller with AuthElementCont with TokenValidateElementCont with AuthConfigImpl { 16 | implicit val ec: ExecutionContext = play.api.libs.concurrent.Execution.defaultContext 17 | 18 | def checkCont(authority: Authority, ignoreTokenValidation: Boolean) 19 | (implicit request: Request[AnyContent], ec: ExecutionContext): ActionCont[(User, PreventingCsrfToken)] = 20 | for { 21 | user <- authElementCont(NormalUser) 22 | token <- tokenValidateElementCont(ignoreTokenValidation) 23 | } yield (user, token) 24 | 25 | def formWithToken = ActionCont.run(implicit request => 26 | for ( 27 | (user, token) <- checkCont(NormalUser, ignoreTokenValidation = true) 28 | ) yield Ok(views.html.csrf.formWithToken()(user, token)) 29 | ) 30 | 31 | def formWithoutToken = ActionCont.run(implicit request => 32 | for ( 33 | (user, _) <- checkCont(NormalUser, ignoreTokenValidation = true) 34 | ) yield Ok(views.html.csrf.formWithoutToken()(user)) 35 | ) 36 | 37 | val form = Form { single("message" -> text) } 38 | 39 | def submitTarget = ActionCont.run(implicit request => 40 | for { 41 | _ <- checkCont(NormalUser, ignoreTokenValidation = false) 42 | message <- FormCont.hasErrors(form, request)(_ => throw new Exception) 43 | } yield Ok(message).as("text/plain") 44 | ) 45 | } 46 | 47 | object PreventingCsrfSample extends PreventingCsrfSample 48 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/csrf/Sessions.scala: -------------------------------------------------------------------------------- 1 | package controllers.csrf 2 | 3 | import jp.t2v.lab.play2.auth.LoginLogout 4 | import jp.t2v.lab.play2.auth.sample.Account 5 | import play.api.data.Form 6 | import play.api.data.Forms._ 7 | import play.api.mvc.{Action, Controller} 8 | import views.html 9 | 10 | import scala.concurrent.Future 11 | import play.api.libs.concurrent.Execution.Implicits.defaultContext 12 | 13 | object Sessions extends Controller with LoginLogout with AuthConfigImpl { 14 | 15 | val loginForm = Form { 16 | mapping("email" -> email, "password" -> text)(Account.authenticate)(_.map(u => (u.email, ""))) 17 | .verifying("Invalid email or password", result => result.isDefined) 18 | } 19 | 20 | def login = Action { implicit request => 21 | Ok(html.csrf.login(loginForm)) 22 | } 23 | 24 | def logout = Action.async { implicit request => 25 | gotoLogoutSucceeded.map(_.flashing( 26 | "success" -> "You've been logged out" 27 | )) 28 | } 29 | 30 | def authenticate = Action.async { implicit request => 31 | loginForm.bindFromRequest.fold( 32 | formWithErrors => Future.successful(BadRequest(html.csrf.login(formWithErrors))), 33 | user => gotoLoginSucceeded(user.get.id) 34 | ) 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/ephemeral/AuthConfigImpl.scala: -------------------------------------------------------------------------------- 1 | package controllers.ephemeral 2 | 3 | import controllers.BaseAuthConfig 4 | import play.api.mvc.RequestHeader 5 | import play.api.mvc.Results._ 6 | 7 | import scala.concurrent.{Future, ExecutionContext} 8 | 9 | trait AuthConfigImpl extends BaseAuthConfig { 10 | 11 | def loginSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext) = Future.successful(Redirect(routes.Messages.main)) 12 | 13 | def logoutSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext) = Future.successful(Redirect(routes.Sessions.login)) 14 | 15 | def authenticationFailed(request: RequestHeader)(implicit ctx: ExecutionContext) = Future.successful(Redirect(routes.Sessions.login)) 16 | 17 | override lazy val isTransientCookie = true 18 | 19 | } -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/ephemeral/Messages.scala: -------------------------------------------------------------------------------- 1 | package controllers.ephemeral 2 | 3 | import controllers.stack.Pjax 4 | import jp.t2v.lab.play2.auth.AuthElement 5 | import play.api.mvc.Controller 6 | import views.html 7 | import jp.t2v.lab.play2.auth.sample.Role._ 8 | 9 | trait Messages extends Controller with Pjax with AuthElement with AuthConfigImpl { 10 | 11 | def main = StackAction(AuthorityKey -> NormalUser) { implicit request => 12 | val title = "message main" 13 | Ok(html.message.main(title)) 14 | } 15 | 16 | def list = StackAction(AuthorityKey -> NormalUser) { implicit request => 17 | val title = "all messages" 18 | Ok(html.message.list(title)) 19 | } 20 | 21 | def detail(id: Int) = StackAction(AuthorityKey -> NormalUser) { implicit request => 22 | val title = "messages detail " 23 | Ok(html.message.detail(title + id)) 24 | } 25 | 26 | def write = StackAction(AuthorityKey -> Administrator) { implicit request => 27 | val title = "write message" 28 | Ok(html.message.write(title)) 29 | } 30 | 31 | protected val fullTemplate: User => Template = html.ephemeral.fullTemplate.apply 32 | 33 | } 34 | object Messages extends Messages 35 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/ephemeral/Sessions.scala: -------------------------------------------------------------------------------- 1 | package controllers.ephemeral 2 | 3 | import jp.t2v.lab.play2.auth.LoginLogout 4 | import jp.t2v.lab.play2.auth.sample.Account 5 | import play.api.data.Form 6 | import play.api.data.Forms._ 7 | import play.api.mvc.{Action, Controller} 8 | import views.html 9 | 10 | import scala.concurrent.Future 11 | import play.api.libs.concurrent.Execution.Implicits.defaultContext 12 | 13 | object Sessions extends Controller with LoginLogout with AuthConfigImpl { 14 | 15 | val loginForm = Form { 16 | mapping("email" -> email, "password" -> text)(Account.authenticate)(_.map(u => (u.email, ""))) 17 | .verifying("Invalid email or password", result => result.isDefined) 18 | } 19 | 20 | def login = Action { implicit request => 21 | Ok(html.ephemeral.login(loginForm)) 22 | } 23 | 24 | def logout = Action.async { implicit request => 25 | gotoLogoutSucceeded.map(_.flashing( 26 | "success" -> "You've been logged out" 27 | )) 28 | } 29 | 30 | def authenticate = Action.async { implicit request => 31 | loginForm.bindFromRequest.fold( 32 | formWithErrors => Future.successful(BadRequest(html.ephemeral.login(formWithErrors))), 33 | user => gotoLoginSucceeded(user.get.id) 34 | ) 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/rememberme/AuthConfigImpl.scala: -------------------------------------------------------------------------------- 1 | package controllers.rememberme 2 | 3 | import controllers.BaseAuthConfig 4 | import play.api.mvc.RequestHeader 5 | import play.api.mvc.Results._ 6 | 7 | import scala.concurrent.{Future, ExecutionContext} 8 | 9 | trait AuthConfigImpl extends BaseAuthConfig { 10 | 11 | def loginSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext) = Future.successful(Redirect(routes.Messages.main)) 12 | 13 | def logoutSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext) = Future.successful(Redirect(routes.Sessions.login)) 14 | 15 | def authenticationFailed(request: RequestHeader)(implicit ctx: ExecutionContext) = Future.successful(Redirect(routes.Sessions.login)) 16 | 17 | override lazy val tokenAccessor = new RememberMeTokenAccessor(sessionTimeoutInSeconds) 18 | 19 | } -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/rememberme/Messages.scala: -------------------------------------------------------------------------------- 1 | package controllers.rememberme 2 | 3 | import controllers.stack.Pjax 4 | import jp.t2v.lab.play2.auth.AuthElement 5 | import play.api.mvc.Controller 6 | import views.html 7 | import jp.t2v.lab.play2.auth.sample.Role._ 8 | 9 | trait Messages extends Controller with Pjax with AuthElement with AuthConfigImpl { 10 | 11 | def main = StackAction(AuthorityKey -> NormalUser) { implicit request => 12 | val title = "message main" 13 | Ok(html.message.main(title)) 14 | } 15 | 16 | def list = StackAction(AuthorityKey -> NormalUser) { implicit request => 17 | val title = "all messages" 18 | Ok(html.message.list(title)) 19 | } 20 | 21 | def detail(id: Int) = StackAction(AuthorityKey -> NormalUser) { implicit request => 22 | val title = "messages detail " 23 | Ok(html.message.detail(title + id)) 24 | } 25 | 26 | def write = StackAction(AuthorityKey -> Administrator) { implicit request => 27 | val title = "write message" 28 | Ok(html.message.write(title)) 29 | } 30 | 31 | protected val fullTemplate: User => Template = html.rememberme.fullTemplate.apply 32 | 33 | } 34 | object Messages extends Messages 35 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/rememberme/RememberMeTokenAccessor.scala: -------------------------------------------------------------------------------- 1 | package controllers.rememberme 2 | 3 | import jp.t2v.lab.play2.auth._ 4 | import play.api.mvc.{Cookie, RequestHeader, Result} 5 | 6 | class RememberMeTokenAccessor(maxAge: Int) extends CookieTokenAccessor() { 7 | 8 | override def put(token: AuthenticityToken)(result: Result)(implicit request: RequestHeader): Result = { 9 | val remember = request.tags.get("rememberme").exists("true" ==) || request.session.get("rememberme").exists("true" ==) 10 | val _maxAge = if (remember) Some(maxAge) else None 11 | val c = Cookie(cookieName, sign(token), _maxAge, cookiePathOption, cookieDomainOption, cookieSecureOption, cookieHttpOnlyOption) 12 | result.withCookies(c) 13 | } 14 | 15 | 16 | } 17 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/rememberme/Sessions.scala: -------------------------------------------------------------------------------- 1 | package controllers.rememberme 2 | 3 | import jp.t2v.lab.play2.auth.LoginLogout 4 | import jp.t2v.lab.play2.auth.sample.Account 5 | import play.api.data.Form 6 | import play.api.data.Forms._ 7 | import play.api.mvc.{Action, Controller} 8 | import views.html 9 | 10 | import scala.concurrent.Future 11 | import play.api.libs.concurrent.Execution.Implicits.defaultContext 12 | 13 | object Sessions extends Controller with LoginLogout with AuthConfigImpl { 14 | 15 | val loginForm = Form { 16 | mapping("email" -> email, "password" -> text)(Account.authenticate)(_.map(u => (u.email, ""))) 17 | .verifying("Invalid email or password", result => result.isDefined) 18 | } 19 | val remembermeForm = Form { 20 | "rememberme" -> boolean 21 | } 22 | 23 | def login = Action { implicit request => 24 | Ok(html.rememberme.login(loginForm, remembermeForm.fill(request.session.get("rememberme").exists("true" ==)))) 25 | } 26 | 27 | def logout = Action.async { implicit request => 28 | gotoLogoutSucceeded.map(_.flashing( 29 | "success" -> "You've been logged out" 30 | )) 31 | } 32 | 33 | def authenticate = Action.async { implicit request => 34 | val rememberme = remembermeForm.bindFromRequest() 35 | loginForm.bindFromRequest.fold( 36 | formWithErrors => Future.successful(BadRequest(html.rememberme.login(formWithErrors, rememberme))), 37 | { user => 38 | val req = request.copy(tags = request.tags + ("rememberme" -> rememberme.get.toString)) 39 | gotoLoginSucceeded(user.get.id)(req, defaultContext).map(_.withSession("rememberme" -> rememberme.get.toString)) 40 | } 41 | ) 42 | } 43 | 44 | } -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/stack/Pjax.scala: -------------------------------------------------------------------------------- 1 | package controllers.stack 2 | 3 | import controllers.BaseAuthConfig 4 | import jp.t2v.lab.play2.auth.AuthElement 5 | import jp.t2v.lab.play2.stackc.{RequestAttributeKey, RequestWithAttributes, StackableController} 6 | import play.api.mvc.{Controller, Result} 7 | import play.twirl.api.Html 8 | import views.html 9 | 10 | import scala.concurrent.Future 11 | 12 | trait Pjax extends StackableController with AuthElement { 13 | self: Controller with BaseAuthConfig => 14 | 15 | type Template = String => Html => Html 16 | 17 | case object TemplateKey extends RequestAttributeKey[Template] 18 | 19 | abstract override def proceed[A](req: RequestWithAttributes[A])(f: RequestWithAttributes[A] => Future[Result]): Future[Result] = { 20 | super.proceed(req) { req => 21 | val template: Template = if (req.headers.keys("X-Pjax")) html.pjaxTemplate.apply else fullTemplate(loggedIn(req)) 22 | f(req.set(TemplateKey, template)) 23 | } 24 | } 25 | 26 | implicit def template(implicit req: RequestWithAttributes[_]): Template = req.get(TemplateKey).get 27 | 28 | protected val fullTemplate: User => Template 29 | 30 | } 31 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/stack/TokenValidateElement.scala: -------------------------------------------------------------------------------- 1 | package controllers.stack 2 | 3 | import jp.t2v.lab.play2.stackc.{RequestAttributeKey, RequestWithAttributes, StackableController} 4 | import scala.concurrent.Future 5 | import play.api.mvc.{Result, Request, Controller} 6 | import play.api.data._ 7 | import play.api.data.Forms._ 8 | import scala.util.Random 9 | import java.security.SecureRandom 10 | 11 | trait TokenValidateElement extends StackableController { 12 | self: Controller => 13 | 14 | private val PreventingCsrfTokenSessionKey = "preventingCsrfToken" 15 | 16 | private val tokenForm = Form(PreventingCsrfToken.FormKey -> text) 17 | 18 | private val random = new Random(new SecureRandom) 19 | private val table = ('a' to 'z') ++ ('A' to 'Z') ++ ('0' to '9') ++ "^`~:/?,.{[}}|+_()*^%$#@!" 20 | 21 | private def generateToken: PreventingCsrfToken = PreventingCsrfToken { 22 | Iterator.continually(random.nextInt(table.size)).map(table).take(32).mkString 23 | } 24 | 25 | case object PreventingCsrfTokenKey extends RequestAttributeKey[PreventingCsrfToken] 26 | case object IgnoreTokenValidation extends RequestAttributeKey[Boolean] 27 | 28 | private def validateToken(request: Request[_]): Boolean = (for { 29 | tokenInForm <- tokenForm.bindFromRequest()(request).value 30 | tokenInSession <- request.session.get(PreventingCsrfTokenSessionKey) 31 | } yield tokenInForm == tokenInSession) getOrElse false 32 | 33 | override def proceed[A](request: RequestWithAttributes[A])(f: RequestWithAttributes[A] => Future[Result]): Future[Result] = { 34 | if (isIgnoreTokenValidation(request) || validateToken(request)) { 35 | implicit val ctx = StackActionExecutionContext(request) 36 | val newToken = generateToken 37 | super.proceed(request.set(PreventingCsrfTokenKey, newToken))(f) map { 38 | _.withSession(PreventingCsrfTokenSessionKey -> newToken.value) 39 | } 40 | } else { 41 | Future.successful(BadRequest("Invalid preventing CSRF token")) 42 | } 43 | } 44 | 45 | implicit def isIgnoreTokenValidation(implicit request: RequestWithAttributes[_]): Boolean = 46 | request.get(IgnoreTokenValidation).exists(identity) 47 | 48 | implicit def preventingCsrfToken(implicit request: RequestWithAttributes[_]): PreventingCsrfToken = 49 | request.get(PreventingCsrfTokenKey).get 50 | 51 | 52 | } 53 | 54 | case class PreventingCsrfToken(value: String) 55 | 56 | object PreventingCsrfToken { 57 | 58 | val FormKey = "preventingCsrfToken" 59 | 60 | } 61 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/standard/AuthConfigImpl.scala: -------------------------------------------------------------------------------- 1 | package controllers.standard 2 | 3 | import controllers.BaseAuthConfig 4 | import play.api.mvc.RequestHeader 5 | import play.api.mvc.Results._ 6 | 7 | import scala.concurrent.{Future, ExecutionContext} 8 | 9 | trait AuthConfigImpl extends BaseAuthConfig { 10 | 11 | def loginSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext) = Future.successful(Redirect(routes.Messages.main)) 12 | 13 | def logoutSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext) = Future.successful(Redirect(routes.Sessions.login)) 14 | 15 | def authenticationFailed(request: RequestHeader)(implicit ctx: ExecutionContext) = Future.successful(Redirect(routes.Sessions.login)) 16 | 17 | } -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/standard/Messages.scala: -------------------------------------------------------------------------------- 1 | package controllers.standard 2 | 3 | import com.github.hexx.play.cont.ActionCont 4 | import controllers.cont.MessageCont 5 | import jp.t2v.lab.play2.auth.sample.Role._ 6 | import play.api.mvc.Action 7 | import play.api.mvc.AnyContent 8 | import play.api.mvc.Controller 9 | import play.twirl.api.Html 10 | import scala.concurrent.ExecutionContext 11 | import views.html 12 | 13 | trait Messages extends Controller with MessageCont with AuthConfigImpl { 14 | implicit val ec: ExecutionContext = play.api.libs.concurrent.Execution.defaultContext 15 | 16 | def action(authority: Authority, templateToHtml: Template => Html) 17 | (implicit ec: ExecutionContext): Action[AnyContent] = 18 | ActionCont.run(request => messageCont(authority, html.standard.fullTemplate.apply, templateToHtml)(request, ec)) 19 | 20 | def main = action(NormalUser, html.message.main("message main")(_)) 21 | 22 | def list = action(NormalUser, html.message.list("all messages")(_)) 23 | 24 | def detail(id: Int) = action(NormalUser, html.message.detail("messages detail " + id)(_)) 25 | 26 | def write = action(Administrator, html.message.write("write message")(_)) 27 | } 28 | 29 | object Messages extends Messages 30 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/standard/Sessions.scala: -------------------------------------------------------------------------------- 1 | package controllers.standard 2 | 3 | import jp.t2v.lab.play2.auth.LoginLogout 4 | import jp.t2v.lab.play2.auth.sample.Account 5 | import play.api.data.Form 6 | import play.api.data.Forms._ 7 | import play.api.mvc.{Action, Controller} 8 | import views.html 9 | 10 | import scala.concurrent.Future 11 | import play.api.libs.concurrent.Execution.Implicits.defaultContext 12 | 13 | object Sessions extends Controller with LoginLogout with AuthConfigImpl { 14 | 15 | val loginForm = Form { 16 | mapping("email" -> email, "password" -> text)(Account.authenticate)(_.map(u => (u.email, ""))) 17 | .verifying("Invalid email or password", result => result.isDefined) 18 | } 19 | 20 | def login = Action { implicit request => 21 | Ok(html.standard.login(loginForm)) 22 | } 23 | 24 | def logout = Action.async { implicit request => 25 | gotoLogoutSucceeded.map(_.flashing( 26 | "success" -> "You've been logged out" 27 | ).removingFromSession("rememberme")) 28 | } 29 | 30 | def authenticate = Action.async { implicit request => 31 | loginForm.bindFromRequest.fold( 32 | formWithErrors => Future.successful(BadRequest(html.standard.login(formWithErrors))), 33 | user => gotoLoginSucceeded(user.get.id) 34 | ) 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/stateless/AuthConfigImpl.scala: -------------------------------------------------------------------------------- 1 | package controllers.stateless 2 | 3 | import controllers.BaseAuthConfig 4 | import play.api.mvc.RequestHeader 5 | import play.api.mvc.Results._ 6 | 7 | import scala.concurrent.{Future, ExecutionContext} 8 | import jp.t2v.lab.play2.auth.{CookieIdContainer, AsyncIdContainer} 9 | 10 | trait AuthConfigImpl extends BaseAuthConfig { 11 | 12 | def loginSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext) = Future.successful(Redirect(routes.Messages.main)) 13 | 14 | def logoutSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext) = Future.successful(Redirect(routes.Sessions.login)) 15 | 16 | def authenticationFailed(request: RequestHeader)(implicit ctx: ExecutionContext) = Future.successful(Redirect(routes.Sessions.login)) 17 | 18 | override lazy val idContainer = AsyncIdContainer(new CookieIdContainer[Id]) 19 | 20 | } -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/stateless/Messages.scala: -------------------------------------------------------------------------------- 1 | package controllers.stateless 2 | 3 | import controllers.stack.Pjax 4 | import jp.t2v.lab.play2.auth.AuthElement 5 | import play.api.mvc.Controller 6 | import views.html 7 | import jp.t2v.lab.play2.auth.sample.Role._ 8 | 9 | trait Messages extends Controller with Pjax with AuthElement with AuthConfigImpl { 10 | 11 | def main = StackAction(AuthorityKey -> NormalUser) { implicit request => 12 | val title = "message main" 13 | Ok(html.message.main(title)) 14 | } 15 | 16 | def list = StackAction(AuthorityKey -> NormalUser) { implicit request => 17 | val title = "all messages" 18 | Ok(html.message.list(title)) 19 | } 20 | 21 | def detail(id: Int) = StackAction(AuthorityKey -> NormalUser) { implicit request => 22 | val title = "messages detail " 23 | Ok(html.message.detail(title + id)) 24 | } 25 | 26 | def write = StackAction(AuthorityKey -> Administrator) { implicit request => 27 | val title = "write message" 28 | Ok(html.message.write(title)) 29 | } 30 | 31 | protected val fullTemplate: User => Template = html.stateless.fullTemplate.apply 32 | 33 | } 34 | object Messages extends Messages 35 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/controllers/stateless/Sessions.scala: -------------------------------------------------------------------------------- 1 | package controllers.stateless 2 | 3 | import jp.t2v.lab.play2.auth.LoginLogout 4 | import jp.t2v.lab.play2.auth.sample.Account 5 | import play.api.data.Form 6 | import play.api.data.Forms._ 7 | import play.api.mvc.{Action, Controller} 8 | import views.html 9 | 10 | import scala.concurrent.Future 11 | import play.api.libs.concurrent.Execution.Implicits.defaultContext 12 | 13 | object Sessions extends Controller with LoginLogout with AuthConfigImpl { 14 | 15 | val loginForm = Form { 16 | mapping("email" -> email, "password" -> text)(Account.authenticate)(_.map(u => (u.email, ""))) 17 | .verifying("Invalid email or password", result => result.isDefined) 18 | } 19 | 20 | def login = Action { implicit request => 21 | Ok(html.stateless.login(loginForm)) 22 | } 23 | 24 | def logout = Action.async { implicit request => 25 | gotoLogoutSucceeded.map(_.flashing( 26 | "success" -> "You've been logged out" 27 | )) 28 | } 29 | 30 | def authenticate = Action.async { implicit request => 31 | loginForm.bindFromRequest.fold( 32 | formWithErrors => Future.successful(BadRequest(html.stateless.login(formWithErrors))), 33 | user => gotoLoginSucceeded(user.get.id) 34 | ) 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/jp/t2v/lab/play2/auth/sample/Account.scala: -------------------------------------------------------------------------------- 1 | package jp.t2v.lab.play2.auth.sample 2 | 3 | import org.mindrot.jbcrypt.BCrypt 4 | import scalikejdbc._ 5 | 6 | case class Account(id: Int, email: String, password: String, name: String, role: Role) 7 | 8 | object Account extends SQLSyntaxSupport[Account] { 9 | 10 | private val a = syntax("a") 11 | 12 | def apply(a: SyntaxProvider[Account])(rs: WrappedResultSet): Account = autoConstruct(rs, a) 13 | 14 | private val auto = AutoSession 15 | 16 | def authenticate(email: String, password: String)(implicit s: DBSession = auto): Option[Account] = { 17 | findByEmail(email).filter { account => BCrypt.checkpw(password, account.password) } 18 | } 19 | 20 | def findByEmail(email: String)(implicit s: DBSession = auto): Option[Account] = withSQL { 21 | select.from(Account as a).where.eq(a.email, email) 22 | }.map(Account(a)).single.apply() 23 | 24 | def findById(id: Int)(implicit s: DBSession = auto): Option[Account] = withSQL { 25 | select.from(Account as a).where.eq(a.id, id) 26 | }.map(Account(a)).single.apply() 27 | 28 | def findAll()(implicit s: DBSession = auto): Seq[Account] = withSQL { 29 | select.from(Account as a) 30 | }.map(Account(a)).list.apply() 31 | 32 | def create(account: Account)(implicit s: DBSession = auto) { 33 | withSQL { 34 | import account._ 35 | val pass = BCrypt.hashpw(account.password, BCrypt.gensalt()) 36 | insert.into(Account).values(id, email, pass, name, role.toString) 37 | }.update.apply() 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/jp/t2v/lab/play2/auth/sample/Role.scala: -------------------------------------------------------------------------------- 1 | package jp.t2v.lab.play2.auth.sample 2 | 3 | import scalikejdbc.TypeBinder 4 | 5 | sealed trait Role 6 | 7 | object Role { 8 | 9 | case object Administrator extends Role 10 | case object NormalUser extends Role 11 | 12 | def valueOf(value: String): Role = value match { 13 | case "Administrator" => Administrator 14 | case "NormalUser" => NormalUser 15 | case _ => throw new IllegalArgumentException() 16 | } 17 | 18 | implicit val typeBinder: TypeBinder[Role] = TypeBinder.string.map(valueOf) 19 | 20 | } 21 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/views/basic/fullTemplate.scala.html: -------------------------------------------------------------------------------- 1 | @(account: Account)(title: String)(content: Html) 2 | 3 | 4 | 5 | 6 | 7 | @title 8 | 9 | 10 | 11 | 12 | 13 | 14 | Logged-in 15 | 16 | @content 17 | 18 | 19 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/views/builder/fullTemplate.scala.html: -------------------------------------------------------------------------------- 1 | @(account: Account)(title: String)(content: Html) 2 | 3 | 4 | 5 | 6 | 7 | @title 8 | 9 | 10 | 11 | 12 | 13 | 14 | logout 15 | 16 | @content 17 | 18 | 19 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/views/builder/login.scala.html: -------------------------------------------------------------------------------- 1 | @(form: Form[Option[Account]])(implicit flash: Flash) 2 | 3 | 4 | 5 | 6 | Login 7 | 8 | 9 | 10 | 11 | 12 | 13 | @helper.form(controllers.builder.routes.Sessions.authenticate) { 14 | 15 |

Sign in

16 | 17 | @form.globalError.map { error => 18 |

19 | @error.message 20 |

21 | } 22 | 23 | @flash.get("success").map { message => 24 |

25 | @message 26 |

27 | } 28 | 29 |

30 | 31 |

32 |

33 | 34 |

35 |

36 | 37 |

38 | 39 | } 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/views/csrf/formWithToken.scala.html: -------------------------------------------------------------------------------- 1 | @()(implicit account: Account, token: stack.PreventingCsrfToken) 2 | 3 | @fullTemplate(account)("with Token") { 4 | 5 | @helper.form(action = controllers.csrf.routes.PreventingCsrfSample.submitTarget()) { 6 | 7 |

With Token

8 | 9 | 10 | 11 | } 12 | 13 | } 14 | 15 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/views/csrf/formWithoutToken.scala.html: -------------------------------------------------------------------------------- 1 | @()(implicit account: Account) 2 | 3 | @fullTemplate(account)("with Token") { 4 | 5 | @helper.form(action = controllers.csrf.routes.PreventingCsrfSample.submitTarget()) { 6 | 7 |

Without Token

8 | 9 | 10 | } 11 | 12 | } 13 | 14 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/views/csrf/fullTemplate.scala.html: -------------------------------------------------------------------------------- 1 | @(account: Account)(title: String)(content: Html) 2 | 3 | 4 | 5 | 6 | 7 | @title 8 | 9 | 10 | 11 | 12 | 13 | 14 | logout 15 | 16 | @content 17 | 18 | 19 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/views/csrf/login.scala.html: -------------------------------------------------------------------------------- 1 | @(form: Form[Option[Account]])(implicit flash: Flash) 2 | 3 | 4 | 5 | 6 | Login 7 | 8 | 9 | 10 | 11 | 12 | 13 | @helper.form(controllers.csrf.routes.Sessions.authenticate) { 14 | 15 |

Sign in

16 | 17 | @form.globalError.map { error => 18 |

19 | @error.message 20 |

21 | } 22 | 23 | @flash.get("success").map { message => 24 |

25 | @message 26 |

27 | } 28 | 29 |

30 | 31 |

32 |

33 | 34 |

35 |

36 | 37 |

38 | 39 | } 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/views/ephemeral/fullTemplate.scala.html: -------------------------------------------------------------------------------- 1 | @(account: Account)(title: String)(content: Html) 2 | 3 | 4 | 5 | 6 | 7 | @title 8 | 9 | 10 | 11 | 12 | 13 | 14 | logout 15 | 16 | @content 17 | 18 | 19 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/views/ephemeral/login.scala.html: -------------------------------------------------------------------------------- 1 | @(form: Form[Option[Account]])(implicit flash: Flash) 2 | 3 | 4 | 5 | 6 | Login 7 | 8 | 9 | 10 | 11 | 12 | 13 | @helper.form(controllers.ephemeral.routes.Sessions.authenticate) { 14 | 15 |

Sign in

16 | 17 | @form.globalError.map { error => 18 |

19 | @error.message 20 |

21 | } 22 | 23 | @flash.get("success").map { message => 24 |

25 | @message 26 |

27 | } 28 | 29 |

30 | 31 |

32 |

33 | 34 |

35 |

36 | 37 |

38 | 39 | } 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/views/message/detail.scala.html: -------------------------------------------------------------------------------- 1 | @(title: String)(implicit template: String => Html => Html) 2 | 3 | @template(title) { 4 | 5 | detail 6 | 7 | } 8 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/views/message/list.scala.html: -------------------------------------------------------------------------------- 1 | @(title: String)(implicit template: String => Html => Html) 2 | 3 | @template(title) { 4 | 5 | list 6 | 7 | } 8 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/views/message/main.scala.html: -------------------------------------------------------------------------------- 1 | @(title: String)(implicit template: String => Html => Html) 2 | 3 | @template(title) { 4 | 5 | main 6 | 7 | } 8 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/views/message/write.scala.html: -------------------------------------------------------------------------------- 1 | @(title: String)(implicit template: String => Html => Html) 2 | 3 | @template(title) { 4 | 5 | write 6 | 7 | } 8 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/views/pjaxTemplate.scala.html: -------------------------------------------------------------------------------- 1 | @(title: String)(content: Html) 2 | 3 | @title 4 | 5 | @content -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/views/rememberme/fullTemplate.scala.html: -------------------------------------------------------------------------------- 1 | @(account: Account)(title: String)(content: Html) 2 | 3 | 4 | 5 | 6 | 7 | @title 8 | 9 | 10 | 11 | 12 | 13 | 14 | logout 15 | 16 | @content 17 | 18 | 19 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/views/rememberme/login.scala.html: -------------------------------------------------------------------------------- 1 | @(form: Form[Option[Account]], rememberme: Form[Boolean])(implicit flash: Flash) 2 | 3 | 4 | 5 | 6 | Login 7 | 8 | 9 | 10 | 11 | 12 | 13 | @helper.form(controllers.rememberme.routes.Sessions.authenticate) { 14 | 15 |

Sign in

16 | 17 | @form.globalError.map { error => 18 |

19 | @error.message 20 |

21 | } 22 | 23 | @flash.get("success").map { message => 24 |

25 | @message 26 |

27 | } 28 | 29 |

30 | 31 |

32 |

33 | 34 |

35 |

36 | 37 |

38 |

39 | 40 |

41 | 42 | } 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/views/standard/fullTemplate.scala.html: -------------------------------------------------------------------------------- 1 | @(account: Account)(title: String)(content: Html) 2 | 3 | 4 | 5 | 6 | 7 | @title 8 | 9 | 10 | 11 | 12 | 13 | 14 | logout 15 | 16 | @content 17 | 18 | 19 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/views/standard/login.scala.html: -------------------------------------------------------------------------------- 1 | @(form: Form[Option[Account]])(implicit flash: Flash) 2 | 3 | 4 | 5 | 6 | Login 7 | 8 | 9 | 10 | 11 | 12 | 13 | @helper.form(controllers.standard.routes.Sessions.authenticate) { 14 | 15 |

Sign in

16 | 17 | @form.globalError.map { error => 18 |

19 | @error.message 20 |

21 | } 22 | 23 | @flash.get("success").map { message => 24 |

25 | @message 26 |

27 | } 28 | 29 |

30 | 31 |

32 |

33 | 34 |

35 |

36 | 37 |

38 | 39 | } 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/views/stateless/fullTemplate.scala.html: -------------------------------------------------------------------------------- 1 | @(account: Account)(title: String)(content: Html) 2 | 3 | 4 | 5 | 6 | 7 | @title 8 | 9 | 10 | 11 | 12 | 13 | 14 | logout 15 | 16 | @content 17 | 18 | 19 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/app/views/stateless/login.scala.html: -------------------------------------------------------------------------------- 1 | @(form: Form[Option[Account]])(implicit flash: Flash) 2 | 3 | 4 | 5 | 6 | Login 7 | 8 | 9 | 10 | 11 | 12 | 13 | @helper.form(controllers.stateless.routes.Sessions.authenticate) { 14 | 15 |

Sign in

16 | 17 | @form.globalError.map { error => 18 |

19 | @error.message 20 |

21 | } 22 | 23 | @flash.get("success").map { message => 24 |

25 | @message 26 |

27 | } 28 | 29 |

30 | 31 |

32 |

33 | 34 |

35 |

36 | 37 |

38 | 39 | } 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/conf/application.conf: -------------------------------------------------------------------------------- 1 | # This is the main configuration file for the application. 2 | # ~~~~~ 3 | 4 | # Secret key 5 | # ~~~~~ 6 | # The secret key is used to secure cryptographics functions. 7 | # If you deploy your application to several instances be sure to use the same key! 8 | application.secret="79V2@SMp]7wuJo0weB7b4PUIk41OmsFwivxL01S?JyEluwPvB]bs/GLR5_O0;sor" 9 | 10 | # The application languages 11 | # ~~~~~ 12 | application.langs="ja" 13 | 14 | # Global object class 15 | # ~~~~~ 16 | # Define the Global object class for this application. 17 | # Default to Global in the root package. 18 | # global=Global 19 | 20 | # Database configuration 21 | # ~~~~~ 22 | # You can declare as many datasources as you want. 23 | # By convention, the default datasource is named `default` 24 | # 25 | db.default.driver=org.h2.Driver 26 | db.default.url="jdbc:h2:mem:play;DB_CLOSE_DELAY=-1" 27 | db.default.user=sa 28 | db.default.password="" 29 | 30 | # Connection Pool settings 31 | db.default.poolInitialSize=10 32 | db.default.poolMaxSize=20 33 | db.default.connectionTimeoutMillis=1000 34 | 35 | # Evolutions 36 | # ~~~~~ 37 | # You can disable evolutions if needed 38 | dbplugin=disabled 39 | evolutionplugin=disabled 40 | 41 | # Logger 42 | # ~~~~~ 43 | # You can also configure logback (http://logback.qos.ch/), by providing a logger.xml file in the conf directory . 44 | 45 | # Root logger: 46 | logger.root=ERROR 47 | 48 | # Logger used by the framework: 49 | logger.play=INFO 50 | 51 | # Logger provided to your application: 52 | logger.application=DEBUG 53 | 54 | scalikejdbc.global.loggingSQLAndTime.enabled=true 55 | scalikejdbc.global.loggingSQLAndTime.logLevel=debug 56 | scalikejdbc.global.loggingSQLAndTime.warningEnabled=true 57 | scalikejdbc.global.loggingSQLAndTime.warningThresholdMillis=1000 58 | scalikejdbc.global.loggingSQLAndTime.warningLogLevel=warn 59 | 60 | #dbplugin=disabled 61 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/conf/db/migration/default/V1__create_tables.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE account ( 2 | id integer NOT NULL PRIMARY KEY, 3 | email varchar NOT NULL UNIQUE, 4 | password varchar NOT NULL, 5 | name varchar NOT NULL, 6 | role varchar NOT NULL 7 | ); 8 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/conf/play.plugins: -------------------------------------------------------------------------------- 1 | 666:com.github.tototoshi.play2.flyway.Plugin 2 | 9999:scalikejdbc.PlayPlugin -------------------------------------------------------------------------------- /play2-auth-cont-sample/conf/routes: -------------------------------------------------------------------------------- 1 | # Routes 2 | # This file defines all application routes (Higher priority routes first) 3 | # ~~~~ 4 | 5 | # Standard 6 | GET / controllers.standard.Sessions.login 7 | POST /standard/login controllers.standard.Sessions.authenticate 8 | GET /standard/logout controllers.standard.Sessions.logout 9 | 10 | GET /standard/messages/main controllers.standard.Messages.main 11 | GET /standard/messages/list controllers.standard.Messages.list 12 | GET /standard/messages/detail/:id controllers.standard.Messages.detail(id: Int) 13 | GET /standard/messages/write controllers.standard.Messages.write 14 | 15 | # Builder 16 | GET /builder/ controllers.builder.Sessions.login 17 | POST /builder/login controllers.builder.Sessions.authenticate 18 | GET /builder/logout controllers.builder.Sessions.logout 19 | 20 | GET /builder/messages/main controllers.builder.Messages.main 21 | GET /builder/messages/list controllers.builder.Messages.list 22 | GET /builder/messages/detail/:id controllers.builder.Messages.detail(id: Int) 23 | GET /builder/messages/write controllers.builder.Messages.write 24 | 25 | # Csrf 26 | GET /csrf/ controllers.csrf.Sessions.login 27 | POST /csrf/login controllers.csrf.Sessions.authenticate 28 | GET /csrf/logout controllers.csrf.Sessions.logout 29 | 30 | GET /csrf/with_token controllers.csrf.PreventingCsrfSample.formWithToken 31 | GET /csrf/without_token controllers.csrf.PreventingCsrfSample.formWithoutToken 32 | POST /csrf/ controllers.csrf.PreventingCsrfSample.submitTarget 33 | 34 | 35 | # Ephemeral 36 | GET /ephemeral/ controllers.ephemeral.Sessions.login 37 | POST /ephemeral/login controllers.ephemeral.Sessions.authenticate 38 | GET /ephemeral/logout controllers.ephemeral.Sessions.logout 39 | 40 | GET /ephemeral/messages/main controllers.ephemeral.Messages.main 41 | GET /ephemeral/messages/list controllers.ephemeral.Messages.list 42 | GET /ephemeral/messages/detail/:id controllers.ephemeral.Messages.detail(id: Int) 43 | GET /ephemeral/messages/write controllers.ephemeral.Messages.write 44 | 45 | # Stateless 46 | GET /stateless/ controllers.stateless.Sessions.login 47 | POST /stateless/login controllers.stateless.Sessions.authenticate 48 | GET /stateless/logout controllers.stateless.Sessions.logout 49 | 50 | GET /stateless/messages/main controllers.stateless.Messages.main 51 | GET /stateless/messages/list controllers.stateless.Messages.list 52 | GET /stateless/messages/detail/:id controllers.stateless.Messages.detail(id: Int) 53 | GET /stateless/messages/write controllers.stateless.Messages.write 54 | 55 | 56 | # HTTP Basic Auth 57 | GET /basic/ controllers.Default.redirect(to = "/basic/messages/main") 58 | GET /basic/messages/main controllers.basic.Messages.main 59 | GET /basic/messages/list controllers.basic.Messages.list 60 | GET /basic/messages/detail/:id controllers.basic.Messages.detail(id: Int) 61 | GET /basic/messages/write controllers.basic.Messages.write 62 | 63 | 64 | # Remember Me 65 | GET /rememberme/ controllers.rememberme.Sessions.login 66 | POST /rememberme/login controllers.rememberme.Sessions.authenticate 67 | GET /rememberme/logout controllers.rememberme.Sessions.logout 68 | 69 | GET /rememberme/messages/main controllers.rememberme.Messages.main 70 | GET /rememberme/messages/list controllers.rememberme.Messages.list 71 | GET /rememberme/messages/detail/:id controllers.rememberme.Messages.detail(id: Int) 72 | GET /rememberme/messages/write controllers.rememberme.Messages.write 73 | 74 | 75 | # Map static resources from the /public folder to the /assets URL path 76 | GET /assets/*file controllers.Assets.at(path="/public", file) 77 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/public/images/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hexx/action-cont/a75d2fac64f5fbfc111a686a2fea5b8aab673905/play2-auth-cont-sample/public/images/favicon.png -------------------------------------------------------------------------------- /play2-auth-cont-sample/public/javascripts/jquery-1.7.1.min.js: -------------------------------------------------------------------------------- 1 | /*! jQuery v1.7.1 jquery.com | jquery.org/license */ 2 | (function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cv(a){if(!ck[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cl||(cl=c.createElement("iframe"),cl.frameBorder=cl.width=cl.height=0),b.appendChild(cl);if(!cm||!cl.createElement)cm=(cl.contentWindow||cl.contentDocument).document,cm.write((c.compatMode==="CSS1Compat"?"":"")+""),cm.close();d=cm.createElement(a),cm.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cl)}ck[a]=e}return ck[a]}function cu(a,b){var c={};f.each(cq.concat.apply([],cq.slice(0,b)),function(){c[this]=a});return c}function ct(){cr=b}function cs(){setTimeout(ct,0);return cr=f.now()}function cj(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ci(){try{return new a.XMLHttpRequest}catch(b){}}function cc(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g0){if(c!=="border")for(;g=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.1",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c
a",d=q.getElementsByTagName("*"),e=q.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=q.getElementsByTagName("input")[0],b={leadingWhitespace:q.firstChild.nodeType===3,tbody:!q.getElementsByTagName("tbody").length,htmlSerialize:!!q.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:q.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete q.test}catch(s){b.deleteExpando=!1}!q.addEventListener&&q.attachEvent&&q.fireEvent&&(q.attachEvent("onclick",function(){b.noCloneEvent=!1}),q.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),q.appendChild(i),k=c.createDocumentFragment(),k.appendChild(q.lastChild),b.checkClone=k.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,k.removeChild(i),k.appendChild(q),q.innerHTML="",a.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",q.style.width="2px",q.appendChild(j),b.reliableMarginRight=(parseInt((a.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(q.attachEvent)for(o in{submit:1,change:1,focusin:1})n="on"+o,p=n in q,p||(q.setAttribute(n,"return;"),p=typeof q[n]=="function"),b[o+"Bubbles"]=p;k.removeChild(q),k=g=h=j=q=i=null,f(function(){var a,d,e,g,h,i,j,k,m,n,o,r=c.getElementsByTagName("body")[0];!r||(j=1,k="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",m="visibility:hidden;border:0;",n="style='"+k+"border:5px solid #000;padding:0;'",o="
"+""+"
",a=c.createElement("div"),a.style.cssText=m+"width:0;height:0;position:static;top:0;margin-top:"+j+"px",r.insertBefore(a,r.firstChild),q=c.createElement("div"),a.appendChild(q),q.innerHTML="
t
",l=q.getElementsByTagName("td"),p=l[0].offsetHeight===0,l[0].style.display="",l[1].style.display="none",b.reliableHiddenOffsets=p&&l[0].offsetHeight===0,q.innerHTML="",q.style.width=q.style.paddingLeft="1px",f.boxModel=b.boxModel=q.offsetWidth===2,typeof q.style.zoom!="undefined"&&(q.style.display="inline",q.style.zoom=1,b.inlineBlockNeedsLayout=q.offsetWidth===2,q.style.display="",q.innerHTML="
",b.shrinkWrapBlocks=q.offsetWidth!==2),q.style.cssText=k+m,q.innerHTML=o,d=q.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,i={doesNotAddBorder:e.offsetTop!==5,doesAddBorderForTableAndCells:h.offsetTop===5},e.style.position="fixed",e.style.top="20px",i.fixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",i.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,i.doesNotIncludeMarginInBodyOffset=r.offsetTop!==j,r.removeChild(a),q=a=null,f.extend(b,i))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;h=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/\bhover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function(a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")}; 3 | f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;le&&i.push({elem:this,matches:d.slice(e)});for(j=0;j0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return bc[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="

";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="
";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h0)for(h=g;h=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/",""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div
","
"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function() 4 | {for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1>");try{for(var c=0,d=this.length;c1&&l0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||!bc.test("<"+a.nodeName)?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!_.test(k))k=b.createTextNode(k);else{k=k.replace(Y,"<$1>");var l=(Z.exec(k)||["",""])[1].toLowerCase(),m=bg[l]||bg._default,n=m[0],o=b.createElement("div");b===c?bh.appendChild(o):U(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=$.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]===""&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&X.test(k)&&o.insertBefore(b.createTextNode(X.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return br.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bq,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bq.test(g)?g.replace(bq,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bz(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bA=function(a,b){var c,d,e;b=b.replace(bs,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b)));return c}),c.documentElement.currentStyle&&(bB=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bt.test(f)&&bu.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bz=bA||bB,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bD=/%20/g,bE=/\[\]$/,bF=/\r?\n/g,bG=/#.*$/,bH=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bI=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bJ=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bK=/^(?:GET|HEAD)$/,bL=/^\/\//,bM=/\?/,bN=/)<[^<]*)*<\/script>/gi,bO=/^(?:select|textarea)/i,bP=/\s+/,bQ=/([?&])_=[^&]*/,bR=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bS=f.fn.load,bT={},bU={},bV,bW,bX=["*/"]+["*"];try{bV=e.href}catch(bY){bV=c.createElement("a"),bV.href="",bV=bV.href}bW=bR.exec(bV.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bS)return bS.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("
").append(c.replace(bN,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bO.test(this.nodeName)||bI.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bF,"\r\n")}}):{name:b.name,value:c.replace(bF,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b_(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b_(a,b);return a},ajaxSettings:{url:bV,isLocal:bJ.test(bW[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bX},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bZ(bT),ajaxTransport:bZ(bU),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cb(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cc(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bH.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bG,"").replace(bL,bW[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bP),d.crossDomain==null&&(r=bR.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bW[1]&&r[2]==bW[2]&&(r[3]||(r[1]==="http:"?80:443))==(bW[3]||(bW[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),b$(bT,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bK.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bM.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bQ,"$1_="+x);d.url=y+(y===d.url?(bM.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bX+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=b$(bU,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)ca(g,a[g],c,e);return d.join("&").replace(bD,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cd=f.now(),ce=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cd++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(ce.test(b.url)||e&&ce.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(ce,l),b.url===j&&(e&&(k=k.replace(ce,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var cf=a.ActiveXObject?function(){for(var a in ch)ch[a](0,1)}:!1,cg=0,ch;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ci()||cj()}:ci,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,cf&&delete ch[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cg,cf&&(ch||(ch={},f(a).unload(cf)),ch[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var ck={},cl,cm,cn=/^(?:toggle|show|hide)$/,co=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cp,cq=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cr;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cu("show",3),a,b,c);for(var g=0,h=this.length;g=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cy(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cy(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window); -------------------------------------------------------------------------------- /play2-auth-cont-sample/public/javascripts/jquery.pjax.js: -------------------------------------------------------------------------------- 1 | // jquery.pjax.js 2 | // copyright chris wanstrath 3 | // https://github.com/defunkt/jquery-pjax 4 | 5 | (function($){ 6 | 7 | // When called on a link, fetches the href with ajax into the 8 | // container specified as the first parameter or with the data-pjax 9 | // attribute on the link itself. 10 | // 11 | // Tries to make sure the back button and ctrl+click work the way 12 | // you'd expect. 13 | // 14 | // Accepts a jQuery ajax options object that may include these 15 | // pjax specific options: 16 | // 17 | // container - Where to stick the response body. Usually a String selector. 18 | // $(container).html(xhr.responseBody) 19 | // push - Whether to pushState the URL. Defaults to true (of course). 20 | // replace - Want to use replaceState instead? That's cool. 21 | // 22 | // For convenience the first parameter can be either the container or 23 | // the options object. 24 | // 25 | // Returns the jQuery object 26 | $.fn.pjax = function( container, options ) { 27 | return this.live('click.pjax', function(event){ 28 | handleClick(event, container, options) 29 | }) 30 | } 31 | 32 | // Public: pjax on click handler 33 | // 34 | // Exported as $.pjax.click. 35 | // 36 | // event - "click" jQuery.Event 37 | // options - pjax options 38 | // 39 | // Examples 40 | // 41 | // $('a').live('click', $.pjax.click) 42 | // // is the same as 43 | // $('a').pjax() 44 | // 45 | // $(document).on('click', 'a', function(event) { 46 | // var container = $(this).closest('[data-pjax-container]') 47 | // return $.pjax.click(event, container) 48 | // }) 49 | // 50 | // Returns false if pjax runs, otherwise nothing. 51 | function handleClick(event, container, options) { 52 | options = optionsFor(container, options) 53 | 54 | var link = event.currentTarget 55 | 56 | // If current target isnt a link, try to find the first A descendant 57 | if (link.tagName.toUpperCase() !== 'A') 58 | link = $(link).find('a')[0] 59 | 60 | if (!link) 61 | throw "$.fn.pjax or $.pjax.click requires an anchor element" 62 | 63 | // Middle click, cmd click, and ctrl click should open 64 | // links in a new tab as normal. 65 | if ( event.which > 1 || event.metaKey ) 66 | return 67 | 68 | // Ignore cross origin links 69 | if ( location.protocol !== link.protocol || location.host !== link.host ) 70 | return 71 | 72 | // Ignore anchors on the same page 73 | if ( link.hash && link.href.replace(link.hash, '') === 74 | location.href.replace(location.hash, '') ) 75 | return 76 | 77 | var defaults = { 78 | url: link.href, 79 | container: $(link).attr('data-pjax'), 80 | target: link, 81 | clickedElement: $(link), // DEPRECATED: use target 82 | fragment: null 83 | } 84 | 85 | $.pjax($.extend({}, defaults, options)) 86 | 87 | event.preventDefault() 88 | } 89 | 90 | 91 | // Loads a URL with ajax, puts the response body inside a container, 92 | // then pushState()'s the loaded URL. 93 | // 94 | // Works just like $.ajax in that it accepts a jQuery ajax 95 | // settings object (with keys like url, type, data, etc). 96 | // 97 | // Accepts these extra keys: 98 | // 99 | // container - Where to stick the response body. 100 | // $(container).html(xhr.responseBody) 101 | // push - Whether to pushState the URL. Defaults to true (of course). 102 | // replace - Want to use replaceState instead? That's cool. 103 | // 104 | // Use it just like $.ajax: 105 | // 106 | // var xhr = $.pjax({ url: this.href, container: '#main' }) 107 | // console.log( xhr.readyState ) 108 | // 109 | // Returns whatever $.ajax returns. 110 | var pjax = $.pjax = function( options ) { 111 | options = $.extend(true, {}, $.ajaxSettings, pjax.defaults, options) 112 | 113 | if ($.isFunction(options.url)) { 114 | options.url = options.url() 115 | } 116 | 117 | var target = options.target 118 | 119 | // DEPRECATED: use options.target 120 | if (!target && options.clickedElement) target = options.clickedElement[0] 121 | 122 | var hash = parseURL(options.url).hash 123 | 124 | // DEPRECATED: Save references to original event callbacks. However, 125 | // listening for custom pjax:* events is prefered. 126 | var oldBeforeSend = options.beforeSend, 127 | oldComplete = options.complete, 128 | oldSuccess = options.success, 129 | oldError = options.error 130 | 131 | var context = options.context = findContainerFor(options.container) 132 | 133 | // We want the browser to maintain two separate internal caches: one 134 | // for pjax'd partial page loads and one for normal page loads. 135 | // Without adding this secret parameter, some browsers will often 136 | // confuse the two. 137 | if (!options.data) options.data = {} 138 | options.data._pjax = context.selector 139 | 140 | function fire(type, args) { 141 | var event = $.Event(type, { relatedTarget: target }) 142 | context.trigger(event, args) 143 | return !event.isDefaultPrevented() 144 | } 145 | 146 | var timeoutTimer 147 | 148 | options.beforeSend = function(xhr, settings) { 149 | if (settings.timeout > 0) { 150 | timeoutTimer = setTimeout(function() { 151 | if (fire('pjax:timeout', [xhr, options])) 152 | xhr.abort('timeout') 153 | }, settings.timeout) 154 | 155 | // Clear timeout setting so jquerys internal timeout isn't invoked 156 | settings.timeout = 0 157 | } 158 | 159 | xhr.setRequestHeader('X-PJAX', 'true') 160 | xhr.setRequestHeader('X-PJAX-Container', context.selector) 161 | 162 | var result 163 | 164 | // DEPRECATED: Invoke original `beforeSend` handler 165 | if (oldBeforeSend) { 166 | result = oldBeforeSend.apply(this, arguments) 167 | if (result === false) return false 168 | } 169 | 170 | if (!fire('pjax:beforeSend', [xhr, settings])) return false 171 | 172 | if (options.push && !options.replace) { 173 | // Cache current container element before replacing it 174 | containerCache.push(pjax.state.id, context.clone(true, true).contents()) 175 | 176 | window.history.pushState(null, "", options.url) 177 | } 178 | 179 | fire('pjax:start', [xhr, options]) 180 | // start.pjax is deprecated 181 | fire('start.pjax', [xhr, options]) 182 | 183 | fire('pjax:send', [xhr, settings]) 184 | } 185 | 186 | options.complete = function(xhr, textStatus) { 187 | if (timeoutTimer) 188 | clearTimeout(timeoutTimer) 189 | 190 | // DEPRECATED: Invoke original `complete` handler 191 | if (oldComplete) oldComplete.apply(this, arguments) 192 | 193 | fire('pjax:complete', [xhr, textStatus, options]) 194 | 195 | fire('pjax:end', [xhr, options]) 196 | // end.pjax is deprecated 197 | fire('end.pjax', [xhr, options]) 198 | } 199 | 200 | options.error = function(xhr, textStatus, errorThrown) { 201 | var container = extractContainer("", xhr, options) 202 | 203 | // DEPRECATED: Invoke original `error` handler 204 | if (oldError) oldError.apply(this, arguments) 205 | 206 | var allowed = fire('pjax:error', [xhr, textStatus, errorThrown, options]) 207 | if (textStatus !== 'abort' && allowed) 208 | window.location = container.url 209 | } 210 | 211 | options.success = function(data, status, xhr) { 212 | var container = extractContainer(data, xhr, options) 213 | 214 | if (!container.contents) { 215 | window.location = container.url 216 | return 217 | } 218 | 219 | pjax.state = { 220 | id: options.id || uniqueId(), 221 | url: container.url, 222 | container: context.selector, 223 | fragment: options.fragment, 224 | timeout: options.timeout 225 | } 226 | 227 | if (options.push || options.replace) { 228 | window.history.replaceState(pjax.state, container.title, container.url) 229 | } 230 | 231 | if (container.title) document.title = container.title 232 | context.html(container.contents) 233 | 234 | // Scroll to top by default 235 | if (typeof options.scrollTo === 'number') 236 | $(window).scrollTop(options.scrollTo) 237 | 238 | // Google Analytics support 239 | if ( (options.replace || options.push) && window._gaq ) 240 | _gaq.push(['_trackPageview']) 241 | 242 | // If the URL has a hash in it, make sure the browser 243 | // knows to navigate to the hash. 244 | if ( hash !== '' ) { 245 | window.location.href = hash 246 | } 247 | 248 | // DEPRECATED: Invoke original `success` handler 249 | if (oldSuccess) oldSuccess.apply(this, arguments) 250 | 251 | fire('pjax:success', [data, status, xhr, options]) 252 | } 253 | 254 | 255 | // Initialize pjax.state for the initial page load. Assume we're 256 | // using the container and options of the link we're loading for the 257 | // back button to the initial page. This ensures good back button 258 | // behavior. 259 | if (!pjax.state) { 260 | pjax.state = { 261 | id: uniqueId(), 262 | url: window.location.href, 263 | container: context.selector, 264 | fragment: options.fragment, 265 | timeout: options.timeout 266 | } 267 | window.history.replaceState(pjax.state, document.title) 268 | } 269 | 270 | // Cancel the current request if we're already pjaxing 271 | var xhr = pjax.xhr 272 | if ( xhr && xhr.readyState < 4) { 273 | xhr.onreadystatechange = $.noop 274 | xhr.abort() 275 | } 276 | 277 | pjax.options = options 278 | pjax.xhr = $.ajax(options) 279 | 280 | // pjax event is deprecated 281 | $(document).trigger('pjax', [pjax.xhr, options]) 282 | 283 | return pjax.xhr 284 | } 285 | 286 | 287 | // Internal: Generate unique id for state object. 288 | // 289 | // Use a timestamp instead of a counter since ids should still be 290 | // unique across page loads. 291 | // 292 | // Returns Number. 293 | function uniqueId() { 294 | return (new Date).getTime() 295 | } 296 | 297 | // Internal: Strips _pjax param from url 298 | // 299 | // url - String 300 | // 301 | // Returns String. 302 | function stripPjaxParam(url) { 303 | return url 304 | .replace(/\?_pjax=[^&]+&?/, '?') 305 | .replace(/_pjax=[^&]+&?/, '') 306 | .replace(/[\?&]$/, '') 307 | } 308 | 309 | // Internal: Parse URL components and returns a Locationish object. 310 | // 311 | // url - String URL 312 | // 313 | // Returns HTMLAnchorElement that acts like Location. 314 | function parseURL(url) { 315 | var a = document.createElement('a') 316 | a.href = url 317 | return a 318 | } 319 | 320 | // Internal: Build options Object for arguments. 321 | // 322 | // For convenience the first parameter can be either the container or 323 | // the options object. 324 | // 325 | // Examples 326 | // 327 | // optionsFor('#container') 328 | // // => {container: '#container'} 329 | // 330 | // optionsFor('#container', {push: true}) 331 | // // => {container: '#container', push: true} 332 | // 333 | // optionsFor({container: '#container', push: true}) 334 | // // => {container: '#container', push: true} 335 | // 336 | // Returns options Object. 337 | function optionsFor(container, options) { 338 | // Both container and options 339 | if ( container && options ) 340 | options.container = container 341 | 342 | // First argument is options Object 343 | else if ( $.isPlainObject(container) ) 344 | options = container 345 | 346 | // Only container 347 | else 348 | options = {container: container} 349 | 350 | // Find and validate container 351 | if (options.container) 352 | options.container = findContainerFor(options.container) 353 | 354 | return options 355 | } 356 | 357 | // Internal: Find container element for a variety of inputs. 358 | // 359 | // Because we can't persist elements using the history API, we must be 360 | // able to find a String selector that will consistently find the Element. 361 | // 362 | // container - A selector String, jQuery object, or DOM Element. 363 | // 364 | // Returns a jQuery object whose context is `document` and has a selector. 365 | function findContainerFor(container) { 366 | container = $(container) 367 | 368 | if ( !container.length ) { 369 | throw "no pjax container for " + container.selector 370 | } else if ( container.selector !== '' && container.context === document ) { 371 | return container 372 | } else if ( container.attr('id') ) { 373 | return $('#' + container.attr('id')) 374 | } else { 375 | throw "cant get selector for pjax container!" 376 | } 377 | } 378 | 379 | // Internal: Filter and find all elements matching the selector. 380 | // 381 | // Where $.fn.find only matches descendants, findAll will test all the 382 | // top level elements in the jQuery object as well. 383 | // 384 | // elems - jQuery object of Elements 385 | // selector - String selector to match 386 | // 387 | // Returns a jQuery object. 388 | function findAll(elems, selector) { 389 | var results = $() 390 | elems.each(function() { 391 | if ($(this).is(selector)) 392 | results = results.add(this) 393 | results = results.add(selector, this) 394 | }) 395 | return results 396 | } 397 | 398 | // Internal: Extracts container and metadata from response. 399 | // 400 | // 1. Extracts X-PJAX-URL header if set 401 | // 2. Extracts inline tags 402 | // 3. Builds response Element and extracts fragment if set 403 | // 404 | // data - String response data 405 | // xhr - XHR response 406 | // options - pjax options Object 407 | // 408 | // Returns an Object with url, title, and contents keys. 409 | function extractContainer(data, xhr, options) { 410 | var obj = {} 411 | 412 | // Prefer X-PJAX-URL header if it was set, otherwise fallback to 413 | // using the original requested url. 414 | obj.url = stripPjaxParam(xhr.getResponseHeader('X-PJAX-URL') || options.url) 415 | 416 | // Attempt to parse response html into elements 417 | var $data = $(data) 418 | 419 | // If response data is empty, return fast 420 | if ($data.length === 0) 421 | return obj 422 | 423 | // If there's a <title> tag in the response, use it as 424 | // the page's title. 425 | obj.title = findAll($data, 'title').last().text() 426 | 427 | if (options.fragment) { 428 | // If they specified a fragment, look for it in the response 429 | // and pull it out. 430 | var $fragment = findAll($data, options.fragment).first() 431 | 432 | if ($fragment.length) { 433 | obj.contents = $fragment.contents() 434 | 435 | // If there's no title, look for data-title and title attributes 436 | // on the fragment 437 | if (!obj.title) 438 | obj.title = $fragment.attr('title') || $fragment.data('title') 439 | } 440 | 441 | } else if (!/<html/i.test(data)) { 442 | obj.contents = $data 443 | } 444 | 445 | // Clean up any <title> tags 446 | if (obj.contents) { 447 | // Remove any parent title elements 448 | obj.contents = obj.contents.not('title') 449 | 450 | // Then scrub any titles from their descendents 451 | obj.contents.find('title').remove() 452 | } 453 | 454 | // Trim any whitespace off the title 455 | if (obj.title) obj.title = $.trim(obj.title) 456 | 457 | return obj 458 | } 459 | 460 | // Public: Reload current page with pjax. 461 | // 462 | // Returns whatever $.pjax returns. 463 | pjax.reload = function(container, options) { 464 | var defaults = { 465 | url: window.location.href, 466 | push: false, 467 | replace: true, 468 | scrollTo: false 469 | } 470 | 471 | return $.pjax($.extend(defaults, optionsFor(container, options))) 472 | } 473 | 474 | 475 | pjax.defaults = { 476 | timeout: 650, 477 | push: true, 478 | replace: false, 479 | type: 'GET', 480 | dataType: 'html', 481 | scrollTo: 0, 482 | maxCacheLength: 20 483 | } 484 | 485 | // Internal: History DOM caching class. 486 | function Cache() { 487 | this.mapping = {} 488 | this.forwardStack = [] 489 | this.backStack = [] 490 | } 491 | // Push previous state id and container contents into the history 492 | // cache. Should be called in conjunction with `pushState` to save the 493 | // previous container contents. 494 | // 495 | // id - State ID Number 496 | // value - DOM Element to cache 497 | // 498 | // Returns nothing. 499 | Cache.prototype.push = function(id, value) { 500 | this.mapping[id] = value 501 | this.backStack.push(id) 502 | 503 | // Remove all entires in forward history stack after pushing 504 | // a new page. 505 | while (this.forwardStack.length) 506 | delete this.mapping[this.forwardStack.shift()] 507 | 508 | // Trim back history stack to max cache length. 509 | while (this.backStack.length > pjax.defaults.maxCacheLength) 510 | delete this.mapping[this.backStack.shift()] 511 | } 512 | // Retrieve cached DOM Element for state id. 513 | // 514 | // id - State ID Number 515 | // 516 | // Returns DOM Element(s) or undefined if cache miss. 517 | Cache.prototype.get = function(id) { 518 | return this.mapping[id] 519 | } 520 | // Shifts cache from forward history cache to back stack. Should be 521 | // called on `popstate` with the previous state id and container 522 | // contents. 523 | // 524 | // id - State ID Number 525 | // value - DOM Element to cache 526 | // 527 | // Returns nothing. 528 | Cache.prototype.forward = function(id, value) { 529 | this.mapping[id] = value 530 | this.backStack.push(id) 531 | 532 | if (id = this.forwardStack.pop()) 533 | delete this.mapping[id] 534 | } 535 | // Shifts cache from back history cache to forward stack. Should be 536 | // called on `popstate` with the previous state id and container 537 | // contents. 538 | // 539 | // id - State ID Number 540 | // value - DOM Element to cache 541 | // 542 | // Returns nothing. 543 | Cache.prototype.back = function(id, value) { 544 | this.mapping[id] = value 545 | this.forwardStack.push(id) 546 | 547 | if (id = this.backStack.pop()) 548 | delete this.mapping[id] 549 | } 550 | 551 | var containerCache = new Cache 552 | 553 | 554 | // Export $.pjax.click 555 | pjax.click = handleClick 556 | 557 | 558 | // Used to detect initial (useless) popstate. 559 | // If history.state exists, assume browser isn't going to fire initial popstate. 560 | var popped = ('state' in window.history), initialURL = location.href 561 | 562 | 563 | // popstate handler takes care of the back and forward buttons 564 | // 565 | // You probably shouldn't use pjax on pages with other pushState 566 | // stuff yet. 567 | $(window).bind('popstate', function(event){ 568 | // Ignore inital popstate that some browsers fire on page load 569 | var initialPop = !popped && location.href == initialURL 570 | popped = true 571 | if ( initialPop ) return 572 | 573 | var state = event.state 574 | 575 | if (state && state.container) { 576 | var container = $(state.container) 577 | if (container.length) { 578 | var contents = containerCache.get(state.id) 579 | 580 | if (pjax.state) { 581 | // Since state ids always increase, we can deduce the history 582 | // direction from the previous state. 583 | var direction = pjax.state.id < state.id ? 'forward' : 'back' 584 | 585 | // Cache current container before replacement and inform the 586 | // cache which direction the history shifted. 587 | containerCache[direction](pjax.state.id, container.clone(true, true).contents()) 588 | } 589 | 590 | var options = { 591 | id: state.id, 592 | url: state.url, 593 | container: container, 594 | push: false, 595 | fragment: state.fragment, 596 | timeout: state.timeout, 597 | scrollTo: false 598 | } 599 | 600 | if (contents) { 601 | // pjax event is deprecated 602 | $(document).trigger('pjax', [null, options]) 603 | container.trigger('pjax:start', [null, options]) 604 | // end.pjax event is deprecated 605 | container.trigger('start.pjax', [null, options]) 606 | 607 | container.html(contents) 608 | pjax.state = state 609 | 610 | container.trigger('pjax:end', [null, options]) 611 | // end.pjax event is deprecated 612 | container.trigger('end.pjax', [null, options]) 613 | } else { 614 | $.pjax(options) 615 | } 616 | 617 | // Force reflow/relayout before the browser tries to restore the 618 | // scroll position. 619 | container[0].offsetHeight 620 | } else { 621 | window.location = location.href 622 | } 623 | } 624 | }) 625 | 626 | 627 | // Add the state property to jQuery's event object so we can use it in 628 | // $(window).bind('popstate') 629 | if ( $.inArray('state', $.event.props) < 0 ) 630 | $.event.props.push('state') 631 | 632 | 633 | // Is pjax supported by this browser? 634 | $.support.pjax = 635 | window.history && window.history.pushState && window.history.replaceState 636 | // pushState isn't reliable on iOS until 5. 637 | && !navigator.userAgent.match(/((iPod|iPhone|iPad).+\bOS\s+[1-4]|WebApps\/.+CFNetwork)/) 638 | 639 | 640 | // Fall back to normalcy for older browsers. 641 | if ( !$.support.pjax ) { 642 | $.pjax = function( options ) { 643 | var url = $.isFunction(options.url) ? options.url() : options.url, 644 | method = options.type ? options.type.toUpperCase() : 'GET' 645 | 646 | var form = $('<form>', { 647 | method: method === 'GET' ? 'GET' : 'POST', 648 | action: url, 649 | style: 'display:none' 650 | }) 651 | 652 | if (method !== 'GET' && method !== 'POST') { 653 | form.append($('<input>', { 654 | type: 'hidden', 655 | name: '_method', 656 | value: method.toLowerCase() 657 | })) 658 | } 659 | 660 | var data = options.data 661 | if (typeof data === 'string') { 662 | $.each(data.split('&'), function(index, value) { 663 | var pair = value.split('=') 664 | form.append($('<input>', {type: 'hidden', name: pair[0], value: pair[1]})) 665 | }) 666 | } else if (typeof data === 'object') { 667 | for (key in data) 668 | form.append($('<input>', {type: 'hidden', name: key, value: data[key]})) 669 | } 670 | 671 | $(document.body).append(form) 672 | form.submit() 673 | } 674 | $.pjax.click = $.noop 675 | $.pjax.reload = window.location.reload 676 | $.fn.pjax = function() { return this } 677 | } 678 | 679 | })(jQuery); 680 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/public/stylesheets/main.css: -------------------------------------------------------------------------------- 1 | html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{margin:0;padding:0;border:0;outline:0;font-weight:inherit;font-style:inherit;font-size:100%;font-family:inherit;} 2 | table{border-collapse:collapse;border-spacing:0;} 3 | caption,th,td{text-align:left;font-weight:normal;} 4 | form legend{display:none;} 5 | blockquote:before,blockquote:after,q:before,q:after{content:"";} 6 | blockquote,q{quotes:"" "";} 7 | ol,ul{list-style:none;} 8 | hr{display:none;visibility:hidden;} 9 | :focus{outline:0;} 10 | article{}article h1,article h2,article h3,article h4,article h5,article h6{color:#333;font-weight:bold;line-height:1.25;margin-top:1.3em;} 11 | article h1 a,article h2 a,article h3 a,article h4 a,article h5 a,article h6 a{font-weight:inherit;color:#333;}article h1 a:hover,article h2 a:hover,article h3 a:hover,article h4 a:hover,article h5 a:hover,article h6 a:hover{color:#333;} 12 | article h1{font-size:36px;margin:0 0 18px;border-bottom:4px solid #eee;} 13 | article h2{font-size:25px;margin-bottom:9px;border-bottom:2px solid #eee;} 14 | article h3{font-size:18px;margin-bottom:9px;} 15 | article h4{font-size:15px;margin-bottom:3px;} 16 | article h5{font-size:12px;font-weight:normal;margin-bottom:3px;} 17 | article .subheader{color:#777;font-weight:300;margin-bottom:24px;} 18 | article p{line-height:1.3em;margin:1em 0;} 19 | article p img{margin:0;} 20 | article p.lead{font-size:18px;font-size:1.8rem;line-height:1.5;} 21 | article ul li,article ol li{position:relative;padding:4px 0 4px 14px;}article ul li ol,article ol li ol,article ul li ul,article ol li ul{margin-left:20px;} 22 | article ul li:before,article ol li:before{position:absolute;top:8px;left:0;content:"?";color:#ccc;font-size:10px;margin-right:5px;} 23 | article>ol{counter-reset:section;}article>ol li:before{color:#ccc;font-size:13px;} 24 | article>ol>li{padding:6px 0 4px 20px;counter-reset:chapter;}article>ol>li:before{content:counter(section) ".";counter-increment:section;} 25 | article>ol>li>ol>li{padding:6px 0 4px 30px;counter-reset:item;}article>ol>li>ol>li:before{content:counter(section) "." counter(chapter);counter-increment:chapter;} 26 | article>ol>li>ol>li>ol>li{padding:6px 0 4px 40px;}article>ol>li>ol>li>ol>li:before{content:counter(section) "." counter(chapter) "." counter(item);counter-increment:item;} 27 | article em,article i{font-style:italic;line-height:inherit;} 28 | article strong,article b{font-weight:bold;line-height:inherit;} 29 | article small{font-size:60%;line-height:inherit;} 30 | article h1 small,article h2 small,article h3 small,article h4 small,article h5 small{color:#777;} 31 | article hr{border:solid #ddd;border-width:1px 0 0;clear:both;margin:12px 0 18px;height:0;} 32 | article abbr,article acronym{text-transform:uppercase;font-size:90%;color:#222;border-bottom:1px solid #ddd;cursor:help;} 33 | article abbr{text-transform:none;} 34 | article img{max-width:100%;} 35 | article pre{margin:10px 0;border:1px solid #ddd;padding:10px;background:#fafafa;color:#666;overflow:auto;border-radius:5px;} 36 | article code{background:#fafafa;color:#666;font-family:inconsolata, monospace;border:1px solid #ddd;border-radius:3px;height:4px;padding:0;} 37 | article pre code{border:0;background:inherit;border-radius:0;line-height:inherit;font-size:14px;} 38 | article blockquote,article blockquote p,article p.note{line-height:20px;color:#4c4742;} 39 | article blockquote,article .note{margin:0 0 18px;padding:1px 20px;background:#fff7d6;}article blockquote li:before,article .note li:before{color:#e0bc6f;} 40 | article blockquote code,article .note code{background:#f5d899;border:none;color:inherit;} 41 | article blockquote a,article .note a{color:#6dae38;} 42 | article blockquote pre,article .note pre{background:#F5D899 !important;color:#48484C !important;border:none !important;} 43 | article p.note{padding:15px 20px;} 44 | article table{width:100%;}article table td{padding:8px;} 45 | article table tr{background:#F4F4F7;border-bottom:1px solid #eee;} 46 | article table tr:nth-of-type(odd){background:#fafafa;} 47 | a{color:#80c846;}a:hover{color:#6dae38;} 48 | p{margin:1em 0;} 49 | h1{-webkit-font-smoothing:antialiased;} 50 | h2{font-weight:bold;font-size:28px;} 51 | hr{clear:both;margin:20px 0 25px 0;border:none;border-top:1px solid #444;visibility:visible;display:block;} 52 | section{padding:50px 0;} 53 | body{background:#f5f5f5;background:#fff;color:#555;font:15px "Helvetica Nueue",sans-serif;padding:0px 0 0px;} 54 | .wrapper{width:960px;margin:0 auto;box-sizing:border-box;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;padding:60px 0;}.wrapper:after{content:" ";display:block;clear:both;} 55 | .wrapper article{min-height:310px;width:650px;float:left;} 56 | .wrapper aside{width:270px;float:right;}.wrapper aside ul{margin:2px 0 30px;}.wrapper aside ul a{display:block;padding:3px 0 3px 10px;margin:2px 0;border-left:4px solid #eee;}.wrapper aside ul a:hover{border-color:#80c846;} 57 | .wrapper aside h3{font-size:18px;color:#333;font-weight:bold;line-height:2em;margin:9px 0;border-bottom:1px solid #eee;} 58 | .wrapper aside.stick{position:fixed;right:50%;margin-right:-480px;top:120px;bottom:0;overflow:hidden;} 59 | .half{width:50%;float:left;box-sizing:border-box;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;} 60 | header{position:fixed;top:0;z-index:1000;width:100%;height:50px;line-height:50px;padding:30px 0;background:#fff;background:rgba(255, 255, 255, 0.95);border-bottom:1px solid #ccc;box-shadow:0 4px 0 rgba(0, 0, 0, 0.1);}header #logo{position:absolute;left:50%;margin-left:-480px;} 61 | header nav{position:absolute;right:50%;margin-right:-480px;}header nav a{padding:0 10px 4px;font-size:21px;font-weight:500;text-decoration:none;} 62 | header nav a.selected{border-bottom:3px solid #E9E9E9;} 63 | header nav a.download{position:relative;background:#80c846;color:white;margin-left:10px;padding:5px 10px 2px;font-weight:700;border-radius:5px;box-shadow:0 3px 0 #6dae38;text-shadow:-1px -1px 0 rgba(0, 0, 0, 0.2);-webkit-transition:all 70ms ease-out;border:0;}header nav a.download:hover{box-shadow:0 3px 0 #6dae38,0 3px 4px rgba(0, 0, 0, 0.3);} 64 | header nav a.download:active{box-shadow:0 1px 0 #6dae38;top:2px;-webkit-transition:none;} 65 | #download,#getLogo{display:none;position:absolute;padding:5px 20px;width:200px;background:#000;background:rgba(0, 0, 0, 0.8);border-radius:5px;color:#999;line-height:15px;}#download a,#getLogo a{color:#ccc;text-decoration:none;}#download a:hover,#getLogo a:hover{color:#fff;} 66 | #getLogo{text-align:center;}#getLogo h3{font-size:16px;color:#80c846;margin:0 0 15px;} 67 | #getLogo figure{border-radius:3px;margin:5px 0;padding:5px;background:#fff;line-height:25px;width:80px;display:inline-block;}#getLogo figure a{color:#999;text-decoration:none;}#getLogo figure a:hover{color:#666;} 68 | #download{top:85px;right:50%;margin-right:-480px;}#download .button{font-size:16px;color:#80c846;} 69 | #getLogo{top:85px;left:50%;padding:20px;margin-left:-480px;}#getLogo ul{margin:5px 0;} 70 | #getLogo li{margin:1px 0;} 71 | #news{background:#f5f5f5;color:#999;font-size:17px;box-shadow:0 1px 0 rgba(0, 0, 0, 0.1);position:relative;z-index:2;padding:3px 0;}#news ul{box-sizing:border-box;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;background:url(/assets/images/news.png) 10px center no-repeat;padding:19px 0 19px 60px;} 72 | #content{padding:30px 0;} 73 | #top{background:#80c846 url(/@documentation/resources/style/header-pattern.png) fixed;box-shadow:0 -4px 0 rgba(0, 0, 0, 0.1) inset;padding:0;position:relative;}#top .wrapper{padding:30px 0;} 74 | #top h1{float:left;color:#fff;font-size:35px;line-height:48px;text-shadow:2px 2px 0 rgba(0, 0, 0, 0.1);}#top h1 a{text-decoration:none;color:#fff;} 75 | #top nav{float:right;margin-top:10px;line-height:25px;}#top nav .versions,#top nav form{float:left;margin:0 5px;} 76 | #top nav .versions{height:25px;display:inline-block;border:1px solid #6dae38;border-radius:3px;background:#80c846;background:-moz-linear-gradient(top, #80c846 0%, #6dae38 100%);background:-webkit-gradient(linear, left top, left bottom, color-stop(0%, #80c846), color-stop(100%, #6dae38));background:-webkit-linear-gradient(top, #80c846 0%, #6dae38 100%);background:-o-linear-gradient(top, #80c846 0%, #6dae38 100%);background:-ms-linear-gradient(top, #80c846 0%, #6dae38 100%);background:linear-gradient(top, #80c846 0%, #6dae38 100%);filter:progid:DXImageTransform.Microsoft.gradient( startColorstr='#80c846', endColorstr='#6dae38',GradientType=0 );box-shadow:inset 0 -1px 1px #80c846;text-align:center;color:#fff;text-shadow:-1px -1px 0 #6dae38;}#top nav .versions span{padding:0 4px;position:absolute;}#top nav .versions span:before{content:"?";color:rgba(0, 0, 0, 0.4);text-shadow:1px 1px 0 #80c846;margin-right:4px;} 77 | #top nav .versions select{opacity:0;position:relative;z-index:9;} 78 | #top .follow{display:inline-block;border:1px solid #6dae38;border-radius:3px;background:#80c846;background:-moz-linear-gradient(top, #80c846 0%, #6dae38 100%);background:-webkit-gradient(linear, left top, left bottom, color-stop(0%, #80c846), color-stop(100%, #6dae38));background:-webkit-linear-gradient(top, #80c846 0%, #6dae38 100%);background:-o-linear-gradient(top, #80c846 0%, #6dae38 100%);background:-ms-linear-gradient(top, #80c846 0%, #6dae38 100%);background:linear-gradient(top, #80c846 0%, #6dae38 100%);filter:progid:DXImageTransform.Microsoft.gradient( startColorstr='#80c846', endColorstr='#6dae38',GradientType=0 );box-shadow:inset 0 -1px 1px #80c846;text-align:center;vertical-align:middle;color:#fff;text-shadow:-1px -1px 0 #6dae38;padding:4px 8px;text-decoration:none;position:absolute;top:41px;left:50%;margin-left:210px;width:250px;}#top .follow:before{vertical-align:middle;content:url(/assets/images/twitter.png);margin-right:10px;} 79 | #top input{width:80px;-webkit-transition:width 200ms ease-in-out;-moz-transition:width 200ms ease-in-out;}#top input:focus{width:200px;} 80 | #title{width:500px;float:left;font-size:17px;color:#2d6201;} 81 | #quicklinks{width:350px;margin:-15px 0 0 0;box-sizing:border-box;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;float:right;padding:30px;background:#fff;color:#888;box-shadow:0 3px 5px rgba(0, 0, 0, 0.2);}#quicklinks h2{color:#80c846;font-size:20px;margin-top:15px;padding:10px 0 5px 0;border-top:1px solid #eee;}#quicklinks h2:first-child{margin:0;padding:0 0 5px 0;border:0;} 82 | #quicklinks p{margin:0;} 83 | #quicklinks a{color:#444;}#quicklinks a:hover{color:#222;} 84 | .tweet{border-bottom:1px solid #eee;padding:6px 0 20px 60px;position:relative;min-height:50px;margin-bottom:20px;}.tweet img{position:absolute;left:0;top:8px;} 85 | .tweet strong{font-size:14px;font-weight:bold;} 86 | .tweet span{font-size:12px;color:#888;} 87 | .tweet p{padding:0;margin:5px 0 0 0;} 88 | footer{padding:40px 0;background:#363736;background:#eee;border-top:1px solid #e5e5e5;color:#aaa;position:relative;}footer .logo{position:absolute;top:55px;left:50%;margin-left:-480px;-webkit-transform:translate3d(0, 0, 0);-moz-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0);} 89 | footer:after{content:" ";display:block;clear:both;} 90 | footer .links{width:960px;margin:0 auto;box-sizing:border-box;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;margin:0 auto;padding-left:200px;}footer .links:after{content:" ";display:block;clear:both;} 91 | footer .links dl{width:33%;box-sizing:border-box;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;padding:0 10px;float:left;} 92 | footer .links dt{color:#80c846;font-weight:bold;} 93 | footer .links a{color:#aaa;text-decoration:none;}footer .links a:hover{color:#888;} 94 | footer .licence{width:960px;margin:0 auto;box-sizing:border-box;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;margin:20px auto 0;padding-top:20px;border-top:2px solid #ddd;font-size:12px;}footer .licence:after{content:" ";display:block;clear:both;} 95 | footer .licence .typesafe,footer .licence .zenexity{float:right;} 96 | footer .licence .typesafe{position:relative;top:-3px;margin-left:10px;} 97 | footer .licence a{color:#999;} 98 | div.coreteam{position:relative;min-height:80px;border-bottom:1px solid #eee;}div.coreteam img{width:50px;position:absolute;left:0;top:0;padding:2px;border:1px solid #ddd;} 99 | div.coreteam a{color:inherit;text-decoration:none;} 100 | div.coreteam h2{padding-left:70px;border:none;font-size:20px;} 101 | div.coreteam p{margin-top:5px;padding-left:70px;} 102 | ul.contributors{padding:0;margin:0;list-style:none;}ul.contributors li{padding:6px 0 !important;margin:0;}ul.contributors li:before{content:' ';} 103 | ul.contributors img{width:25px;padding:1px;border:1px solid #ddd;margin-right:5px;vertical-align:middle;} 104 | ul.contributors a{color:inherit;text-decoration:none;} 105 | ul.contributors span{font-weight:bold;color:#666;} 106 | ul.contributors.others li{display:inline-block;width:32.3333%;} 107 | div.list{float:left;width:33.3333%;margin-bottom:30px;} 108 | h2{clear:both;} 109 | span.by{font-size:14px;font-weight:normal;} 110 | form dl{padding:10px 0;} 111 | dd.info{color:#888;font-size:12px;} 112 | dd.error{color:#c00;} 113 | aside a[href^="http"]:after,.doc a[href^="http"]:after{content:url(/@documentation/resources/style/external.png);vertical-align:middle;margin-left:5px;} 114 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/test/ApplicationSpec.scala: -------------------------------------------------------------------------------- 1 | package test 2 | 3 | import org.specs2.mutable._ 4 | 5 | import play.api.test._ 6 | import play.api.test.Helpers._ 7 | import controllers.standard.{AuthConfigImpl, Messages} 8 | import jp.t2v.lab.play2.auth.test.Helpers._ 9 | import java.io.File 10 | 11 | class ApplicationSpec extends Specification { 12 | 13 | object config extends AuthConfigImpl 14 | 15 | "Messages" should { 16 | "return list when user is authorized" in new WithApplication(FakeApplication(additionalConfiguration = inMemoryDatabase(name = "default", options = Map("DB_CLOSE_DELAY" -> "-1")))) { 17 | val res = Messages.list(FakeRequest().withLoggedIn(config)(1)) 18 | contentType(res) must beSome("text/html") 19 | } 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /play2-auth-cont-sample/test/IntegrationSpec.scala: -------------------------------------------------------------------------------- 1 | package test 2 | 3 | import org.specs2.mutable._ 4 | 5 | import play.api.test._ 6 | import play.api.test.Helpers._ 7 | import java.io.File 8 | 9 | class IntegrationSpec extends Specification { 10 | 11 | "Standard Sample" should { 12 | 13 | "work from within a browser" in new WithBrowser(webDriver = WebDriverFactory(HTMLUNIT), app = FakeApplication(additionalConfiguration = inMemoryDatabase(name = "default", options = Map("DB_CLOSE_DELAY" -> "-1")))) { 14 | 15 | val baseURL = s"http://localhost:${port}" 16 | // login failed 17 | browser.goTo(baseURL) 18 | browser.$("#email").text("alice@example.com") 19 | browser.$("#password").text("secretxxx") 20 | browser.$("#loginbutton").click() 21 | browser.pageSource must contain("Invalid email or password") 22 | 23 | // login succeded 24 | browser.$("#email").text("alice@example.com") 25 | browser.$("#password").text("secret") 26 | browser.$("#loginbutton").click() 27 | browser.$("dl.error").size must equalTo(0) 28 | browser.pageSource must not contain ("Sign in") 29 | browser.pageSource must contain("logout") 30 | browser.getCookie("PLAY2AUTH_SESS_ID").getExpiry must not beNull 31 | 32 | // logout 33 | browser.$("a").click() 34 | browser.pageSource must contain("Sign in") 35 | 36 | browser.goTo(s"$baseURL/standard/messages/write") 37 | browser.pageSource must contain("Sign in") 38 | 39 | } 40 | 41 | "authorize" in new WithBrowser(webDriver = WebDriverFactory(HTMLUNIT), app = FakeApplication(additionalConfiguration = inMemoryDatabase(name = "default", options = Map("DB_CLOSE_DELAY" -> "-1")))) { 42 | 43 | val baseURL = s"http://localhost:${port}" 44 | 45 | // login succeded 46 | browser.goTo(baseURL) 47 | browser.$("#email").text("bob@example.com") 48 | browser.$("#password").text("secret") 49 | browser.$("#loginbutton").click() 50 | browser.$("dl.error").size must equalTo(0) 51 | browser.pageSource must not contain("Sign in") 52 | browser.pageSource must contain("logout") 53 | 54 | browser.goTo(s"${baseURL}/standard/messages/write") 55 | browser.pageSource must contain("no permission") 56 | 57 | browser.goTo(s"${baseURL}/standard/logout") 58 | browser.$("#email").text("alice@example.com") 59 | browser.$("#password").text("secret") 60 | browser.$("#loginbutton").click() 61 | browser.$("dl.error").size must equalTo(0) 62 | browser.goTo(s"${baseURL}/standard/messages/write") 63 | browser.pageSource must not contain("no permission") 64 | 65 | } 66 | 67 | } 68 | 69 | "Builder Sample" should { 70 | 71 | "work from within a browser" in new WithBrowser(webDriver = WebDriverFactory(HTMLUNIT), app = FakeApplication(additionalConfiguration = inMemoryDatabase(name = "default", options = Map("DB_CLOSE_DELAY" -> "-1")))) { 72 | 73 | val baseURL = s"http://localhost:${port}" 74 | // login failed 75 | browser.goTo(s"${baseURL}/builder/") 76 | browser.$("#email").text("alice@example.com") 77 | browser.$("#password").text("secretxxx") 78 | browser.$("#loginbutton").click() 79 | browser.pageSource must contain("Invalid email or password") 80 | 81 | // login succeded 82 | browser.$("#email").text("alice@example.com") 83 | browser.$("#password").text("secret") 84 | browser.$("#loginbutton").click() 85 | browser.$("dl.error").size must equalTo(0) 86 | browser.pageSource must not contain("Sign in") 87 | browser.pageSource must contain("logout") 88 | 89 | // logout 90 | browser.$("a").click() 91 | browser.pageSource must contain("Sign in") 92 | 93 | browser.goTo(s"$baseURL/builder/messages/write") 94 | browser.pageSource must contain("Sign in") 95 | 96 | } 97 | 98 | "authorize" in new WithBrowser(webDriver = WebDriverFactory(HTMLUNIT), app = FakeApplication(additionalConfiguration = inMemoryDatabase(name = "default", options = Map("DB_CLOSE_DELAY" -> "-1")))) { 99 | 100 | val baseURL = s"http://localhost:${port}" 101 | 102 | // login succeded 103 | browser.goTo(s"${baseURL}/builder/") 104 | browser.$("#email").text("bob@example.com") 105 | browser.$("#password").text("secret") 106 | browser.$("#loginbutton").click() 107 | browser.$("dl.error").size must equalTo(0) 108 | browser.pageSource must not contain("Sign in") 109 | browser.pageSource must contain("logout") 110 | 111 | browser.goTo(s"${baseURL}/builder/messages/write") 112 | browser.pageSource must contain("no permission") 113 | 114 | browser.goTo(s"${baseURL}/builder/logout") 115 | browser.$("#email").text("alice@example.com") 116 | browser.$("#password").text("secret") 117 | browser.$("#loginbutton").click() 118 | browser.$("dl.error").size must equalTo(0) 119 | browser.goTo(s"${baseURL}/builder/messages/write") 120 | browser.pageSource must not contain("no permission") 121 | 122 | } 123 | 124 | } 125 | 126 | "CSRF Sample" should { 127 | 128 | "work from within a browser" in new WithBrowser(webDriver = WebDriverFactory(HTMLUNIT), app = FakeApplication(additionalConfiguration = inMemoryDatabase(name = "default", options = Map("DB_CLOSE_DELAY" -> "-1")))) { 129 | 130 | val baseURL = s"http://localhost:${port}" 131 | // login 132 | browser.goTo(s"${baseURL}/csrf/") 133 | browser.$("#email").text("alice@example.com") 134 | browser.$("#password").text("secret") 135 | browser.$("#loginbutton").click() 136 | browser.$("dl.error").size must equalTo(0) 137 | browser.pageSource must not contain("Sign in") 138 | browser.pageSource must contain("logout") 139 | 140 | // submit with token form 141 | browser.$("#message").text("testmessage") 142 | browser.$("#submitbutton").click() 143 | browser.pageSource must contain("testmessage") 144 | 145 | // submit without token form 146 | browser.goTo(s"$baseURL/csrf/without_token") 147 | browser.pageSource must not contain("Sign in") 148 | browser.pageSource must contain("logout") 149 | browser.$("#message").text("testmessage") 150 | browser.$("#submitbutton").click() 151 | browser.pageSource must not contain("testmessage") 152 | 153 | } 154 | 155 | } 156 | 157 | "Ephemeral Sample" should { 158 | 159 | "work from within a browser" in new WithBrowser(webDriver = WebDriverFactory(HTMLUNIT), app = FakeApplication(additionalConfiguration = inMemoryDatabase(name = "default", options = Map("DB_CLOSE_DELAY" -> "-1")))) { 160 | 161 | val baseURL = s"http://localhost:${port}" 162 | // login failed 163 | browser.goTo(s"${baseURL}/ephemeral/") 164 | browser.$("#email").text("alice@example.com") 165 | browser.$("#password").text("secretxxx") 166 | browser.$("#loginbutton").click() 167 | browser.pageSource must contain("Invalid email or password") 168 | 169 | // login succeded 170 | browser.$("#email").text("alice@example.com") 171 | browser.$("#password").text("secret") 172 | browser.$("#loginbutton").click() 173 | browser.$("dl.error").size must equalTo(0) 174 | browser.pageSource must not contain("Sign in") 175 | browser.pageSource must contain("logout") 176 | browser.getCookie("PLAY2AUTH_SESS_ID").getExpiry must beNull 177 | 178 | // logout 179 | browser.$("a").click() 180 | browser.pageSource must contain("Sign in") 181 | 182 | browser.goTo(s"$baseURL/ephemeral/messages/write") 183 | browser.pageSource must contain("Sign in") 184 | 185 | } 186 | 187 | "authorize" in new WithBrowser(webDriver = WebDriverFactory(HTMLUNIT), app = FakeApplication(additionalConfiguration = inMemoryDatabase(name = "default", options = Map("DB_CLOSE_DELAY" -> "-1")))) { 188 | 189 | val baseURL = s"http://localhost:${port}" 190 | 191 | // login succeded 192 | browser.goTo(s"${baseURL}/ephemeral/") 193 | browser.$("#email").text("bob@example.com") 194 | browser.$("#password").text("secret") 195 | browser.$("#loginbutton").click() 196 | browser.$("dl.error").size must equalTo(0) 197 | browser.pageSource must not contain("Sign in") 198 | browser.pageSource must contain("logout") 199 | browser.getCookie("PLAY2AUTH_SESS_ID").getExpiry must beNull 200 | 201 | browser.goTo(s"${baseURL}/ephemeral/messages/write") 202 | browser.pageSource must contain("no permission") 203 | 204 | browser.goTo(s"${baseURL}/ephemeral/logout") 205 | browser.$("#email").text("alice@example.com") 206 | browser.$("#password").text("secret") 207 | browser.$("#loginbutton").click() 208 | browser.$("dl.error").size must equalTo(0) 209 | browser.goTo(s"${baseURL}/ephemeral/messages/write") 210 | browser.pageSource must not contain("no permission") 211 | 212 | } 213 | 214 | } 215 | 216 | "Stateless Sample" should { 217 | 218 | "work from within a browser" in new WithBrowser(webDriver = WebDriverFactory(HTMLUNIT), app = FakeApplication(additionalConfiguration = inMemoryDatabase(name = "default", options = Map("DB_CLOSE_DELAY" -> "-1")))) { 219 | 220 | val baseURL = s"http://localhost:${port}" 221 | // login failed 222 | browser.goTo(s"$baseURL/stateless/") 223 | browser.$("#email").text("alice@example.com") 224 | browser.$("#password").text("secretxxx") 225 | browser.$("#loginbutton").click() 226 | browser.pageSource must contain("Invalid email or password") 227 | 228 | // login succeded 229 | browser.$("#email").text("alice@example.com") 230 | browser.$("#password").text("secret") 231 | browser.$("#loginbutton").click() 232 | browser.$("dl.error").size must equalTo(0) 233 | browser.pageSource must not contain ("Sign in") 234 | browser.pageSource must contain("logout") 235 | 236 | // logout 237 | browser.$("a").click() 238 | browser.pageSource must contain("Sign in") 239 | 240 | browser.goTo(s"$baseURL/stateless/messages/write") 241 | browser.pageSource must contain("Sign in") 242 | 243 | } 244 | 245 | "authorize" in new WithBrowser(webDriver = WebDriverFactory(HTMLUNIT), app = FakeApplication(additionalConfiguration = inMemoryDatabase(name = "default", options = Map("DB_CLOSE_DELAY" -> "-1")))) { 246 | 247 | val baseURL = s"http://localhost:${port}" 248 | 249 | // login succeded 250 | browser.goTo(s"$baseURL/stateless/") 251 | browser.$("#email").text("bob@example.com") 252 | browser.$("#password").text("secret") 253 | browser.$("#loginbutton").click() 254 | browser.$("dl.error").size must equalTo(0) 255 | browser.pageSource must not contain("Sign in") 256 | browser.pageSource must contain("logout") 257 | 258 | browser.goTo(s"${baseURL}/stateless/messages/write") 259 | browser.pageSource must contain("no permission") 260 | 261 | browser.goTo(s"${baseURL}/stateless/logout") 262 | browser.$("#email").text("alice@example.com") 263 | browser.$("#password").text("secret") 264 | browser.$("#loginbutton").click() 265 | browser.$("dl.error").size must equalTo(0) 266 | browser.goTo(s"${baseURL}/stateless/messages/write") 267 | browser.pageSource must not contain("no permission") 268 | 269 | } 270 | 271 | } 272 | 273 | "HTTP Basic Auth Sample" should { 274 | 275 | "work from within a browser" in new WithBrowser(webDriver = WebDriverFactory(HTMLUNIT), app = FakeApplication(additionalConfiguration = inMemoryDatabase(name = "default", options = Map("DB_CLOSE_DELAY" -> "-1")))) { 276 | 277 | val baseURL = s"http://localhost:${port}" 278 | // login failed 279 | browser.goTo(s"$baseURL/basic/") 280 | browser.url must equalTo("/basic/messages/main") 281 | 282 | } 283 | 284 | } 285 | 286 | "Remember Me Sample" should { 287 | 288 | "work from within a browser" in new WithBrowser(webDriver = WebDriverFactory(HTMLUNIT), app = FakeApplication(additionalConfiguration = inMemoryDatabase(name = "default", options = Map("DB_CLOSE_DELAY" -> "-1")))) { 289 | 290 | val baseURL = s"http://localhost:${port}" 291 | // login failed 292 | browser.goTo(s"$baseURL/rememberme/") 293 | browser.$("#email").text("alice@example.com") 294 | browser.$("#password").text("secretxxx") 295 | browser.$("#loginbutton").click() 296 | browser.pageSource must contain("Invalid email or password") 297 | 298 | // login succeded 299 | browser.$("#email").text("alice@example.com") 300 | browser.$("#password").text("secret") 301 | browser.$("#loginbutton").click() 302 | browser.$("dl.error").size must equalTo(0) 303 | browser.pageSource must not contain ("Sign in") 304 | browser.pageSource must contain("logout") 305 | browser.getCookie("PLAY2AUTH_SESS_ID").getExpiry must beNull 306 | 307 | // logout 308 | browser.$("a").click() 309 | browser.pageSource must contain("Sign in") 310 | 311 | browser.goTo(s"$baseURL/rememberme/messages/write") 312 | browser.pageSource must contain("Sign in") 313 | 314 | // login succeded 315 | browser.$("#email").text("alice@example.com") 316 | browser.$("#password").text("secret") 317 | browser.$("#rememberme").click() 318 | browser.$("#loginbutton").click() 319 | browser.$("dl.error").size must equalTo(0) 320 | browser.pageSource must not contain ("Sign in") 321 | browser.pageSource must contain("logout") 322 | browser.getCookie("PLAY2AUTH_SESS_ID").getExpiry must not beNull 323 | 324 | browser.$("a").click() 325 | 326 | } 327 | 328 | "authorize" in new WithBrowser(webDriver = WebDriverFactory(HTMLUNIT), app = FakeApplication(additionalConfiguration = inMemoryDatabase(name = "default", options = Map("DB_CLOSE_DELAY" -> "-1")))) { 329 | 330 | val baseURL = s"http://localhost:${port}" 331 | 332 | // login succeded 333 | browser.goTo(s"$baseURL/rememberme/") 334 | browser.$("#email").text("bob@example.com") 335 | browser.$("#password").text("secret") 336 | browser.$("#loginbutton").click() 337 | browser.$("dl.error").size must equalTo(0) 338 | browser.pageSource must not contain("Sign in") 339 | browser.pageSource must contain("logout") 340 | 341 | browser.goTo(s"${baseURL}/rememberme/messages/write") 342 | browser.pageSource must contain("no permission") 343 | 344 | browser.goTo(s"${baseURL}/rememberme/logout") 345 | browser.$("#email").text("alice@example.com") 346 | browser.$("#password").text("secret") 347 | browser.$("#loginbutton").click() 348 | browser.$("dl.error").size must equalTo(0) 349 | browser.goTo(s"${baseURL}/standard/messages/write") 350 | browser.pageSource must not contain("no permission") 351 | 352 | } 353 | 354 | } 355 | 356 | } 357 | 358 | -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.13.8 2 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | resolvers += "Typesafe repository" at "https://repo.typesafe.com/typesafe/releases/" 2 | 3 | addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.3.8") 4 | --------------------------------------------------------------------------------