Skip to content

Commit

Permalink
clients/web: make sure a GitHub account is connected before installin…
Browse files Browse the repository at this point in the history
…g app
  • Loading branch information
frankie567 committed Oct 24, 2024
1 parent fabadac commit 84074df
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
32 changes: 29 additions & 3 deletions clients/apps/web/src/hooks/github.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,43 @@
import { useStore } from '@/store'
import { getGitHubAuthorizeURL } from '@/utils/auth'
import { CONFIG } from '@/utils/config'
import { Organization } from '@polar-sh/sdk'
import { useCallback } from 'react'
import { usePathname } from 'next/navigation'
import { useCallback, useEffect } from 'react'
import { useGitHubAccount } from './oauth-accounts'

export const useRedirectToGitHubInstallation = (
organization: Organization,
): (() => void) => {
const store = useStore()
const pathname = usePathname()
const gitHubAccount = useGitHubAccount()
const authorizeURL = getGitHubAuthorizeURL({ returnTo: pathname })

const redirect = useCallback(() => {
store.setGitHubInstallation({ organizationId: organization.id })
if (!gitHubAccount) {
store.setGitHubInstallation({
installAfterGitHubAuthentication: true,
organizationId: organization.id,
})
window.location.href = authorizeURL
return
}
store.setGitHubInstallation({
installAfterGitHubAuthentication: false,
organizationId: organization.id,
})
window.location.href = CONFIG.GITHUB_INSTALLATION_URL
}, [store, organization])
}, [store, authorizeURL, organization, gitHubAccount])

useEffect(() => {
if (
gitHubAccount &&
store.gitHubInstallation?.installAfterGitHubAuthentication === true
) {
redirect()
}
}, [gitHubAccount, store.gitHubInstallation, redirect])

return redirect
}
7 changes: 6 additions & 1 deletion clients/apps/web/src/store/githubInstallation.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { StateCreator } from 'zustand'

interface GitHubInstallation {
installAfterGitHubAuthentication: boolean | undefined
organizationId: string | undefined
}

Expand All @@ -14,6 +15,7 @@ export const createGitHubInstallationSlice: StateCreator<
GitHubInstallationSlice
> = (set) => ({
gitHubInstallation: {
installAfterGitHubAuthentication: undefined,
organizationId: undefined,
},
setGitHubInstallation: (gitHubInstallation) => {
Expand All @@ -23,7 +25,10 @@ export const createGitHubInstallationSlice: StateCreator<
},
clearGitHubInstallation: () => {
set({
gitHubInstallation: { organizationId: undefined },
gitHubInstallation: {
installAfterGitHubAuthentication: undefined,
organizationId: undefined,
},
})
},
})

0 comments on commit 84074df

Please sign in to comment.