|
import React, {createContext, useContext} from 'react'; |
|
import {useMachine} from '@xstate/react'; |
|
import {useHistory} from 'react-router-dom'; |
|
import {Auth} from 'aws-amplify'; |
|
|
|
import {orgMachine} from './organization-machine'; |
|
import {userMachine} from './user-machine'; |
|
import {xeroOrgMachine} from './xero-organization-machine'; |
|
|
|
import {routes} from './routes'; |
|
|
|
/** |
|
* machine services |
|
*/ |
|
const services = { |
|
logOut: () => Auth.signOut(), |
|
orgMachine, |
|
userMachine, |
|
xeroOrgMachine, |
|
}; |
|
|
|
/** |
|
* machine guards |
|
*/ |
|
const guards = { |
|
isAlreadyAuthd = () => { |
|
const authState = // get cognito auth state from localstorage |
|
|
|
return authState === 'signedIn'; |
|
}, |
|
}; |
|
|
|
/** |
|
* machine actions |
|
*/ |
|
const actions = { |
|
redirectToGetUserRoute = ({history}) => { |
|
history.push(routes.authIndex); |
|
}. |
|
|
|
redirectToLoginRoute = ({history}) => { |
|
history.push(routes.login); |
|
}, |
|
}; |
|
|
|
|
|
|
|
const AuthContext = createContext(undefined); |
|
|
|
const AuthProvider = ({children}) => { |
|
const history = useHistory(); |
|
const [current, send] = useMachine(authMachine.withContext({history}), { |
|
actions: authMachineActions, |
|
guards: authMachineGuards, |
|
services: authMachineServices, |
|
}); |
|
const value = { |
|
current, |
|
orgMachine, |
|
send, |
|
userMachine, |
|
xeroOrgMachine, |
|
}; |
|
|
|
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>; |
|
}; |
|
|
|
const useAuthMachine = () => { |
|
const context = useContext(AuthContext); |
|
|
|
if (context === undefined) { |
|
throw new Error('useAuthMachine must be used within an AuthProvider component'); |
|
} |
|
|
|
return context; |
|
}; |
|
|
|
export {AuthContext, AuthProvider, useAuthMachine}; |