feat: Attach the Authorization header if a wpAuthToken is present in the context

This commit is contained in:
2026-03-26 15:32:13 -04:00
parent c9a9e03b60
commit 30c7b8b0b5
6 changed files with 124 additions and 26 deletions

View File

@@ -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;
}