Add better error handling for authentication

This commit is contained in:
Michael Fatemi 2021-07-06 20:32:37 -04:00
parent 009b799a99
commit 1fbbf5904a

View File

@ -3,17 +3,18 @@ import { Redirect, useLocation, useParams } from 'react-router-dom';
import AuthenticationContext from './AuthenticationContext'; import AuthenticationContext from './AuthenticationContext';
import { createSession } from './createSession'; import { createSession } from './createSession';
function useCode() { function useCodeAndError() {
const location = useLocation(); const location = useLocation();
const query = new URLSearchParams(location.search); const query = new URLSearchParams(location.search);
const code = query.get('code'); const code = query.get('code');
const error = query.get('error');
return code; return [code, error];
} }
export default function Authenticator() { export default function Authenticator() {
const { provider } = useParams<{ provider: string }>(); const { provider } = useParams<{ provider: string }>();
const code = useCode(); const [code, error] = useCodeAndError();
const { refresh } = useContext(AuthenticationContext); const { refresh } = useContext(AuthenticationContext);
const [pending, setPending] = useState(true); const [pending, setPending] = useState(true);
@ -28,27 +29,54 @@ export default function Authenticator() {
}, [token]); }, [token]);
useEffect(() => { useEffect(() => {
setPending(true); if (code) {
createSession(code!) setPending(true);
.then(({ token }) => { createSession(code)
setToken(token ?? null); .then(({ token }) => {
}) setToken(token ?? null);
.finally(() => setPending(false)); })
.finally(() => setPending(false));
}
}, [code, provider]); }, [code, provider]);
useEffect(() => { useEffect(() => {
// Refresh when the token changes
refresh(); refresh();
}, [token, refresh]); }, [token, refresh]);
let children: JSX.Element; let children: JSX.Element;
if (pending) { if (error != null) {
switch (error) {
case 'access_denied':
children = (
<>
<h1>Sign In Error</h1>
We couldn't use your Ion account to log in.
<br />
<br />
<a href="/">Home</a>
</>
);
break;
default:
console.error('Unhandled OAuth error case:', error);
children = <h1>Sign In Error</h1>;
}
} else if (pending) {
children = <h1>Signing In</h1>; children = <h1>Signing In</h1>;
} else if (token) { } else if (token) {
children = <Redirect to="/" />; children = <Redirect to="/" />;
} else { } else {
// If we aren't pending anymore, but don't have a token, we must have errored // If we aren't pending anymore, but don't have a token, we must have errored
children = <h1>Sign In Error</h1>; children = (
<>
<h1>Sign In Error</h1>
<br />
<br />
<a href="/">Home</a>
</>
);
} }
return ( return (