|
| 1 | +--- |
| 2 | +title: How to use cookies and decorators? |
| 3 | +type: section |
| 4 | +description: Using cookies and decorators with Cask |
| 5 | +num: 36 |
| 6 | +previous-page: web-server-websockets |
| 7 | +next-page: |
| 8 | +--- |
| 9 | + |
| 10 | +{% include markdown.html path="_markdown/install-cask.md" %} |
| 11 | + |
| 12 | +## Using cookies |
| 13 | + |
| 14 | +Cookies are saved by adding them to the `cookies` parameter of the `cask.Response` constructor. |
| 15 | + |
| 16 | +In this example, we are building a rudimentary authentication service. The `getLogin` method provides a form where |
| 17 | +the user can enter their username and password. The `postLogin` method reads the credentials. If they match the expected ones, it generates a session |
| 18 | +identifier is generated, saves it in the application state, and sends back a cookie with the identifier. |
| 19 | + |
| 20 | +Cookies can be read either with a method parameter of `cask.Cookie` type or by accessing the `cask.Request` directly. |
| 21 | +If using the former method, the names of parameters have to match the names of cookies. If a cookie with a matching name is not |
| 22 | +found, an error response will be returned. In the `checkLogin` function, the former method is used, as the cookie is not |
| 23 | +present before the user logs in. |
| 24 | + |
| 25 | +To delete a cookie, set its `expires` parameter to an instant in the past, for example `Instant.EPOCH`. |
| 26 | + |
| 27 | +{% tabs web-server-cookies-1 class=tabs-scala-version %} |
| 28 | +{% tab 'Scala 2' %} |
| 29 | + |
| 30 | +```scala |
| 31 | +import java.util.UUID |
| 32 | +import java.util.concurrent.ConcurrentHashMap |
| 33 | + |
| 34 | +object Example extends cask.MainRoutes { |
| 35 | + |
| 36 | + val sessionIds = ConcurrentHashMap.newKeySet[String]() |
| 37 | + |
| 38 | + @cask.get("/login") |
| 39 | + def getLogin(): cask.Response[String] = { |
| 40 | + val html = |
| 41 | + """<!doctype html> |
| 42 | + |<html> |
| 43 | + |<body> |
| 44 | + |<form action="/login" method="post"> |
| 45 | + | <label for="name">Username:</label><br> |
| 46 | + | <input type="text" name="name" value=""><br> |
| 47 | + | <label for="password">Password:</label><br> |
| 48 | + | <input type="text" name="password" value=""><br><br> |
| 49 | + | <input type="submit" value="Submit"> |
| 50 | + |</form> |
| 51 | + |</body> |
| 52 | + |</html>""".stripMargin |
| 53 | + |
| 54 | + cask.Response(data = html, headers = Seq("Content-Type" -> "text/html")) |
| 55 | + } |
| 56 | + |
| 57 | + @cask.postForm("/login") |
| 58 | + def postLogin(name: String, password: String): cask.Response[String] = { |
| 59 | + if (name == "user" && password == "password") { |
| 60 | + val sessionId = UUID.randomUUID().toString |
| 61 | + sessionIds.add(sessionId) |
| 62 | + cask.Response(data = "Success!", cookies = Seq(cask.Cookie("sessionId", sessionId))) |
| 63 | + } else { |
| 64 | + cask.Response(data = "Authentication failed", statusCode = 401) |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + @cask.get("/check") |
| 69 | + def checkLogin(request: cask.Request): String = { |
| 70 | + val sessionId = request.cookies.get("sessionId") |
| 71 | + if (sessionId.exists(cookie => sessionIds.contains(cookie.value))) { |
| 72 | + "You are logged in" |
| 73 | + } else { |
| 74 | + "You are not logged in" |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + @cask.get("/logout") |
| 79 | + def logout(sessionId: cask.Cookie) = { |
| 80 | + sessionIds.remove(sessionId.value) |
| 81 | + cask.Response(data = "Successfully logged out!", cookies = Seq(cask.Cookie("sessionId", "", expires = Instant.EPOCH))) |
| 82 | + } |
| 83 | + |
| 84 | + initialize() |
| 85 | +} |
| 86 | +``` |
| 87 | +{% endtab %} |
| 88 | +{% tab 'Scala 3' %} |
| 89 | +```scala |
| 90 | +import java.util.UUID |
| 91 | +import java.util.concurrent.ConcurrentHashMap |
| 92 | + |
| 93 | +object Example extends cask.MainRoutes: |
| 94 | + |
| 95 | + val sessionIds = ConcurrentHashMap.newKeySet[String]() |
| 96 | + |
| 97 | + @cask.get("/login") |
| 98 | + def getLogin(): cask.Response[String] = |
| 99 | + val html = |
| 100 | + """<!doctype html> |
| 101 | + |<html> |
| 102 | + |<body> |
| 103 | + |<form action="/login" method="post"> |
| 104 | + | <label for="name">Username:</label><br> |
| 105 | + | <input type="text" name="name" value=""><br> |
| 106 | + | <label for="password">Password:</label><br> |
| 107 | + | <input type="text" name="password" value=""><br><br> |
| 108 | + | <input type="submit" value="Submit"> |
| 109 | + |</form> |
| 110 | + |</body> |
| 111 | + |</html>""".stripMargin |
| 112 | + |
| 113 | + cask.Response(data = html, headers = Seq("Content-Type" -> "text/html")) |
| 114 | + |
| 115 | + @cask.postForm("/login") |
| 116 | + def postLogin(name: String, password: String): cask.Response[String] = |
| 117 | + if name == "user" && password == "password" then |
| 118 | + val sessionId = UUID.randomUUID().toString |
| 119 | + sessionIds.add(sessionId) |
| 120 | + cask.Response(data = "Success!", cookies = Seq(cask.Cookie("sessionId", sessionId))) |
| 121 | + else |
| 122 | + cask.Response(data = "Authentication failed", statusCode = 401) |
| 123 | + |
| 124 | + @cask.get("/check") |
| 125 | + def checkLogin(request: cask.Request): String = |
| 126 | + val sessionId = request.cookies.get("sessionId") |
| 127 | + if sessionId.exists(cookie => sessionIds.contains(cookie.value)) then |
| 128 | + "You are logged in" |
| 129 | + else |
| 130 | + "You are not logged in" |
| 131 | + |
| 132 | + @cask.get("/logout") |
| 133 | + def logout(sessionId: cask.Cookie): cask.Response[String] = |
| 134 | + sessionIds.remove(sessionId.value) |
| 135 | + cask.Response(data = "Successfully logged out!", cookies = Seq(cask.Cookie("sessionId", "", expires = Instant.EPOCH))) |
| 136 | + |
| 137 | + initialize() |
| 138 | +``` |
| 139 | +{% endtab %} |
| 140 | +{% endtabs %} |
| 141 | + |
| 142 | +## Using decorators |
| 143 | + |
| 144 | +Decorators can be used for extending endpoints functionality with validation or new parameters. They are defined by extending |
| 145 | +`cask.RawDecorator` class. They are used as annotations. |
| 146 | + |
| 147 | +In this example, the `loggedIn` decorator is used to check if the user is logged in before accessing the `/decorated` |
| 148 | +endpoint. |
| 149 | + |
| 150 | +The decorator class can pass additional arguments to the decorated endpoint using a map. The passed arguments are available |
| 151 | +through the last argument group. Here we are passing the session identifier to an argument named `sessionId`. |
| 152 | + |
| 153 | +{% tabs web-server-cookies-2 class=tabs-scala-version %} |
| 154 | +{% tab 'Scala 2' %} |
| 155 | +```scala |
| 156 | +class loggedIn extends cask.RawDecorator { |
| 157 | + override def wrapFunction(ctx: cask.Request, delegate: Delegate): Result[Raw] = { |
| 158 | + ctx.cookies.get("sessionId") match { |
| 159 | + case Some(cookie) if sessionIds.contains(cookie.value) => delegate(Map("sessionId" -> cookie.value)) |
| 160 | + case _ => cask.router.Result.Success(cask.model.Response("You aren't logged in", 403)) |
| 161 | + } |
| 162 | + } |
| 163 | +} |
| 164 | + |
| 165 | +@loggedIn() |
| 166 | +@cask.get("/decorated") |
| 167 | +def decorated()(sessionId: String): String = { |
| 168 | + s"You are logged in with id: $sessionId" |
| 169 | +} |
| 170 | +``` |
| 171 | +{% endtab %} |
| 172 | +{% tab 'Scala 3' %} |
| 173 | +```scala |
| 174 | +class loggedIn extends cask.RawDecorator: |
| 175 | + override def wrapFunction(ctx: cask.Request, delegate: Delegate): Result[Raw] = |
| 176 | + ctx.cookies.get("sessionId") match |
| 177 | + case Some(cookie) if sessionIds.contains(cookie.value) => |
| 178 | + delegate(Map("sessionId" -> cookie.value)) |
| 179 | + case _ => |
| 180 | + cask.router.Result.Success(cask.model.Response("You aren't logged in", 403)) |
| 181 | + |
| 182 | + |
| 183 | +@loggedIn() |
| 184 | +@cask.get("/decorated") |
| 185 | +def decorated()(sessionId: String): String = s"You are logged in with id: $sessionId" |
| 186 | +``` |
| 187 | +{% endtab %} |
| 188 | +{% endtabs %} |
0 commit comments