Skip to content

Commit

Permalink
Preventing multiple calls to the same methods in CSP OAuth flow
Browse files Browse the repository at this point in the history
  • Loading branch information
nigeon authored and elboletaire committed Jan 8, 2024
1 parent f0ec92e commit f4a17fc
Showing 1 changed file with 23 additions and 19 deletions.
42 changes: 23 additions & 19 deletions packages/react-providers/src/election/use-election-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export const useElectionProvider = ({
sik: { password, signature },
} = state
const [anonCircuitsFetched, setAnonCircuitsFetched] = useState(false)
const [oAuthMessage, setOAuthMessage] = useState<{ code: string; handler: string } | undefined>()

const isAnonCircuitsFetching = useRef(false)

Expand Down Expand Up @@ -196,27 +197,25 @@ export const useElectionProvider = ({
}, [autoUpdate, autoUpdateInterval, election])

// CSP OAuth flow
// Listening for the popup window meessage
// Listening for the popup window message
useEffect(() => {
;(async () => {
const handleMessage = (event: any) => {
if (event.data.code && event.data.handler) {
getOAuthToken(event.data.code, event.data.handler)
}
const handleMessage = (event: any) => {
if (event.data.code && event.data.handler) {
setOAuthMessage(event.data)
}
}

if (window.opener || !client || election?.census?.type !== CensusType.CSP) {
return
}
if (window.opener) {
return
}

window.addEventListener('message', handleMessage)
window.addEventListener('message', handleMessage)

return () => {
window.removeEventListener('message', handleMessage)
}
})()
return () => {
window.removeEventListener('message', handleMessage)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [client, election?.census?.type])
}, [])

// CSP OAuth flow
// Posting the message to the main window
Expand All @@ -238,6 +237,14 @@ export const useElectionProvider = ({
})()
}, [])

// CSP OAuth flow
// Handling message callback preventing multiple calls
useEffect(() => {
if (!oAuthMessage?.code || !oAuthMessage?.handler) return
getOAuthToken(oAuthMessage.code, oAuthMessage.handler)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [oAuthMessage])

// context vote function (the one to be used with the given components)
const vote = async (values: number[]) => {
if (!client) {
Expand Down Expand Up @@ -356,10 +363,7 @@ export const useElectionProvider = ({
// CSP OAuth flow
const getOAuthToken = useCallback(
async (code: string, handler: string) => {
if (csp.token) {
return
}

if (!client || csp.token) return
if (!code) {
throw new Error('no code provided')
}
Expand Down

0 comments on commit f4a17fc

Please sign in to comment.