Skip to content

Commit

Permalink
debug token handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Pascal Klesse committed Sep 4, 2024
1 parent cbbbdb8 commit e4d8fec
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
11 changes: 8 additions & 3 deletions src/runtime/composables/gql-mutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import { useAuth } from './use-auth';
export async function gqlMutation<T = any>(method: string, options: IGraphQLOptions = {}): Promise<{ data: T; error: Error }> {
const { $graphql, _meta } = useNuxtApp();
const _nuxtApp = useNuxtApp();
const { accessTokenState, refreshTokenState } = useAuthState();
const { checkTokenAndRenew } = useAuth();
const { accessTokenState, refreshTokenState } = useAuthState();

// Check parameters
if (!method) {
Expand Down Expand Up @@ -125,12 +125,17 @@ export async function gqlMutation<T = any>(method: string, options: IGraphQLOpti
console.debug('gqlMutation::documentNode ', documentNode);
}

let accessToken;
if (method !== 'refreshToken' || !config.disableTokenCheck) {
await callWithNuxt(_nuxtApp, checkTokenAndRenew);
const tokens = await callWithNuxt(_nuxtApp, checkTokenAndRenew);
console.debug('gqlMutation::tokens ', tokens);
if (tokens) {
accessToken = tokens.token;
}
}

const requestHeaders = {
authorization: `Bearer ${method === 'refreshToken' ? refreshTokenState.value : accessTokenState.value}`,
authorization: `Bearer ${method === 'refreshToken' ? refreshTokenState.value : accessToken}`,
};

let data;
Expand Down
10 changes: 8 additions & 2 deletions src/runtime/composables/use-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,17 @@ export function useAuth() {
return result;
}

async function checkTokenAndRenew() {
async function checkTokenAndRenew(): Promise<{
refreshToken: string;
token: string;
} | null> {
const { accessTokenState } = useAuthState();

if (isTokenExpired(accessTokenState.value)) {
await requestNewToken();
return requestNewToken();
}

return null;
}

function setTokens(newToken: string, newRefreshToken: string) {
Expand Down Expand Up @@ -112,6 +117,7 @@ export function useAuth() {
const decoded = getDecodedAccessToken(token);
return decoded?.exp < Date.now() / 1000;
}

return false;
}

Expand Down

0 comments on commit e4d8fec

Please sign in to comment.