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