Created
July 27, 2020 18:57
-
-
Save KevinDanikowski/5f51c09a92dce55574a67558c4badabb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// in /pages directory | |
import React, { useContext, useEffect } from 'react' | |
import { useRouter } from 'next/router' | |
import { AWS_ACCESS_TOKEN } from '../utils/constants' | |
import Auth from '@aws-amplify/auth' | |
import UserContext from '../lib/UserContext' | |
import { Loading } from '../components/QueryHandling' | |
const getAccessToken = hash => { | |
const hashStart = hash.substr(hash.indexOf('access_token=') + 'access_token='.length, hash.length) | |
return hashStart.substr(hashStart, hashStart.indexOf('&')) | |
} | |
// When a user comes back from authenticating, the url looks like this: | |
// /token#id_token=.... | |
export default function TokenSetter() { | |
const router = useRouter() | |
const { setUserContext } = useContext(UserContext) | |
useEffect(() => { | |
const access_token = getAccessToken(window.location.hash) | |
const updateUser = async nothing => { | |
try { | |
const user = await Auth.currentAuthenticatedUser() | |
setUserContext({ user }) | |
router.replace('/protectedpage') | |
} catch { | |
router.replace('/unprotectedpage') | |
} | |
} | |
if (access_token) { | |
localStorage.setItem(AWS_ACCESS_TOKEN, access_token) | |
} | |
updateUser() | |
}, []) | |
return <Loading /> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment