From 4a79cb42fd5724993a59b2945f411b9e27add7a3 Mon Sep 17 00:00:00 2001 From: Justin Campbell Date: Sun, 15 Nov 2020 23:26:35 -0500 Subject: [PATCH] Add token refresh function to auth utilities --- src/auth/index.js | 2 +- src/auth/utilities.js | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/auth/index.js b/src/auth/index.js index dad0b46..679b398 100644 --- a/src/auth/index.js +++ b/src/auth/index.js @@ -1 +1 @@ -export { login } from "./utilities"; \ No newline at end of file +export { login, refresh } from "./utilities"; \ No newline at end of file diff --git a/src/auth/utilities.js b/src/auth/utilities.js index 1237078..8800954 100644 --- a/src/auth/utilities.js +++ b/src/auth/utilities.js @@ -31,3 +31,29 @@ export async function login(username, password){ return data.access_token || false; } +/** + * Refresh current access token. + * @example + * refresh("csrf_refresh_token") + * @param {String} csrf_refresh_token The current CSRF validation string. + * @returns {Boolean | String} An access token on success, `false` otherwise. + */ +export async function refresh(csrf_refresh_token){ + const refreshInit = { + method: "POST", + headers: {'X-CSRF-TOKEN': csrf_refresh_token}, + }; + + let refreshResponse = await fetch("/tokens/refresh", refreshInit); + let data = await refreshResponse.json(); + + if (data === null){ + return false; + } + if (!refreshResponse.ok){ + console.error(`Refresh failed. Got code ${refreshResponse.status} (${refreshResponse.statusText})`); + return false; + } + + return data.access_token || false; +} \ No newline at end of file