From 93dfe2be64e8658839bcfe5356adf35f8cde7075 Mon Sep 17 00:00:00 2001
From: Nicolas James <Eele1Ephe7uZahRie@tutanota.com>
Date: Thu, 13 Feb 2025 18:04:18 +1100
Subject: initial commit

---
 src/web/helpers/Auth.jsx | 66 ++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 66 insertions(+)
 create mode 100644 src/web/helpers/Auth.jsx

(limited to 'src/web/helpers/Auth.jsx')

diff --git a/src/web/helpers/Auth.jsx b/src/web/helpers/Auth.jsx
new file mode 100644
index 0000000..bbbe577
--- /dev/null
+++ b/src/web/helpers/Auth.jsx
@@ -0,0 +1,66 @@
+import {getCookie, setCookie} from "react-use-cookie";
+import jwtDecode from "jwt-decode";
+
+export async function refreshToken({user, setUser}) {
+    const init = {
+        method: "POST",
+        referrer: "same-origin",
+    };
+    return fetch("/api/refresh", init)
+        .then((response) => {
+            if (!response.ok) {
+                throw new Error("server rejected refresh");
+            }
+            const user = maybeGetUser();
+            if (user == null) {
+                throw new Error("bad token response");
+            }
+            setUser(user);
+        })
+        .catch((error) => {
+            console.log(error);
+            setUser(null);
+        })
+} 
+
+export function maybeGetUser() {
+    const token = getCookie("token");
+    if (token == null || token == "") {
+        return null;
+    }
+
+    const jwt = jwtDecode(token);
+    if (jwt.iss !== "react-go-forum") {
+        return null;
+    }
+
+    const expiry_date = (() => {
+        var time = new Date(Date.UTC, 0, 1);
+        time.setUTCSeconds(jwt.exp);
+        return time;
+    })();
+    if (expiry_date <= new Date(Date.now())) {
+        return null;
+    }
+
+    return {
+        id: jwt.sub,
+        expiry: expiry_date,
+    }
+}
+
+export function maybeAuthFromCookie(userState) {
+    const user = maybeGetUser();
+    if (user == null) {
+        return false;
+    }
+
+    const [_, setUser] = userState;
+    setUser(user);
+    return true;
+}
+
+export function logout(setUser) {
+    setCookie("token", "", {path: "/"});
+    setUser(null);
+}
\ No newline at end of file
-- 
cgit v1.2.3

