Skip to content

Instantly share code, notes, and snippets.

@yamitzky
Created July 28, 2019 12:42
Show Gist options
  • Save yamitzky/d542f92fb5db602bf5f74cc3c56bf0c1 to your computer and use it in GitHub Desktop.
Save yamitzky/d542f92fb5db602bf5f74cc3c56bf0c1 to your computer and use it in GitHub Desktop.
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