Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

40
LINES

< > BotCompany Repo | #1027732 // ServeHttp_CookieHandler

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (13531L/80K).

sclass ServeHttp_CookieHandler {
  int days = 365;
  S cookieName = "cookie";
  bool verbose;
  S cookieValue;
  S metaParams; // e.g. "SameSite=Strict"
  bool shareCookiesBetweenApexDomains;

  // returns cookie (may be empty if client doesn't accept cookies)
  S handle() {
    NanoHTTPD.IHTTPSession session = NanoHTTPD.currentSession!;
    if (session == null) null;
    NanoHTTPD.CookieHandler cookies = session.getCookies();
    if (empty(cookieValue)) cookieValue = cookies.read(cookieName);
    S existingValue = cookieValue;
    var headers= session.getHeaders();
    if (empty(cookieValue) && empty((S) mapGet(headers, "x-no-cookies"))) {
      cookieValue = createNewCookie();
      if (verbose)
        print("New cookie.");
    }
    
    if (verbose)
      print("IP " + session.remoteIp() + ", cookie: " + cookieValue);
      
    if (!eq_nullIfEmpty(existingValue, cookieValue)) {
      var cookie = cookies.set(cookieName, cookieValue + prependIfNempty("; ", metaParams), days);
      
      S apexDomain = apexDomain(dropPortFromHost(session.getHeaders().get("host")));
      if (shareCookiesBetweenApexDomains && nempty(apexDomain))
        cookie.domain = apexDomain;
    }

    ret cookieValue; 
  }
  
  swappable S createNewCookie() {
    ret randomID(20);
  }
}

Author comment

Began life as a copy of #1011963

download  show line numbers  debug dex  old transpilations   

Travelled to 7 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt, xrpafgyirdlv

No comments. add comment

Snippet ID: #1027732
Snippet name: ServeHttp_CookieHandler
Eternal ID of this version: #1027732/14
Text MD5: 184234e2d693f18db3fd78a781db62e1
Transpilation MD5: 2a227370ef5a86a9e61f3dec23a542f1
Author: stefan
Category: eleu / javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2023-06-12 20:11:41
Source code size: 1324 bytes / 40 lines
Pitched / IR pitched: No / No
Views / Downloads: 288 / 671
Version history: 13 change(s)
Referenced in: [show references]