feat: Attach the Authorization header if a wpAuthToken is present in the context
This commit is contained in:
@@ -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