Created
March 4, 2018 15:42
-
-
Save tindzk/6a7d269a41653defd799fa5779492d1b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.scalajs.dom.document | |
object Session { | |
val CookieName = "SessionId" | |
val key: String = CookieName | |
var username: Option[String] = Option(JsGlobals.username) | |
def get: Option[String] = | |
document.cookie.split(";").toList.flatMap { part => | |
part.split("=").toList match { | |
case `key` :: value :: Nil if value.nonEmpty => List(value) | |
case _ => Nil | |
} | |
}.headOption | |
def set(key: String, value: String, expires: String, path: String = "/"): Unit = | |
document.cookie = s"$key=$value; expires=$expires; path=$path" | |
def set: Option[String] => Unit = { | |
case None => set(key, "", "Thu, 01-Jan-1970 00:00:01 GMT") | |
case Some(sess) => set(key, sess, "Fri, 31 Dec 9999 23:59:59 GMT") | |
} | |
def reset(): Unit = { | |
username = None | |
set(None) | |
} | |
def set(username: String, hash: String): Unit = { | |
this.username = Some(username) | |
set(Some(hash)) | |
} | |
} | |
object LogInPage { | |
def manage(): Unit = { | |
TagRef[tag.Button]("login").click := { | |
val username = TagRef[tag.Input]("username").dom.value | |
val password = TagRef[tag.Input]("password").dom.value | |
API.request(protocol.LogIn(username, password)).foreach { | |
case None => | |
Session.reset() | |
window.alert("Log-in failed") | |
case Some(hash) => | |
Session.set(username, hash) | |
val host = window.location.origin | |
window.location.href = s"$host/" | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment