feat: Attach the Authorization header if a wpAuthToken is present in the context
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
export default defineGraphQLContext(async (event) => {
|
||||
return {};
|
||||
const wpAuthToken = await getAuthToken(event);
|
||||
return { wpAuthToken };
|
||||
});
|
||||
|
||||
12
wp-content/themes/headless/server/graphql/wp-hooks.ts
Normal file
12
wp-content/themes/headless/server/graphql/wp-hooks.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { defu } from "defu";
|
||||
|
||||
export default defineRemoteExecutorHooks({
|
||||
onRequest(request, context) {
|
||||
// Attach the Authorization header if a wpAuthToken is present in the context
|
||||
if (context?.wpAuthToken) {
|
||||
request.extensions = defu(request.extensions, {
|
||||
headers: { Authorization: `Bearer ${context.wpAuthToken}` },
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -1,3 +1,5 @@
|
||||
import { jwtDecode } from "jwt-decode";
|
||||
|
||||
import type { AuthPayloadFragment, AuthUserFragment } from "#graphql/types";
|
||||
import type { H3Event } from "h3";
|
||||
|
||||
@@ -47,3 +49,26 @@ function getAuthUser(user: AuthUserFragment) {
|
||||
roles: user.roles.nodes.map(({ name }) => name) || [],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the authentication token from the user's session, checking for expiration and handling token refresh if necessary.
|
||||
*
|
||||
* @param event The H3 event object, used to access the user's session data.
|
||||
* @returns A promise that resolves to the authentication token if it is valid, or undefined if there is no valid token or if the user is not authenticated.
|
||||
*/
|
||||
export async function getAuthToken(event: H3Event) {
|
||||
// Retrieve user session, return if none
|
||||
const session = await getUserSession(event);
|
||||
if (!session.secure) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Extract tokens and check expiration
|
||||
const decoded = jwtDecode<{ exp: number }>(session.secure.authToken);
|
||||
const isExpired = decoded.exp * 1000 < Date.now();
|
||||
if (isExpired) {
|
||||
// TOOD: Refresh token logic
|
||||
}
|
||||
|
||||
return session.secure.authToken;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user