|
|
import debugFactory from 'debug'; |
|
|
import { useEffect, useState } from 'react'; |
|
|
import DesktopLoginStart from 'calypso/login/desktop-login/start'; |
|
|
import WpcomLoginForm from 'calypso/signup/wpcom-login-form'; |
|
|
|
|
|
const debug = debugFactory( 'calypso:desktop' ); |
|
|
|
|
|
interface Props { |
|
|
accessToken: string; |
|
|
error?: string; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export default function DesktopLoginFinalize( props: Props ) { |
|
|
const { accessToken } = props; |
|
|
const [ username, setUsername ] = useState< string >(); |
|
|
const [ error, setError ] = useState< string | undefined >( |
|
|
props.error ?? ! accessToken ? 'Access token is missing' : undefined |
|
|
); |
|
|
|
|
|
if ( error ) { |
|
|
debug( error ); |
|
|
} |
|
|
|
|
|
useEffect( () => { |
|
|
if ( ! error && accessToken && ! username ) { |
|
|
debug( 'Retrieving username from the API' ); |
|
|
getUsername( accessToken ) |
|
|
.then( setUsername ) |
|
|
.catch( () => setError( 'Failed to retrieve username' ) ); |
|
|
} |
|
|
}, [ error, accessToken, username ] ); |
|
|
|
|
|
if ( error ) { |
|
|
|
|
|
|
|
|
return <DesktopLoginStart error={ error } />; |
|
|
} |
|
|
|
|
|
if ( ! username ) { |
|
|
|
|
|
return undefined; |
|
|
} |
|
|
|
|
|
return ( |
|
|
<WpcomLoginForm |
|
|
log={ username } |
|
|
authorization={ 'Bearer ' + accessToken } |
|
|
redirectTo={ window.location.href } |
|
|
rememberMe |
|
|
/> |
|
|
); |
|
|
} |
|
|
|
|
|
async function getUsername( accessToken: string ): Promise< string > { |
|
|
const response = await fetch( 'https://public-api.wordpress.com/rest/v1/me', { |
|
|
headers: { |
|
|
Authorization: `Bearer ${ accessToken }`, |
|
|
}, |
|
|
} ); |
|
|
if ( ! response.ok ) { |
|
|
throw new Error( `Failed to retrieve username: ${ response.status }` ); |
|
|
} |
|
|
return ( await response.json() ).username; |
|
|
} |
|
|
|