@@ -3,9 +3,12 @@ import open from 'open';
33import pc from 'picocolors' ;
44import jwtDecode from 'jwt-decode' ;
55import inquirer from 'inquirer' ;
6+ import { EnumStatusCode } from '@wundergraph/cosmo-connect/dist/common/common_pb' ;
7+ import ora from 'ora' ;
68import { BaseCommandOptions } from '../../../core/types/types.js' ;
79import { DecodedAccessToken , performDeviceAuth , startPollingForAccessToken } from '../utils.js' ;
810import { updateConfigFile } from '../../../utils.js' ;
11+ import { getBaseHeaders } from '../../../core/config.js' ;
912
1013export default ( opts : BaseCommandOptions ) => {
1114 const loginCommand = new Command ( 'login' ) ;
@@ -45,16 +48,51 @@ export default (opts: BaseCommandOptions) => {
4548 program . error ( 'Could not perform authentication. Please try again' ) ;
4649 }
4750
48- const organizations = new Set ( decoded . groups . map ( ( group ) => group . split ( '/' ) [ 1 ] ) ) ;
51+ const organizationSlugs = new Set ( decoded . groups . map ( ( group ) => group . split ( '/' ) [ 1 ] ) ) ;
52+
53+ const organizationSlugByDisplayKey = new Map < string , string > ( ) ;
54+ const organizationKeys : Array < string > = [ ] ;
55+ const spinner = ora ( 'Fetching organizations...' ) . start ( ) ;
56+ for ( const organizationSlug of organizationSlugs ) {
57+ const headers = getBaseHeaders ( ) ;
58+ const response = await opts . client . platform . getOrganizationBySlug (
59+ {
60+ slug : organizationSlug ,
61+ } ,
62+ {
63+ headers : {
64+ ...headers ,
65+ authorization : `Bearer ${ accessTokenResp . response . accessToken } ` ,
66+ 'cosmo-org-slug' : organizationSlug ,
67+ } ,
68+ } ,
69+ ) ;
70+ if ( ! response . response || response . response . code !== EnumStatusCode . OK || ! response . organization ) {
71+ organizationKeys . push ( organizationSlug ) ;
72+ organizationSlugByDisplayKey . set ( organizationSlug , organizationSlug ) ;
73+ continue ;
74+ }
75+ const organizationKey = `${ response . organization . name } (${ organizationSlug } )` ;
76+ organizationKeys . push ( organizationKey ) ;
77+ organizationSlugByDisplayKey . set ( organizationKey , organizationSlug ) ;
78+ }
79+
80+ spinner . stop ( ) ;
4981
5082 const selectedOrganization = await inquirer . prompt ( {
51- name : 'organizationSlug ' ,
83+ name : 'organizationKey ' ,
5284 type : 'list' ,
5385 message : 'Select Organization:' ,
54- choices : [ ... organizations ] ,
86+ choices : organizationKeys ,
5587 } ) ;
5688
57- updateConfigFile ( { ...accessTokenResp . response , organizationSlug : selectedOrganization . organizationSlug } ) ;
89+ const organizationSlug = organizationSlugByDisplayKey . get ( selectedOrganization . organizationKey ) ;
90+
91+ if ( ! organizationSlug ) {
92+ program . error ( 'Unable to login.' ) ;
93+ }
94+
95+ updateConfigFile ( { ...accessTokenResp . response , organizationSlug } ) ;
5896
5997 console . log ( pc . green ( 'Logged in Successfully!' ) ) ;
6098 } ) ;
0 commit comments