Bläddra i källkod

Include csrf helper for api calls

Andrew Swistak 6 år sedan
förälder
incheckning
66524944e5

+ 3 - 0
app/javascript/packs/frontend/graphqlEnvironment.ts

@@ -14,6 +14,8 @@ import {
   Variables,
 } from 'relay-runtime';
 
+import csrf from './lib/utils/csrf';
+
 // 100 cache entries, 300 seconds until cache is invalid.
 export const cache = new QueryResponseCache({size: 100, ttl: 300000});
 
@@ -35,6 +37,7 @@ export const fetchQuery: FetchFunction = (
     method: 'POST',
     headers: {
       'Content-Type': 'application/json',
+      ...csrf.headers,
     },
     body: JSON.stringify({
       query: operation.text,

+ 34 - 0
app/javascript/packs/frontend/lib/utils/csrf.ts

@@ -0,0 +1,34 @@
+// Easily expose and cache CSRF tokens
+
+const csrf = {
+  init(): void {
+    const tokenEl = document.querySelector('meta[name=csrf-token]');
+
+    if (tokenEl !== null) {
+      this.csrfToken = tokenEl.getAttribute('content');
+    } else {
+      this.csrfToken = null;
+    }
+  },
+
+  get token(): string {
+    return this.csrfToken;
+  },
+
+  get headerKey(): string {
+    return 'X-CSRF-Token';
+  },
+
+  get headers(): Record<string, string> {
+    if (this.csrfToken !== null) {
+      return {
+        [this.headerKey]: this.token,
+      };
+    }
+    return {};
+  },
+};
+
+csrf.init();
+
+export default csrf;