Created
March 12, 2024 04:19
-
-
Save ravenwilde/ccfa8aa59762d1e5905b41dd597e7a80 to your computer and use it in GitHub Desktop.
JSON Web Token authentication functions for use with WPGraphQL JWT Authentication plugin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const API_URL = process.env.WORDPRESS_API_URL | |
/** | |
* Fetches the API to get the JWT refresh token | |
* @returns {Promise<string>} The JWT refresh token | |
*/ | |
export async function fetchToken() { | |
const query = ` | |
mutation LoginUser($input: LoginInput!) { | |
login(input: $input) { | |
authToken | |
user { | |
id | |
name | |
} | |
} | |
} | |
` | |
const variables = { input: { | |
clientMutationId: v4(), | |
username: process.env.WORDPRESS_USERNAME, | |
password: process.env.WORDPRESS_PASSWORD, | |
} | |
} | |
const res = await fetch(API_URL, { | |
method: 'POST', | |
headers: { 'Content-Type': 'application/json' }, | |
body: JSON.stringify({ | |
query, | |
variables, | |
}), | |
}) | |
const json = await res.json() | |
if (json.data.login) { | |
return json.data.login.authToken | |
} else { | |
throw new Error(`Failed to fetch API token`) | |
} | |
} | |
async function fetchAPI(query = '', { variables }: Record<string, any> = {}) { | |
const headers = { 'Content-Type': 'application/json' } | |
const token = await fetchToken(); | |
if (token) { | |
headers[ | |
'Authorization' | |
] = `Bearer ${token}` | |
} | |
// WPGraphQL Plugin must be enabled | |
const res = await fetch(API_URL, { | |
headers, | |
method: 'POST', | |
body: JSON.stringify({ | |
query, | |
variables, | |
}), | |
}) | |
const json = await res.json() | |
if (json.errors) { | |
console.error(json.errors) | |
throw new Error('Failed to fetch API') | |
} | |
return json.data | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment