1+ import type FetchError from 'ofetch' ;
12
23export default defineOAuthGitHubEventHandler ( {
34 config : {
45 } ,
56 async onSuccess ( event , { user, tokens } ) {
7+ const config = useRuntimeConfig ( event ) ;
8+ const logger = console ;
9+
610 await setUserSession ( event , {
711 user : {
812 githubId : user . id ,
@@ -15,6 +19,38 @@ export default defineOAuthGitHubEventHandler({
1519 }
1620 }
1721 )
22+
23+ // need to check if this is public app (no default org/team/ent)
24+ if ( config . public . isPublicApp ) {
25+ try {
26+ const installationsResponse = await $fetch ( 'https://api.github.com/user/installations' , {
27+ headers : {
28+ Authorization : `token ${ tokens . access_token } ` ,
29+ Accept : 'application/vnd.github+json' ,
30+ 'X-GitHub-Api-Version' : '2022-11-28'
31+ }
32+ } ) as { installations : Array < { account : { login : string } } > } ;
33+
34+ const installations = installationsResponse . installations ;
35+ const organizations = installations . map ( installation => installation . account . login ) ;
36+
37+ await setUserSession ( event , {
38+ organizations
39+ } ) ;
40+ logger . info ( 'User organizations:' , organizations ) ;
41+
42+ if ( organizations . length === 0 ) {
43+ console . error ( 'No organizations found for the user.' ) ;
44+ return sendRedirect ( event , '/?error=No organizations found for the user.' ) ;
45+ }
46+
47+ return sendRedirect ( event , `/orgs/${ organizations [ 0 ] } ` ) ;
48+ }
49+ catch ( error : FetchError ) {
50+ logger . error ( 'Error fetching installations:' , error ) ;
51+ }
52+ }
53+
1854 return sendRedirect ( event , '/' )
1955 } ,
2056 // Optional, will return a json error and 401 status code by default
0 commit comments