From ca130f81ababbd4cde281a768d81d2b9a82e1dc3 Mon Sep 17 00:00:00 2001 From: Justin Campbell Date: Fri, 13 Nov 2020 15:10:45 -0500 Subject: [PATCH] Create base auth utilities -- only login --- src/auth/index.js | 1 + src/auth/utilities.js | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 src/auth/index.js create mode 100644 src/auth/utilities.js diff --git a/src/auth/index.js b/src/auth/index.js new file mode 100644 index 0000000..dad0b46 --- /dev/null +++ b/src/auth/index.js @@ -0,0 +1 @@ +export { login } from "./utilities"; \ No newline at end of file diff --git a/src/auth/utilities.js b/src/auth/utilities.js new file mode 100644 index 0000000..1237078 --- /dev/null +++ b/src/auth/utilities.js @@ -0,0 +1,33 @@ +/** Utility Functions for webqueue2 API */ + + + +/** + * Returns an access token to be used for authorization. + * @example + * login("janeDoe", "superSecretPassword") + * @param {String} username + * @param {String} password + * @returns {Boolean | String} An access token on success, `false` otherwise. + */ +export async function login(username, password){ + const loginInit = { + method: "POST", + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({ "username": username, "password": password}) + }; + + let loginResponse = await fetch("/login", loginInit); + let data = await loginResponse.json(); + + if (data === null){ + return false; + } + if (!loginResponse.ok){ + console.error(`Login failed. Got code ${loginResponse.status} (${loginResponse.statusText})`); + return false; + } + + return data.access_token || false; +} +