update to js
This commit is contained in:
59
dashboard_js/app/hooks/use-auth.jsx
Normal file
59
dashboard_js/app/hooks/use-auth.jsx
Normal file
@@ -0,0 +1,59 @@
|
||||
import {
|
||||
useContext,
|
||||
useMemo,
|
||||
useCallback,
|
||||
createContext,
|
||||
useState,
|
||||
} from 'react'
|
||||
import * as Auth from 'aws-amplify/auth'
|
||||
|
||||
const AuthContext = createContext(null)
|
||||
|
||||
export function useAuth() {
|
||||
const ctx = useContext(AuthContext)
|
||||
|
||||
if (!ctx) {
|
||||
throw new Error('useAuth must be used within an AuthProvider')
|
||||
}
|
||||
|
||||
return ctx
|
||||
}
|
||||
|
||||
export function AuthProvider({ children }) {
|
||||
const [authUser, setAuthUser] = useState(null)
|
||||
|
||||
const signIn = useCallback(async ({ username, password }) => {
|
||||
const signInOut = await Auth.signIn({
|
||||
username,
|
||||
password,
|
||||
options: {
|
||||
clientMetadata: {},
|
||||
},
|
||||
})
|
||||
|
||||
if (signInOut?.isSignedIn) {
|
||||
setAuthUser(await Auth.fetchUserAttributes())
|
||||
}
|
||||
|
||||
return signInOut
|
||||
}, [])
|
||||
|
||||
const signOut = useCallback(async () => {
|
||||
try {
|
||||
return await Auth.signOut()
|
||||
} catch {}
|
||||
}, [])
|
||||
|
||||
const authContext = useMemo(
|
||||
() => ({
|
||||
authUser,
|
||||
signIn,
|
||||
signOut,
|
||||
}),
|
||||
[authUser, signIn, signOut],
|
||||
)
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={authContext}>{children}</AuthContext.Provider>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user