session context & auth util functions
This commit is contained in:
22
client/src/context/ContextProvider.tsx
Normal file
22
client/src/context/ContextProvider.tsx
Normal file
@@ -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<User | null>({});
|
||||||
|
|
||||||
|
async function getSession() {
|
||||||
|
const user = await fetchSession();
|
||||||
|
setUser(user || null);
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
getSession();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return <SessionContext.Provider value={{ user, setUser }}>{children}</SessionContext.Provider>;
|
||||||
|
}
|
||||||
8
client/src/context/session.ts
Normal file
8
client/src/context/session.ts
Normal file
@@ -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<SetStateAction<User | null>>;
|
||||||
|
} | null>(null);
|
||||||
28
client/src/lib/auth.ts
Normal file
28
client/src/lib/auth.ts
Normal file
@@ -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;
|
||||||
|
}
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user