webmcp

view framework/env/request/set_cookie.lua @ 569:5b19007574de

New argument active_link_attr for env.ui.paginate{...}
author jbe
date Wed Oct 13 17:21:44 2021 +0200 (2021-10-13)
parents a0f1a4e76556
children
line source
1 --[[--
2 request.set_cookie{
3 name = name, -- name of cookie
4 value = value, -- value of cookie
5 domain = domain, -- optional domain domain where cookie is transmitted
6 path = path, -- optional path where cookie is transmitted, defaults to application base
7 secure = secure, -- optional boolean, indicating if cookie should only be transmitted over HTTPS
8 samesite = samesite -- SameSite policy set to "strict", "lax", or "none" (all lower-case, defaults to "lax")
9 }
11 This function is similar to rocketwiki.set_cookie{...}, except that it automatically sets the path to the application base. It also sets secure=true, if the secure option is unset and the application base URL starts with "https://".
13 --]]--
15 function request.set_cookie(args)
16 local args = table.new(args)
17 if not args.path then
18 args.path = string.match(
19 request.get_absolute_baseurl(),
20 "://[^/]*(.*)"
21 )
22 if args.path == nil then
23 args.path = "/"
24 end
25 end
26 if args.secure == nil then
27 if string.find(
28 string.lower(request.get_absolute_baseurl()),
29 "^https://"
30 ) then
31 args.secure = true
32 else
33 args.secure = false
34 end
35 end
36 assert(string.find(args.name, "^[0-9A-Za-z%%._~-]+$"), "Illegal cookie name")
37 assert(string.find(args.value, "^[0-9A-Za-z%%._~-]+$"), "Illegal cookie value")
38 local parts = {args.name .. "=" .. args.value}
39 if args.domain then
40 assert(
41 string.find(args.path, "^[0-9A-Za-z%%/._~-]+$"),
42 "Illegal cookie domain"
43 )
44 parts[#parts+1] = "domain=" .. args.domain
45 end
46 if args.path then
47 assert(
48 string.find(args.path, "^[0-9A-Za-z%%/._~-]+$"),
49 "Illegal cookie path"
50 )
51 parts[#parts+1] = "path=" .. args.path
52 end
53 if args.secure then
54 parts[#parts+1] = "secure"
55 end
56 if args.samesite == "strict" then
57 parts[#parts+1] = "SameSite=Strict"
58 elseif args.samesite == "lax" or args.samesite == nil then
59 parts[#parts+1] = "SameSite=Lax"
60 elseif args.samesite == "none" then
61 parts[#parts+1] = "SameSite=None"
62 else
63 error("Cookie SameSite policy set to unsupported value")
64 end
65 request.add_header("Set-Cookie", table.concat(parts, "; "))
66 end

Impressum / About Us