2020-05-03 04:22:09 -04:00
|
|
|
import React, { useState, useEffect, useContext } from "react";
|
2020-04-26 03:59:46 -04:00
|
|
|
|
2020-09-07 22:35:31 -04:00
|
|
|
import FakeStorage from "../helpers/FakeStorage";
|
2020-04-26 03:59:46 -04:00
|
|
|
|
2021-07-17 04:39:49 -04:00
|
|
|
type AuthContextValue = {
|
2021-07-09 02:22:35 -04:00
|
|
|
password: string;
|
|
|
|
setPassword: React.Dispatch<React.SetStateAction<string>>;
|
|
|
|
};
|
2020-04-14 02:05:44 -04:00
|
|
|
|
2021-07-17 04:39:49 -04:00
|
|
|
const AuthContext =
|
|
|
|
React.createContext<AuthContextValue | undefined>(undefined);
|
2021-06-03 01:31:18 -04:00
|
|
|
|
|
|
|
let storage: Storage | FakeStorage;
|
2020-09-07 22:35:31 -04:00
|
|
|
try {
|
|
|
|
sessionStorage.setItem("__test", "__test");
|
|
|
|
sessionStorage.removeItem("__test");
|
|
|
|
storage = sessionStorage;
|
|
|
|
} catch (e) {
|
|
|
|
console.warn("Session storage is disabled, no authentication will be saved");
|
|
|
|
storage = new FakeStorage();
|
|
|
|
}
|
|
|
|
|
2021-07-02 01:54:54 -04:00
|
|
|
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|
|
|
const [password, setPassword] = useState<string>(
|
|
|
|
storage.getItem("auth") || ""
|
|
|
|
);
|
2020-04-14 02:05:44 -04:00
|
|
|
|
|
|
|
useEffect(() => {
|
2020-09-07 22:35:31 -04:00
|
|
|
storage.setItem("auth", password);
|
2020-04-14 02:05:44 -04:00
|
|
|
}, [password]);
|
|
|
|
|
|
|
|
const value = {
|
|
|
|
password,
|
|
|
|
setPassword,
|
|
|
|
};
|
|
|
|
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
|
|
|
}
|
|
|
|
|
2021-02-05 21:32:38 -05:00
|
|
|
export function useAuth() {
|
|
|
|
const context = useContext(AuthContext);
|
|
|
|
if (context === undefined) {
|
|
|
|
throw new Error("useAuth must be used within a AuthProvider");
|
|
|
|
}
|
|
|
|
return context;
|
|
|
|
}
|
|
|
|
|
2020-04-14 02:05:44 -04:00
|
|
|
export default AuthContext;
|