auth WIP
This commit is contained in:
42
src/auth/auth-provider.tsx
Normal file
42
src/auth/auth-provider.tsx
Normal file
@ -0,0 +1,42 @@
|
||||
import { type JSX, useEffect, useState, createContext } from "react"
|
||||
|
||||
|
||||
type AuthContextType = {
|
||||
token: string | null;
|
||||
setToken: (token: string | null) => void;
|
||||
};
|
||||
|
||||
|
||||
const AuthContext = createContext<AuthContextType>({
|
||||
token: null,
|
||||
setToken: () => { },
|
||||
});
|
||||
|
||||
|
||||
export const AuthProvider = ({ children }: { children: JSX.Element }) => {
|
||||
const [token, setTokenState] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const savedToken = localStorage.getItem("token");
|
||||
if (savedToken) {
|
||||
setTokenState(savedToken);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const setToken = (newToken: string | null) => {
|
||||
setTokenState(newToken);
|
||||
if (newToken) {
|
||||
localStorage.setItem("token", newToken);
|
||||
} else {
|
||||
localStorage.removeItem("token");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ token, setToken }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export default AuthContext;
|
||||
11
src/auth/auth.tsx
Normal file
11
src/auth/auth.tsx
Normal file
@ -0,0 +1,11 @@
|
||||
import { useContext } from "react"
|
||||
import AuthContext from "./auth-provider"
|
||||
|
||||
|
||||
function useAuth() {
|
||||
return (
|
||||
useContext(AuthContext)
|
||||
);
|
||||
}
|
||||
|
||||
export default useAuth;
|
||||
12
src/auth/logout.tsx
Normal file
12
src/auth/logout.tsx
Normal file
@ -0,0 +1,12 @@
|
||||
import useAuth from "./auth";
|
||||
|
||||
const logout = () => {
|
||||
// eslint-disable-next-line react-hooks/rules-of-hooks
|
||||
const { setToken: setAuth } = useAuth();
|
||||
|
||||
return () => {
|
||||
setAuth(false);
|
||||
};
|
||||
}
|
||||
|
||||
export default logout;
|
||||
16
src/auth/ping.tsx
Normal file
16
src/auth/ping.tsx
Normal file
@ -0,0 +1,16 @@
|
||||
const ping = () => {
|
||||
// TODO: request to API
|
||||
return () => {
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
// const ping = async (token: string): Promise<boolean> => {
|
||||
// return new Promise((resolve) => {
|
||||
// setTimeout(() => {
|
||||
// resolve(!!token);
|
||||
// }, 300);
|
||||
// });
|
||||
// };
|
||||
|
||||
export default ping;
|
||||
Reference in New Issue
Block a user