Skip to content

Commit

Permalink
Fix Safari cookie
Browse files Browse the repository at this point in the history
  • Loading branch information
WavJaby committed Aug 30, 2023
1 parent 5d4400f commit 64b640d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
9 changes: 8 additions & 1 deletion res/lib.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,18 @@ export function fetchApi(endpoint, showState, option) {
}
const stateElement = showState ? requestState.addState(showState) : null;

if (isSafari) {
if (!option.headers)
option.headers = {};
option.headers['Safari-Cookie'] = document.cookie;
}

return fetch(apiEndPoint + endpoint, option)
.then(i => {
if (isSafari) {
const c = i.headers.get('Safari-Cookie');
if (c) c.split(',').forEach(i => document.cookie = i);
console.log(c);
if (c) c.split(',').forEach(i => document.cookie = i.replace(/Domain=[\w.]+/, 'Domain=' + window.location.hostname));
}
return i.json()
})
Expand Down
18 changes: 11 additions & 7 deletions src/main/java/com/wavjaby/lib/Cookie.java
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,8 @@ public static void packStudentIdSysLoginStateCookie(HttpExchange req, String org
addCookieToHeader("stuSysLoginData", cookieValue, "/", req);
}

public static String[] splitCookie(Headers requestHeaders) {
String cookie = requestHeaders.getFirst("Cookie");
public static String[] splitCookie(Headers headers) {
String cookie = isSafari(headers) ? headers.getFirst("Safari-Cookie") : headers.getFirst("Cookie");
return cookie == null ? null : cookie.split("; ?");
}

Expand All @@ -167,11 +167,7 @@ public static String getDefaultCookie(Headers requestHeaders, CookieStore cookie

public static void addCookieToHeader(String key, String value, String path, HttpExchange req) {
Headers headers = req.getResponseHeaders();
String userAgent = req.getRequestHeaders().getFirst("User-Agent");
if (userAgent != null &&
userAgent.contains("Safari") && !userAgent.contains("Chrome") &&
!userAgent.contains("CriOS") &&
!userAgent.contains("FxiOS")) {
if (isSafari(req.getRequestHeaders())) {
headers.add("Safari-Cookie", key + '=' + value + "; Path=" + path +
"; SameSite=None; Secure; Domain=" + cookieDomain);
} else {
Expand All @@ -183,4 +179,12 @@ public static void addCookieToHeader(String key, String value, String path, Http
public static void addRemoveCookieToHeader(String key, String path, HttpExchange req) {
addCookieToHeader(key, "; Max-Age=0", path, req);
}

private static boolean isSafari(Headers headers) {
String userAgent = headers.getFirst("User-Agent");
return userAgent != null &&
userAgent.contains("Safari") && !userAgent.contains("Chrome") &&
!userAgent.contains("CriOS") &&
!userAgent.contains("FxiOS");
}
}

0 comments on commit 64b640d

Please sign in to comment.