2021-09-23 22:37:47 -04:00
|
|
|
import React from 'react';
|
|
|
|
|
|
|
|
import type { UserProfile } from '~/common/user.ts'
|
|
|
|
|
2021-09-23 23:34:33 -04:00
|
|
|
import { subscribeToAuthState } from './api/auth.ts'
|
2021-09-23 22:37:47 -04:00
|
|
|
|
|
|
|
type AuthState =
|
|
|
|
| {loginState: 'pending'}
|
|
|
|
| {loginState: 'logged-out'}
|
2021-09-23 23:34:33 -04:00
|
|
|
| {loginState: 'logged-in'; profile: UserProfile}
|
2021-09-23 22:37:47 -04:00
|
|
|
type UserHandle = AuthState
|
|
|
|
|
|
|
|
const AuthContext = React.createContext<UserHandle | null>(null)
|
|
|
|
|
|
|
|
export function useAuth(): UserHandle {
|
|
|
|
const value = React.useContext(AuthContext)
|
|
|
|
if (value === null) throw new Error('useAuth must be used inside an AuthProvider')
|
|
|
|
return value
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: UPDATE HERE TO ENABLE AUTH
|
2021-09-23 23:34:33 -04:00
|
|
|
const initialAuthState: AuthState = {loginState: 'pending'}
|
2021-09-23 22:37:47 -04:00
|
|
|
|
|
|
|
interface AuthProviderProps {
|
|
|
|
children: React.ReactNode
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Handles authentication and token storage.
|
|
|
|
*
|
|
|
|
* Attaches a provider with login and logout callbacks. Handles authenticating using
|
|
|
|
* a token found in the device keychain and attaching/removing the token on login/logout.
|
|
|
|
*
|
|
|
|
* @props children
|
|
|
|
*/
|
|
|
|
export function AuthProvider({children}: AuthProviderProps): JSX.Element {
|
|
|
|
const [authState, setAuthState] = React.useState<AuthState>(initialAuthState)
|
|
|
|
|
|
|
|
React.useEffect(() => {
|
2021-09-23 23:34:33 -04:00
|
|
|
subscribeToAuthState((user) => {
|
|
|
|
if (user) {
|
|
|
|
setAuthState({
|
|
|
|
loginState: 'logged-in',
|
|
|
|
profile: {displayName: user.displayName.split(' ')[0]},
|
|
|
|
})
|
|
|
|
}
|
|
|
|
else setAuthState({ loginState: 'logged-out' })
|
|
|
|
})
|
2021-09-23 22:37:47 -04:00
|
|
|
}, [])
|
|
|
|
|
|
|
|
return (
|
|
|
|
<AuthContext.Provider value={authState}>
|
|
|
|
{children}
|
|
|
|
</AuthContext.Provider>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
const UserContext = React.createContext<UserProfile | null>(null)
|
|
|
|
|
|
|
|
export function useUser(): UserProfile {
|
|
|
|
const value = React.useContext(UserContext)
|
|
|
|
if (value === null) throw new Error('useUser must be used inside a UserProvider')
|
|
|
|
return value
|
|
|
|
}
|
|
|
|
|
|
|
|
interface UserProviderProps {
|
2021-09-23 23:34:33 -04:00
|
|
|
profile: UserProfile
|
2021-09-23 22:37:47 -04:00
|
|
|
children: React.ReactNode
|
|
|
|
}
|
|
|
|
|
|
|
|
export function UserProvider({children, profile}: UserProviderProps) {
|
|
|
|
return (
|
|
|
|
<UserContext.Provider value={profile}>
|
|
|
|
{children}
|
|
|
|
</UserContext.Provider>
|
|
|
|
)
|
|
|
|
}
|