Created
July 28, 2019 12:42
-
-
Save yamitzky/d542f92fb5db602bf5f74cc3c56bf0c1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useCallback, useEffect } from 'react' | |
import { Auth, Hub } from 'aws-amplify' | |
export enum AuthState { | |
SignIn = 'signIn', | |
SignUp = 'signUp', | |
ConfirmSignIn = 'confirmSignIn', | |
ConfirmSignUp = 'confirmSignUp', | |
ForgotPassword = 'forgotPassword', | |
RequireNewPassword = 'requireNewPassword', | |
VerifyContact = 'verifyContact', | |
SignedIn = 'signedIn', | |
Loading = 'loading' | |
} | |
const useAuthenticator = (): [AuthState, any | null] => { | |
const [user, setUser] = useState(null) | |
const [authState, setAuthState] = useState(AuthState.Loading) | |
const checkUser = useCallback(async () => { | |
try { | |
const user = await Auth.currentAuthenticatedUser() | |
setUser(user) | |
setAuthState(AuthState.SignedIn) | |
} catch (e) { | |
console.debug(e) | |
setUser(null) | |
setAuthState(AuthState.SignIn) | |
} | |
}, []) | |
const hubCallback = useCallback( | |
({ payload: { event, data } }) => { | |
console.debug('hub event detected', event, data) | |
let newAuthState = event | |
let newUser = data | |
switch (event) { | |
case 'cognitoHostedUI': | |
newAuthState = AuthState.SignedIn | |
break | |
case 'cognitoHostedUI_failure': | |
case 'parsingUrl_failure': | |
case 'signOut': | |
case 'customGreetingSignOut': | |
newAuthState = AuthState.SignIn | |
newUser = null | |
break | |
// case 'parsingCallbackUrl': | |
// localStorage.setItem(Constants.SIGNING_IN_WITH_HOSTEDUI_KEY, 'true') | |
// break | |
} | |
setAuthState(newAuthState) | |
setUser(newUser) | |
if (newAuthState === AuthState.SignedIn) { | |
checkUser() | |
} | |
}, | |
[checkUser] | |
) | |
useEffect(() => { | |
checkUser() | |
Hub.listen('auth', hubCallback) | |
return () => { | |
Hub.remove('auth', hubCallback) | |
} | |
}, [checkUser, hubCallback]) | |
return [authState, user] | |
} | |
export default useAuthenticator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment