Last active
August 1, 2021 19:58
-
-
Save saleebm/e6855debe058cae2d675518bcf135ece to your computer and use it in GitHub Desktop.
Auth Links for Apollo for WP-GraphQL
This file contains 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
import { setContext } from '@apollo/link-context' | |
import { ApolloLink, ExecutionResult } from '@apollo/client' | |
import { authService } from '@Services' | |
export const authLinkMiddleware = setContext( | |
async (_, { headers }) => { | |
// get the authentication token from cookie storage if it exists | |
const token = await authService.getAccessToken() | |
if (!!token) { | |
return { | |
headers: { | |
...(token ? { authorization: `Bearer ${token}` } : {}), | |
...headers, | |
}, | |
} | |
} | |
return { headers } | |
}, | |
) | |
/** | |
* gets the header tokens as a nice way to refresh | |
*/ | |
export const authLinkAfterware = new ApolloLink( | |
(operation, forward) => | |
forward(operation).map( | |
( | |
response: ExecutionResult & { | |
extensions?: Record<string, any> | |
context?: Record<string, any> | |
}, | |
) => { | |
const ctx = operation.getContext() | |
const res = ctx.response | |
try { | |
// Do we have a response? | |
if (res) { | |
const { headers } = res | |
// Do we have headers with refresh token | |
if (!!headers.get('X-JWT-Refresh')) { | |
// Extract tokens from Headers & save them | |
//todo this does not work | |
// const token = headers.get('X-JWT-Auth') | |
// console.log(`token: ${token}`) | |
// get refresh token. | |
const refreshToken = headers.get('X-JWT-Refresh') | |
if (!!refreshToken) { | |
console.log('setting refresh token in afterware') | |
authService.setRefreshToken( | |
refreshToken, | |
undefined, | |
ctx as any, | |
) | |
} | |
} | |
} | |
} catch (e) { | |
console.log(e) | |
} | |
return response | |
}, | |
), | |
) |
This file contains 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
import fetch from 'isomorphic-unfetch' | |
import { v4 as uuid } from 'uuid' | |
const fetchNewAccessToken: FetchNewAccessToken = async (currentRefreshToken) => { | |
// console.log(`Refresh token: ${currentRefreshToken}`) | |
try { | |
const fetchResult = await fetch(GRAPHQL_ENDPOINT, { | |
method: 'POST', | |
headers: { 'Content-Type': 'application/json', 'credentials': 'same-origin' }, | |
body: JSON.stringify({ | |
query: ` | |
mutation refreshJwtAuthToken { | |
refreshJwtAuthToken(input: { | |
clientMutationId: "${uuid()}", | |
jwtRefreshToken: "${currentRefreshToken}" | |
}) { | |
authToken | |
} | |
} | |
`, | |
}), | |
}) | |
const refreshResponse = await fetchResult.json() | |
console.log( | |
`Refresh token response: ${refreshResponse.data?.refreshJwtAuthToken?.authToken}`, | |
) | |
if (!refreshResponse?.data?.refreshJwtAuthToken?.authToken) { | |
return undefined | |
} | |
return refreshResponse.data.refreshJwtAuthToken.authToken | |
} catch (e) { | |
console.error('Failed to fetch fresh access token', e) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment