import { useState , useEffect } from 'react' ; import useAttempt from 'shared/hooks/useAttemptNext' ; import Ctx from 'teleport/teleportContext' ; import authService from 'teleport/services/auth' ; import cfg from 'teleport/config' ; export default function useAddDevice ( ctx , { token , fetchDevices , onClose } ) { const [ qrCode , setQrCode ] = useState ( '' ) ; const addDeviceAttempt = useAttempt ( '' ) ; const fetchQrCodeAttempt = useAttempt ( '' ) ; function addTotpDevice ( secondFactorToken , deviceName ) { addDeviceAttempt . setAttempt ( { status : 'processing' } ) ; ctx . mfaService . addNewTotpDevice ( { tokenId : token , secondFactorToken , deviceName , } ) . then ( ( ) => { onClose ( ) ; fetchDevices ( ) ; } ) . catch ( addDeviceAttempt . handleError ) ; } function addU2fDevice ( deviceName ) { addDeviceAttempt . setAttempt ( { status : 'processing' } ) ; ctx . mfaService . addNewU2fDevice ( { tokenId : token , deviceName , } ) . then ( ( ) => { onClose ( ) ; fetchDevices ( ) ; } ) . catch ( addDeviceAttempt . handleError ) ; } function addWebauthnDevice ( deviceName ) { addDeviceAttempt . setAttempt ( { status : 'processing' } ) ; ctx . mfaService . addNewWebauthnDevice ( { tokenId : token , deviceName , } ) . then ( ( ) => { onClose ( ) ; fetchDevices ( ) ; } ) . catch ( addDeviceAttempt . handleError ) ; } function clearAttempt ( ) { addDeviceAttempt . setAttempt ( { status : '' } ) ; } useEffect ( ( ) => { fetchQrCodeAttempt . run ( ( ) => authService . createMfaRegistrationChallenge ( token , 'totp' ) . then ( res => setQrCode ( res . qrCode ) ) ) ; } , [ ] ) ; return { addDeviceAttempt : addDeviceAttempt . attempt , fetchQrCodeAttempt : fetchQrCodeAttempt . attempt , addTotpDevice , addU2fDevice , addWebauthnDevice , onClose , clearAttempt , qrCode , auth2faType : cfg . getAuth2faType ( ) , preferredMfaType : cfg . getPreferredMfaType ( ) , } ; } export type State = ReturnType < typeof useAddDevice > ; export type Props = { token : string ; fetchDevices : ( ) => void ; onClose : ( ) => void ; } ;