From 6f7a9fac14d7045350ec894949620d8154396bf7 Mon Sep 17 00:00:00 2001 From: Nathaniel Tampus Date: Sat, 4 Mar 2023 18:38:07 +0800 Subject: [PATCH] session context & auth util functions --- client/src/context/ContextProvider.tsx | 22 ++++++++++++++++++++ client/src/context/session.ts | 8 ++++++++ client/src/lib/auth.ts | 28 ++++++++++++++++++++++++++ 3 files changed, 58 insertions(+) create mode 100644 client/src/context/ContextProvider.tsx create mode 100644 client/src/context/session.ts create mode 100644 client/src/lib/auth.ts diff --git a/client/src/context/ContextProvider.tsx b/client/src/context/ContextProvider.tsx new file mode 100644 index 0000000..91eb386 --- /dev/null +++ b/client/src/context/ContextProvider.tsx @@ -0,0 +1,22 @@ +"use client"; + +import type { User } from "@chessu/types"; + +import { useState, useEffect } from "react"; +import { SessionContext } from "./session"; +import { fetchSession } from "@/lib/auth"; + +export default function ContextProvider({ children }: { children: React.ReactNode }) { + const [user, setUser] = useState({}); + + async function getSession() { + const user = await fetchSession(); + setUser(user || null); + } + + useEffect(() => { + getSession(); + }, []); + + return {children}; +} diff --git a/client/src/context/session.ts b/client/src/context/session.ts new file mode 100644 index 0000000..de6f15d --- /dev/null +++ b/client/src/context/session.ts @@ -0,0 +1,8 @@ +import type { User } from "@chessu/types"; + +import { createContext, Dispatch, SetStateAction } from "react"; + +export const SessionContext = createContext<{ + user: User | null | undefined; // undefined = hasn't been checked yet, null = no user + setUser: Dispatch>; +} | null>(null); diff --git a/client/src/lib/auth.ts b/client/src/lib/auth.ts new file mode 100644 index 0000000..74dbfb5 --- /dev/null +++ b/client/src/lib/auth.ts @@ -0,0 +1,28 @@ +import type { User } from "@chessu/types"; +import { API_URL } from "@/config"; + +export const fetchSession = async () => { + const res = await fetch(`${API_URL}/v1/auth`, { + credentials: "include" + }); + + if (res && res.status === 200) { + const user: User = await res.json(); + return user; + } +}; + +export const setGuestSession = async (name: string) => { + const res = await fetch(`${API_URL}/v1/auth/guest`, { + method: "POST", + credentials: "include", + headers: { + "Content-Type": "application/json" + }, + body: JSON.stringify({ name }) + }); + if (res.status === 201) { + const user: User = await res.json(); + return user; + } +};