-
Notifications
You must be signed in to change notification settings - Fork 2.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: add renew token query for apollo client (chrome-extension) #5200
Merged
FelixMalfait
merged 7 commits into
twentyhq:main
from
AdityaPimpalkar:chrome-renew-token
May 16, 2024
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
3db2df6
renew token query on apollo client
AdityaPimpalkar b03cc9b
Merge branch 'main' into chrome-renew-token
AdityaPimpalkar 1e2e456
Merge branch 'main' into chrome-renew-token
AdityaPimpalkar 0f18f8e
add "ExchangeAuthorizationCode" to TokenMiddleware
AdityaPimpalkar c9ffee9
refacto Renew token query to mutation
AdityaPimpalkar ed38d8f
set authLink with renewToken for apolloClient
AdityaPimpalkar bf3c43d
lint fix
AdityaPimpalkar File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import { ApolloClient, InMemoryCache } from '@apollo/client'; | ||
|
||
import { Tokens } from '~/db/types/auth.types'; | ||
import { RENEW_TOKEN } from '~/graphql/auth/mutations'; | ||
import { isDefined } from '~/utils/isDefined'; | ||
|
||
export const renewToken = async ( | ||
appToken: string, | ||
): Promise<{ renewToken: { tokens: Tokens } } | null> => { | ||
const store = await chrome.storage.local.get(); | ||
const serverUrl = `${ | ||
isDefined(store.serverBaseUrl) | ||
? store.serverBaseUrl | ||
: import.meta.env.VITE_SERVER_BASE_URL | ||
}/graphql`; | ||
|
||
// Create new client to call refresh token graphql mutation | ||
const client = new ApolloClient({ | ||
uri: serverUrl, | ||
cache: new InMemoryCache({}), | ||
}); | ||
|
||
const { data } = await client.mutate({ | ||
mutation: RENEW_TOKEN, | ||
variables: { | ||
appToken, | ||
}, | ||
fetchPolicy: 'network-only', | ||
}); | ||
|
||
if (isDefined(data)) { | ||
return data; | ||
} else { | ||
return null; | ||
} | ||
}; |
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
20 changes: 0 additions & 20 deletions
20
packages/twenty-chrome-extension/src/graphql/auth/queries.ts
This file was deleted.
Oops, something went wrong.
137 changes: 93 additions & 44 deletions
137
packages/twenty-chrome-extension/src/utils/apolloClient.ts
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,72 +1,121 @@ | ||
import { ApolloClient, from, HttpLink, InMemoryCache } from '@apollo/client'; | ||
import { | ||
ApolloClient, | ||
from, | ||
fromPromise, | ||
HttpLink, | ||
InMemoryCache, | ||
} from '@apollo/client'; | ||
import { setContext } from '@apollo/client/link/context'; | ||
import { onError } from '@apollo/client/link/error'; | ||
|
||
import { renewToken } from '~/db/token.db'; | ||
import { Tokens } from '~/db/types/auth.types'; | ||
import { isDefined } from '~/utils/isDefined'; | ||
|
||
const clearStore = () => { | ||
chrome.storage.local.remove('loginToken'); | ||
|
||
chrome.storage.local.remove('accessToken'); | ||
|
||
chrome.storage.local.remove('refreshToken'); | ||
|
||
chrome.storage.local.remove(['loginToken', 'accessToken', 'refreshToken']); | ||
chrome.storage.local.set({ isAuthenticated: false }); | ||
}; | ||
|
||
const getApolloClient = async () => { | ||
const setStore = (tokens: Tokens) => { | ||
if (isDefined(tokens.loginToken)) { | ||
chrome.storage.local.set({ | ||
loginToken: tokens.loginToken, | ||
}); | ||
} | ||
chrome.storage.local.set({ | ||
accessToken: tokens.accessToken, | ||
refreshToken: tokens.refreshToken, | ||
}); | ||
}; | ||
|
||
export const getServerUrl = async () => { | ||
const store = await chrome.storage.local.get(); | ||
const serverUrl = `${ | ||
isDefined(store.serverBaseUrl) | ||
? store.serverBaseUrl | ||
: import.meta.env.VITE_SERVER_BASE_URL | ||
}/graphql`; | ||
return serverUrl; | ||
}; | ||
|
||
const errorLink = onError(({ graphQLErrors, networkError }) => { | ||
if (isDefined(graphQLErrors)) { | ||
for (const graphQLError of graphQLErrors) { | ||
if (graphQLError.message === 'Unauthorized') { | ||
//TODO: replace this with renewToken mutation | ||
clearStore(); | ||
return; | ||
} | ||
switch (graphQLError?.extensions?.code) { | ||
case 'UNAUTHENTICATED': { | ||
//TODO: replace this with renewToken mutation | ||
clearStore(); | ||
break; | ||
const getAuthToken = async () => { | ||
const store = await chrome.storage.local.get(); | ||
if (isDefined(store.accessToken)) return `Bearer ${store.accessToken.token}`; | ||
else return ''; | ||
}; | ||
|
||
const getApolloClient = async () => { | ||
const store = await chrome.storage.local.get(); | ||
|
||
const authLink = setContext(async (_, { headers }) => { | ||
const token = await getAuthToken(); | ||
return { | ||
headers: { | ||
...headers, | ||
authorization: token, | ||
}, | ||
}; | ||
}); | ||
const errorLink = onError( | ||
({ graphQLErrors, networkError, forward, operation }) => { | ||
if (isDefined(graphQLErrors)) { | ||
for (const graphQLError of graphQLErrors) { | ||
if (graphQLError.message === 'Unauthorized') { | ||
return fromPromise( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There might be a problem here, because the server doesn't necessarily returns this exact error. I'm looking into it, might be a problem of guard. |
||
renewToken(store.refreshToken.token) | ||
.then((response) => { | ||
if (isDefined(response)) { | ||
setStore(response.renewToken.tokens); | ||
} | ||
}) | ||
.catch(() => { | ||
clearStore(); | ||
}), | ||
).flatMap(() => forward(operation)); | ||
} | ||
switch (graphQLError?.extensions?.code) { | ||
case 'UNAUTHENTICATED': { | ||
return fromPromise( | ||
renewToken(store.refreshToken.token) | ||
.then((response) => { | ||
if (isDefined(response)) { | ||
setStore(response.renewToken.tokens); | ||
} | ||
}) | ||
.catch(() => { | ||
clearStore(); | ||
}), | ||
).flatMap(() => forward(operation)); | ||
} | ||
default: | ||
// eslint-disable-next-line no-console | ||
console.error( | ||
`[GraphQL error]: Message: ${graphQLError.message}, Location: ${ | ||
graphQLError.locations | ||
? JSON.stringify(graphQLError.locations) | ||
: graphQLError.locations | ||
}, Path: ${graphQLError.path}`, | ||
); | ||
break; | ||
} | ||
default: | ||
// eslint-disable-next-line no-console | ||
console.error( | ||
`[GraphQL error]: Message: ${graphQLError.message}, Location: ${ | ||
graphQLError.locations | ||
? JSON.stringify(graphQLError.locations) | ||
: graphQLError.locations | ||
}, Path: ${graphQLError.path}`, | ||
); | ||
break; | ||
} | ||
} | ||
} | ||
|
||
if (isDefined(networkError)) { | ||
// eslint-disable-next-line no-console | ||
console.error(`[Network error]: ${networkError}`); | ||
} | ||
}); | ||
if (isDefined(networkError)) { | ||
// eslint-disable-next-line no-console | ||
console.error(`[Network error]: ${networkError}`); | ||
} | ||
}, | ||
); | ||
|
||
const httpLink = new HttpLink({ | ||
uri: serverUrl, | ||
headers: isDefined(store.accessToken) | ||
? { | ||
Authorization: `Bearer ${store.accessToken.token}`, | ||
} | ||
: {}, | ||
uri: await getServerUrl(), | ||
}); | ||
|
||
const client = new ApolloClient({ | ||
cache: new InMemoryCache(), | ||
link: from([errorLink, httpLink]), | ||
link: from([errorLink, authLink, httpLink]), | ||
}); | ||
|
||
return client; | ||
|
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
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
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Shouldn't we return null instead to signify that we couldn't get it ? Seems that '' will create a silent error.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Better to return null 👍
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Seems like HttpLink shouldn't be created if we don't have any accessToken, but instead redirect to the login page no ?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, that's the plan! We currently don't have any routing in place though its next on the agenda :)