Cookies are saved by adding them to the cookies parameter of the cask.Response constructor.
In this example, we are building a rudimentary authentication service. The getLogin method provides a form where
the user can enter their username and password. The postLogin method reads the credentials. If they match the expected ones, it generates a session
identifier is generated, saves it in the application state, and sends back a cookie with the identifier.
Cookies can be read either with a method parameter of cask.Cookie type or by accessing the cask.Request directly.
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
found, an error response will be returned. In the checkLogin function, the former method is used, as the cookie is not
present before the user logs in.
To delete a cookie, set its expires parameter to an instant in the past, for example Instant.EPOCH.
Decorators can be used for extending endpoints functionality with validation or new parameters. They are defined by extending
cask.RawDecorator class. They are used as annotations.
In this example, the loggedIn decorator is used to check if the user is logged in before accessing the /decorated
endpoint.
The decorator class can pass additional arguments to the decorated endpoint using a map. The passed arguments are available
through the last argument group. Here we are passing the session identifier to an argument named sessionId.
classloggedInextendscask.RawDecorator{overridedefwrapFunction(ctx:cask.Request,delegate:Delegate):Result[Raw]={ctx.cookies.get("sessionId")match{caseSome(cookie)ifsessionIds.contains(cookie.value)=>delegate(Map("sessionId"->cookie.value))case_=>cask.router.Result.Success(cask.model.Response("You aren't logged in",403))}}}@loggedIn()@cask.get("/decorated")defdecorated()(sessionId:String):String={s"You are logged in with id: $sessionId"}
classloggedInextendscask.RawDecorator:overridedefwrapFunction(ctx:cask.Request,delegate:Delegate):Result[Raw]=ctx.cookies.get("sessionId")matchcaseSome(cookie)ifsessionIds.contains(cookie.value)=>delegate(Map("sessionId"->cookie.value))case_=>cask.router.Result.Success(cask.model.Response("You aren't logged in",403))@loggedIn()@cask.get("/decorated")defdecorated()(sessionId:String):String=s"You are logged in with id: $sessionId"