2025-06-19 16:52:22 -07:00
/ * *
* @license
* Copyright 2025 Google LLC
* SPDX - License - Identifier : Apache - 2.0
* /
import { useState , useCallback , useEffect } from 'react' ;
import { LoadedSettings , SettingScope } from '../../config/settings.js' ;
2025-06-20 01:30:06 -07:00
import {
AuthType ,
Config ,
clearCachedCredentialFile ,
getErrorMessage ,
2025-06-25 05:41:11 -07:00
} from '@google/gemini-cli-core' ;
2025-06-19 16:52:22 -07:00
async function performAuthFlow ( authMethod : AuthType , config : Config ) {
await config . refreshAuth ( authMethod ) ;
console . log ( ` Authenticated via " ${ authMethod } ". ` ) ;
}
export const useAuthCommand = (
settings : LoadedSettings ,
setAuthError : ( error : string | null ) = > void ,
config : Config ,
) = > {
const [ isAuthDialogOpen , setIsAuthDialogOpen ] = useState (
settings . merged . selectedAuthType === undefined ,
) ;
const openAuthDialog = useCallback ( ( ) = > {
setIsAuthDialogOpen ( true ) ;
} , [ ] ) ;
2025-06-20 10:46:41 -07:00
const [ isAuthenticating , setIsAuthenticating ] = useState ( false ) ;
2025-06-20 01:30:06 -07:00
useEffect ( ( ) = > {
const authFlow = async ( ) = > {
if ( isAuthDialogOpen || ! settings . merged . selectedAuthType ) {
return ;
}
try {
2025-06-20 10:46:41 -07:00
setIsAuthenticating ( true ) ;
2025-06-20 01:30:06 -07:00
await performAuthFlow (
settings . merged . selectedAuthType as AuthType ,
config ,
) ;
} catch ( e ) {
const errorMessage =
settings . merged . selectedAuthType ===
AuthType . LOGIN_WITH_GOOGLE_PERSONAL
2025-06-25 09:11:54 -07:00
? ` Failed to login. Ensure the Google account you are using is not a Workspace account and that you are not a licensed Code Assist user (see https://goo.gle/gemini-cli-auth-docs#workspace-gca).
2025-06-20 01:30:06 -07:00
Message : $ { getErrorMessage ( e ) } `
: ` Failed to login. Message: ${ getErrorMessage ( e ) } ` ;
setAuthError ( errorMessage ) ;
openAuthDialog ( ) ;
2025-06-20 10:46:41 -07:00
} finally {
setIsAuthenticating ( false ) ;
2025-06-20 01:30:06 -07:00
}
} ;
void authFlow ( ) ;
} , [ isAuthDialogOpen , settings , config , setAuthError , openAuthDialog ] ) ;
2025-06-19 16:52:22 -07:00
const handleAuthSelect = useCallback (
async ( authMethod : string | undefined , scope : SettingScope ) = > {
if ( authMethod ) {
await clearCachedCredentialFile ( ) ;
settings . setValue ( scope , 'selectedAuthType' , authMethod ) ;
}
setIsAuthDialogOpen ( false ) ;
setAuthError ( null ) ;
} ,
[ settings , setAuthError ] ,
) ;
const handleAuthHighlight = useCallback ( ( _authMethod : string | undefined ) = > {
// For now, we don't do anything on highlight.
} , [ ] ) ;
2025-06-20 10:46:41 -07:00
const cancelAuthentication = useCallback ( ( ) = > {
setIsAuthenticating ( false ) ;
} , [ ] ) ;
2025-06-19 16:52:22 -07:00
return {
isAuthDialogOpen ,
openAuthDialog ,
handleAuthSelect ,
handleAuthHighlight ,
2025-06-20 10:46:41 -07:00
isAuthenticating ,
cancelAuthentication ,
2025-06-19 16:52:22 -07:00
} ;
} ;