Hookup editor login #23

Merged
a3thakra merged 1 commits from hookup-editor-login into hookup-public-page 2021-04-02 11:09:02 -04:00
4 changed files with 87 additions and 66 deletions

View File

@ -7,7 +7,7 @@ import os
DB_PATH = os.path.join(os.path.dirname(__file__), 'links.db')
app = Flask(__name__)
auth = HTTPBasicAuth()
auth = HTTPBasicAuth('CustomBasic')
users = {
"admin": generate_password_hash("test"),
@ -62,6 +62,7 @@ def update_links():
cur.executemany('INSERT INTO links VALUES (?,?,?,?)', links)
con.commit()
data = regen_JSON()
# TODO: Trigger a rebuild of the frontend
outfile = open('data.json', 'w')
print(data, file=outfile)
outfile.close()

View File

@ -1,40 +1,71 @@
import React, { useState, useContext, createContext } from "react";
export interface AuthContextState {
loggedIn: boolean;
loginFailed: boolean;
login: (pass?: string) => void;
interface LoggedInState {
loggedIn: true;
headers: HeadersInit;
logout(): void;
}
const DEFAULT_STATE: AuthContextState = {
interface LoggedOutState {
loggedIn: false;
login(password: string): Promise<boolean>;
}
export type AuthState = LoggedInState | LoggedOutState;
const AuthContext = createContext({
loggedIn: false,
loginFailed: false,
login: () => console.error("No parent AuthContext found!"),
};
const AuthContext: React.Context<AuthContextState> = createContext(
DEFAULT_STATE
);
const password = "bubbles";
login: () => {
throw new Error("No parent AuthContext found!");
},
} as AuthState);
export const AuthProvider: React.FC = (props) => {
const [loggedIn, setLoggedIn] = useState(false);
const [loginFailed, setLoginFailed] = useState(false);
const [headers, setHeaders] = useState<HeadersInit | undefined>();
function login(pass?: string): void {
if (pass === password) {
function logout() {
setLoggedIn(false);
setHeaders(undefined);
}
async function login(password: string): Promise<boolean> {
const username = process.env.NEXT_PUBLIC_EDITOR_USERNAME;
if (!username) {
throw new Error(
"Missing NEXT_PUBLIC_EDITOR_USERNAME environment variable"
);
}
const newHeaders = {
Authorization: `CustomBasic ${btoa(`${username}:${password}`)}`,
};
const res = await fetch("/api/editor/links", { headers: newHeaders });
if (res.status === 200) {
setLoggedIn(true);
setLoginFailed(false);
setHeaders(newHeaders);
return true;
} else {
setLoggedIn(false);
setLoginFailed(true);
logout();
return false;
}
}
return (
<AuthContext.Provider value={{ loggedIn, login, loginFailed }} {...props} />
<AuthContext.Provider
value={
loggedIn && headers != null
? { loggedIn, headers, logout }
: { loggedIn: false, login }
}
{...props}
/>
);
};
export const useAuth = () => useContext(AuthContext);
export function useAuth(): AuthState {
return useContext(AuthContext);
}

View File

@ -4,7 +4,8 @@ import { useAuth } from "components/Login/authcontext";
const LoginBox: React.FC = () => {
const [password, setPassword] = useState("");
const [focused, setFocused] = useState(false);
const { login, loginFailed } = useAuth();
const [loginFailed, setLoginFailed] = useState(false);
const auth = useAuth();
const passwordLabelClassName = `absolute inset-y-0 left-0 px-4 font-sans text-gray-600 ${
focused || password
@ -12,10 +13,17 @@ const LoginBox: React.FC = () => {
: ""
} transition-transform pointer-events-none`;
function handleSubmit(e: React.SyntheticEvent): void {
async function handleSubmit(e: React.SyntheticEvent) {
e.preventDefault();
login(password);
setPassword("");
if (!auth.loggedIn) {
const loginSuccessful = await auth.login(password);
if (!loginSuccessful) {
setLoginFailed(true);
setPassword("");
}
}
}
return (

View File

@ -1,6 +1,5 @@
import Head from "next/head";
import { GetStaticProps } from "next";
import React, { useState } from "react";
import React, { useEffect, useState } from "react";
import { AuthProvider, useAuth } from "components/Login/authcontext";
import LoginHead from "components/Login/loginhead";
import LoginBox from "components/Login/loginbox";
@ -8,33 +7,6 @@ import Analytics from "components/Analytics";
import Editor from "components/Editor";
import { EditableLink } from "components/Editor/Link";
export const getStaticProps: GetStaticProps = async () => {
// TODO: Fetch links here
return {
props: {
data: [
{
name: "dummlink1",
url: "www.helloworld.com",
clicks: 0,
active: true,
},
{
name: "dummlink2",
url: "www.hiworld.com",
clicks: 0,
active: true,
},
],
}, // will be passed to the page component as props
// Next.js will attempt to re-generate the page:
// - When a request comes intype EditableLink = {
// - At most once every second
revalidate: 1,
};
};
const LoginScreen: React.FC = () => (
<div className="fixed h-screen w-full overflow-auto bg-gray-100">
<div className="m-auto h-full flex justify-center items-center">
@ -51,16 +23,25 @@ const LoginScreen: React.FC = () => (
</div>
);
interface EditorPageProps {
data: any;
}
const EditorPage: React.FC = () => {
const auth = useAuth();
const [links, setLinks] = useState<EditableLink[]>([]);
const EditorPage: React.FC<EditorPageProps> = ({ data }) => {
const { loggedIn } = useAuth();
const [links, setLinks] = useState<EditableLink[]>(data ?? []);
useEffect(() => {
async function fetchLinks() {
if (!auth.loggedIn) {
return;
}
console.log({ links });
return loggedIn ? (
const res = await fetch("/api/editor/links", { headers: auth.headers });
setLinks(await res.json());
}
fetchLinks();
}, [auth]);
return auth.loggedIn ? (
<>
<Analytics />
<Editor links={links} setLinks={setLinks} />
@ -70,10 +51,10 @@ const EditorPage: React.FC<EditorPageProps> = ({ data }) => {
);
};
export default function EditorPageWrapper({ data }: any): JSX.Element {
export default function EditorPageWrapper(): JSX.Element {
return (
<AuthProvider>
<EditorPage data={data} />
<EditorPage />
</AuthProvider>
);
}