working authenticationwrapper

This commit is contained in:
Michael Fatemi 2021-04-10 16:46:55 -04:00
parent 3e84fc1b9d
commit 8f11ed7947
4 changed files with 25 additions and 12 deletions

View File

@ -10,10 +10,10 @@ export type AuthState = {
refreshAuthState: (() => void) | null;
};
const AuthContext = createContext<AuthState>({
const Authentication = createContext<AuthState>({
isLoggedIn: false,
user: null,
refreshAuthState: null,
});
export default AuthContext;
export default Authentication;

View File

@ -1,6 +1,6 @@
import { useCallback, useEffect, useState } from 'react';
import { getMe } from '../api/api';
import AuthContext, { AuthState } from './AuthenticationContext';
import Authentication, { AuthState } from './AuthenticationContext';
export default function AuthenticationWrapper({
children,
@ -18,7 +18,11 @@ export default function AuthenticationWrapper({
const refreshAuthState = useCallback(() => {
if (sessionId) {
getMe().then((user) => {
setAuthState({ isLoggedIn: true, user, refreshAuthState });
if (user) {
setAuthState({ isLoggedIn: true, user, refreshAuthState });
} else {
setAuthState({ isLoggedIn: false, user: null, refreshAuthState });
}
});
} else {
setAuthState({ isLoggedIn: false, user: null, refreshAuthState });
@ -33,7 +37,9 @@ export default function AuthenticationWrapper({
return null;
} else {
return (
<AuthContext.Provider value={authState}>{children}</AuthContext.Provider>
<Authentication.Provider value={authState}>
{children}
</Authentication.Provider>
);
}
}

View File

@ -1,7 +1,10 @@
import { ION_AUTHORIZATION_ENDPOINT } from '../api/api';
import Button from '@material-ui/core/Button';
import { useContext } from 'react';
import { ION_AUTHORIZATION_ENDPOINT } from '../api/api';
import AuthenticationContext from './AuthenticationContext';
export default function Home() {
const { user, isLoggedIn } = useContext(AuthenticationContext);
return (
<div
style={{
@ -12,11 +15,15 @@ export default function Home() {
>
<h1>Home</h1>
<div style={{ display: 'flex', flexDirection: 'row' }}>
<Button
onClick={() => (window.location.href = ION_AUTHORIZATION_ENDPOINT)}
>
Sign In with Ion
</Button>
{!isLoggedIn ? (
<Button
onClick={() => (window.location.href = ION_AUTHORIZATION_ENDPOINT)}
>
Sign In with Ion
</Button>
) : (
'Hello ' + user?.first_name + '!'
)}
</div>
<div className="d-flex flex-column">
<section

View File

@ -1,3 +1,3 @@
export default function getSessionId() {
return localStorage.getItem('session_id');
return localStorage.getItem('session_token');
}