aboutsummaryrefslogtreecommitdiff
path: root/app/static/js/jwt.js
diff options
context:
space:
mode:
authorParker <contact@pkrm.dev>2024-11-08 23:07:20 -0600
committerParker <contact@pkrm.dev>2024-11-08 23:07:20 -0600
commit8941213c8d94f3ad84e07e467e78105dc7fed734 (patch)
tree0ae32555276432b4ddb04a7548ffe2e40904f897 /app/static/js/jwt.js
parent3cde652d52985365d1daf370065753f54e765f9d (diff)
Mainly auth re-thinking - just in thought
Diffstat (limited to 'app/static/js/jwt.js')
-rw-r--r--app/static/js/jwt.js58
1 files changed, 58 insertions, 0 deletions
diff --git a/app/static/js/jwt.js b/app/static/js/jwt.js
new file mode 100644
index 0000000..1e07703
--- /dev/null
+++ b/app/static/js/jwt.js
@@ -0,0 +1,58 @@
+// Description: This file contains functions to access the API with JWT authentication.
+
+/**
+ * Accept a full URL, method, and body to send to the API.
+ * - If successful, return the response
+ * - If first fail, attempt to refresh JWT token and try again
+ * - If second fail, return false
+ * @param {*} endpoint API endpoint
+ * @param {*} method String (GET, POST, PUT, DELETE)
+ * @param {*} body Data to send to the API
+ * @returns boolean
+ */
+async function accessAPI(endpoint, method, body) {
+ let response = await fetch(`/api${endpoint}`, {
+ method: method,
+ body: body,
+ });
+
+ if (response.ok) {
+ let data = await response.json();
+ data = await data;
+ console.log(data);
+ return data;
+ } else if (response.status === 401) {
+ console.log('REFRESHING TOKEN')
+ if (await refreshAccessToken()) {
+ // Try the request again
+ let response = await fetch(`/api${endpoint}`, {
+ method: method,
+ body: body,
+ });
+ if (response.ok) {
+ let data = await response.json();
+ data = await data;
+ console.log("REFRESHED DATA")
+ return data;
+ }
+ }
+ }
+ return false;
+}
+
+/**
+ * Attempt to refresh the JWT token
+ * @returns boolean
+ */
+async function refreshAccessToken () {
+ const response = await fetch('/api/auth/refresh', {
+ method: 'POST',
+ });
+ if (response.ok) {
+ console.log("TOKEN REFRESH")
+ return true;
+ } else {
+ console.log("TOKEN REFRESH FAILED")
+ return false;
+ }
+} \ No newline at end of file