Advertisement
Guest User

Untitled

a guest
Sep 30th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.97 KB | None | 0 0
  1. package blog
  2.  
  3. import kotlinx.html.*
  4. import kotlinx.html.stream.* // for createHTML
  5. import org.jetbrains.ktor.application.*
  6. import org.jetbrains.ktor.auth.*
  7. import org.jetbrains.ktor.features.*
  8. import org.jetbrains.ktor.http.*
  9. import org.jetbrains.ktor.response.*
  10. import org.jetbrains.ktor.routing.*
  11.  
  12. import org.jetbrains.ktor.request.* // for request.uri
  13.  
  14. import org.jetbrains.ktor.html.*
  15. import org.jetbrains.ktor.pipeline.*
  16.  
  17. import org.jetbrains.ktor.host.* // for embededServer
  18. import org.jetbrains.ktor.netty.* // for Netty
  19.  
  20. fun main(args: Array<String>) {
  21. embeddedServer(Netty, 8080, watchPaths = listOf("BlogAppKt"), module = Application::module).start()
  22. }
  23.  
  24. fun Application.module() {
  25. install(DefaultHeaders)
  26. install(CallLogging)
  27.  
  28. intercept(ApplicationCallPipeline.Call) {
  29. if (call.request.uri == "/hi")
  30. call.respondText("Test String")
  31. }
  32.  
  33. install(Routing) {
  34. get("/") {
  35. call.respondText("""Hello, world!<br><a href="/bye">Say bye?</a>""", ContentType.Text.Html)
  36. }
  37. get("/bye") {
  38. call.respondText("""Good bye! <br><a href="/login">Login?</a> """, ContentType.Text.Html)
  39. }
  40. route("/login") {
  41. authentication {
  42. formAuthentication { up: UserPasswordCredential ->
  43. when {
  44. up.password == "ppp" -> UserIdPrincipal(up.name)
  45. else -> null
  46. }
  47. }
  48. }
  49.  
  50. handle {
  51. val principal = call.authentication.principal<UserIdPrincipal>()
  52. if (principal != null) {
  53. call.respondText("Hello, ${principal.name}")
  54. } else {
  55. val html = createHTML().html {
  56. body {
  57. form(action = "/login", encType = FormEncType.applicationXWwwFormUrlEncoded, method = FormMethod.post) {
  58. p {
  59. +"user:"
  60. textInput(name = "user") {
  61. value = principal?.name ?: ""
  62. }
  63. }
  64.  
  65. p {
  66. +"password:"
  67. passwordInput(name = "pass")
  68. }
  69.  
  70. p {
  71. submitInput() { value = "Login" }
  72. }
  73. }
  74. }
  75. }
  76. call.respondText(html, ContentType.Text.Html)
  77. }
  78. }
  79. }
  80. }
  81. }
  82.  
  83. authentication {
  84. formAuthentication { up: UserPasswordCredential ->
  85. when {
  86. up.password == "ppp" -> UserIdPrincipal(up.name)
  87. else -> null
  88. }
  89. }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement