51 lines
1.2 KiB
TypeScript
51 lines
1.2 KiB
TypeScript
import React, { useState, useContext, createContext } from "react";
|
|
|
|
interface AuthState {
|
|
loggedIn: boolean;
|
|
login: (password: string) => Promise<boolean>;
|
|
logout: () => void;
|
|
headers?: HeadersInit;
|
|
}
|
|
|
|
const AuthContext = createContext<AuthState>({
|
|
loggedIn: false,
|
|
login: () => Promise.resolve(false),
|
|
logout: () => console.error("No parent AuthContext found!"),
|
|
});
|
|
|
|
export const AuthProvider: React.FC = ({ children }) => {
|
|
const [headers, setHeaders] = useState<HeadersInit | undefined>();
|
|
|
|
const logout = () => setHeaders(undefined);
|
|
|
|
const login = async (password: string): Promise<boolean> => {
|
|
const username = "admin";
|
|
|
|
const newHeaders = {
|
|
Authorization: `CustomBasic ${btoa(`${username}:${password}`)}`,
|
|
};
|
|
|
|
const res = await fetch("api/editor/links", { headers: newHeaders });
|
|
|
|
if (res.status === 200) {
|
|
setHeaders(newHeaders);
|
|
return true;
|
|
} else {
|
|
logout();
|
|
return false;
|
|
}
|
|
};
|
|
|
|
return (
|
|
<AuthContext.Provider
|
|
value={{ loggedIn: !!headers, login, logout, headers }}
|
|
>
|
|
{children}
|
|
</AuthContext.Provider>
|
|
);
|
|
};
|
|
|
|
export function useAuth(): AuthState {
|
|
return useContext(AuthContext);
|
|
}
|