import { useState , useEffect } from 'react' ; import useAttempt from 'shared/hooks/useAttemptNext' ; import cfg from 'teleport/config' ; import history from 'teleport/services/history' ; import auth from 'teleport/services/auth' ; export default function useToken ( tokenId ) { const [ passwordToken , setPswToken ] = useState < ResetToken > ( ) ; const fetchAttempt = useAttempt ( '' ) ; const submitAttempt = useAttempt ( '' ) ; const auth2faType = cfg . getAuth2faType ( ) ; useEffect ( ( ) => { fetchAttempt . run ( ( ) => auth . fetchPasswordToken ( tokenId ) . then ( resetToken => setPswToken ( resetToken ) ) ) ; } , [ ] ) ; function onSubmit ( password , otpToken ) { submitAttempt . setAttempt ( { status : 'processing' } ) ; auth . resetPassword ( tokenId , password , otpToken ) . then ( redirect ) . catch ( submitAttempt . handleError ) ; } function onSubmitWithU2f ( password ) { submitAttempt . setAttempt ( { status : 'processing' } ) ; auth . resetPasswordWithU2f ( tokenId , password ) . then ( redirect ) . catch ( submitAttempt . handleError ) ; } function onSubmitWithWebauthn ( password ) { submitAttempt . setAttempt ( { status : 'processing' } ) ; auth . resetPasswordWithWebauthn ( tokenId , password ) . then ( redirect ) . catch ( submitAttempt . handleError ) ; } function redirect ( ) { history . push ( cfg . routes . root , true ) ; } function clearSubmitAttempt ( ) { submitAttempt . setAttempt ( { status : '' } ) ; } return { auth2faType , preferredMfaType : cfg . getPreferredMfaType ( ) , fetchAttempt : fetchAttempt . attempt , submitAttempt : submitAttempt . attempt , clearSubmitAttempt , onSubmit , onSubmitWithU2f , onSubmitWithWebauthn , passwordToken , } ; } type ResetToken = { tokenId : string ; qrCode : string ; user : string ; } ; export type State = ReturnType < typeof useToken > ;