Adding Google as an Authentication Method

October 26, 2022

I didn’t have the most productive of days today. However, made some progress with authentication and authorisation.

Google Authentication

I managed to add Google as a user authentication method today using next auth. I had quite a bit of bother getting it to work properly. Turns out I needed to fix some things in my Prisma schema. It was super important to get the Google authentication provider working as pretty much everyone has a google account. I don’t want to faff around trying to get email authentication working just now. It can be added at a later point.

Authorisation

I added in some logic to ensure non-authorised users (aka people who haven’t logged in yet) are unable to access authorised pages such as the user portal and deck review pages. Previously any old person could just go to those urls. Although nothing would render on the page. Now they just get redirected to the homepage.

Below is the code I’ve used to implement authorisation on my Deck pages.

const router = useRouter();
const { deckName } = router.query;
const { data: session, status } = useSession();
//if session doesnt exist then redirect to home page
useEffect(() => {
if (status === "unauthenticated") {
router.push("/");
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [status]);
if (status === "loading") {
<div className="mt-20">
<LoadingSpinner width="w-20" height="w-20" />
</div>;
}
if (status === "authenticated") {
return <Deck deckName={deckName as string} />;
← Go home