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

View File

@ -1,40 +1,71 @@
import React, { useState, useContext, createContext } from "react"; import React, { useState, useContext, createContext } from "react";
export interface AuthContextState { interface LoggedInState {
loggedIn: boolean; loggedIn: true;
loginFailed: boolean; headers: HeadersInit;
login: (pass?: string) => void; 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, loggedIn: false,
loginFailed: false, login: () => {
login: () => console.error("No parent AuthContext found!"), throw new Error("No parent AuthContext found!");
}; },
} as AuthState);
const AuthContext: React.Context<AuthContextState> = createContext(
DEFAULT_STATE
);
const password = "bubbles";
export const AuthProvider: React.FC = (props) => { export const AuthProvider: React.FC = (props) => {
const [loggedIn, setLoggedIn] = useState(false); const [loggedIn, setLoggedIn] = useState(false);
const [loginFailed, setLoginFailed] = useState(false); const [headers, setHeaders] = useState<HeadersInit | undefined>();
function login(pass?: string): void { function logout() {
if (pass === password) { 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); setLoggedIn(true);
setLoginFailed(false); setHeaders(newHeaders);
return true;
} else { } else {
setLoggedIn(false); logout();
setLoginFailed(true); return false;
} }
} }
return ( 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 LoginBox: React.FC = () => {
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
const [focused, setFocused] = useState(false); 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 ${ const passwordLabelClassName = `absolute inset-y-0 left-0 px-4 font-sans text-gray-600 ${
focused || password focused || password
@ -12,10 +13,17 @@ const LoginBox: React.FC = () => {
: "" : ""
} transition-transform pointer-events-none`; } transition-transform pointer-events-none`;
function handleSubmit(e: React.SyntheticEvent): void { async function handleSubmit(e: React.SyntheticEvent) {
e.preventDefault(); e.preventDefault();
login(password);
setPassword(""); if (!auth.loggedIn) {
const loginSuccessful = await auth.login(password);
if (!loginSuccessful) {
setLoginFailed(true);
setPassword("");
}
}
} }
return ( return (

View File

@ -1,6 +1,5 @@
import Head from "next/head"; import Head from "next/head";
import { GetStaticProps } from "next"; import React, { useEffect, useState } from "react";
import React, { useState } from "react";
import { AuthProvider, useAuth } from "components/Login/authcontext"; import { AuthProvider, useAuth } from "components/Login/authcontext";
import LoginHead from "components/Login/loginhead"; import LoginHead from "components/Login/loginhead";
import LoginBox from "components/Login/loginbox"; import LoginBox from "components/Login/loginbox";
@ -8,33 +7,6 @@ import Analytics from "components/Analytics";
import Editor from "components/Editor"; import Editor from "components/Editor";
import { EditableLink } from "components/Editor/Link"; 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 = () => ( const LoginScreen: React.FC = () => (
<div className="fixed h-screen w-full overflow-auto bg-gray-100"> <div className="fixed h-screen w-full overflow-auto bg-gray-100">
<div className="m-auto h-full flex justify-center items-center"> <div className="m-auto h-full flex justify-center items-center">
@ -51,16 +23,25 @@ const LoginScreen: React.FC = () => (
</div> </div>
); );
interface EditorPageProps { const EditorPage: React.FC = () => {
data: any; const auth = useAuth();
} const [links, setLinks] = useState<EditableLink[]>([]);
const EditorPage: React.FC<EditorPageProps> = ({ data }) => { useEffect(() => {
const { loggedIn } = useAuth(); async function fetchLinks() {
const [links, setLinks] = useState<EditableLink[]>(data ?? []); if (!auth.loggedIn) {
return;
}
console.log({ links }); const res = await fetch("/api/editor/links", { headers: auth.headers });
return loggedIn ? (
setLinks(await res.json());
}
fetchLinks();
}, [auth]);
return auth.loggedIn ? (
<> <>
<Analytics /> <Analytics />
<Editor links={links} setLinks={setLinks} /> <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 ( return (
<AuthProvider> <AuthProvider>
<EditorPage data={data} /> <EditorPage />
</AuthProvider> </AuthProvider>
); );
} }