Hookup public page

This commit is contained in:
Adi Thakral 2021-04-02 16:14:50 -04:00 committed by Steven Xu
parent ee4f7f5f10
commit ffc1ed9d21
12 changed files with 124 additions and 104 deletions

1
.gitignore vendored
View File

@ -3,3 +3,4 @@ links.db
password.txt password.txt
/.vs /.vs
/.vscode /.vscode
/links.json

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,8 +1,8 @@
import React, { useRef, useState } from "react"; import React from "react";
import { Draggable } from "react-beautiful-dnd"; import { Draggable } from "react-beautiful-dnd";
export type EditableLink = { export type EditableLink = {
title: string; name: string;
url: string; url: string;
active: boolean; active: boolean;
clicks: number; clicks: number;
@ -55,8 +55,8 @@ const Link: React.FC<LinkProps> = ({ index, link, onChange, onDelete }) => {
<input <input
type="text" type="text"
placeholder="Edit Title" placeholder="Edit Title"
value={link.title} value={link.name}
onChange={(e) => onChange({ ...link, title: e.target.value })} onChange={(e) => onChange({ ...link, name: e.target.value })}
/> />
<input <input

View File

@ -1,4 +1,4 @@
import React, { useState } from "react"; import React, { useState, useEffect } from "react";
import { DragDropContext, Droppable, DropResult } from "react-beautiful-dnd"; import { DragDropContext, Droppable, DropResult } from "react-beautiful-dnd";
import Link, { EditableLink } from "components/Editor/Link"; import Link, { EditableLink } from "components/Editor/Link";
@ -10,10 +10,14 @@ interface EditorProps {
setLinks: React.Dispatch<React.SetStateAction<EditableLink[]>>; setLinks: React.Dispatch<React.SetStateAction<EditableLink[]>>;
} }
const Editor: React.FC<EditorProps> = ({ links, setLinks }) => { const Editor: React.FC<EditorProps> = ({ links }) => {
const [formState, setFormState] = useState<EditableLink[]>(links); const [formState, setFormState] = useState<EditableLink[]>(links);
const { displayDragDrop } = useDragDrop(); const { displayDragDrop } = useDragDrop();
useEffect(() => {
setFormState(links);
}, [links]);
const handleOnDragEnd = (result: DropResult) => { const handleOnDragEnd = (result: DropResult) => {
if (!result?.destination) return; if (!result?.destination) return;
@ -29,7 +33,7 @@ const Editor: React.FC<EditorProps> = ({ links, setLinks }) => {
setFormState([ setFormState([
...formState, ...formState,
{ {
title: "", name: "",
url: "", url: "",
clicks: 0, clicks: 0,
active: true, active: true,

View File

@ -1,15 +1,14 @@
import React from "react"; import React from "react";
import { useEffect } from "react";
interface Link { export interface Link {
title: string; name: string;
url: string; url: string;
} }
interface LinkProps { interface LinkProps {
links: Link[]; links: Link[];
} }
const Links: React.FC<LinkProps> = ({ links }) => { export const Links: React.FC<LinkProps> = ({ links }) => {
const postData = (url = ""): void => { const postData = (url = ""): void => {
fetch(url, { fetch(url, {
method: "POST", method: "POST",
@ -36,7 +35,7 @@ const Links: React.FC<LinkProps> = ({ links }) => {
<img className="mb-3" src="csc_logo.png" alt="CSC Logo" width="100px" /> <img className="mb-3" src="csc_logo.png" alt="CSC Logo" width="100px" />
<h1 className="font-bold">@uwcsclub</h1> <h1 className="font-bold">@uwcsclub</h1>
<ul className="flex flex-col my-6 w-full"> <ul className="flex flex-col my-6 w-full">
{links.map(({ title, url }, i) => ( {links.map(({ name, url }, i) => (
<li key={i} className="w-full contents"> <li key={i} className="w-full contents">
<a <a
className="btn bg-gray-450 p-3 text-white font-bold text-center self-center my-1.5 className="btn bg-gray-450 p-3 text-white font-bold text-center self-center my-1.5
@ -47,7 +46,7 @@ const Links: React.FC<LinkProps> = ({ links }) => {
rel="noreferrer" rel="noreferrer"
onClick={handleClick} onClick={handleClick}
> >
{title} {name}
</a> </a>
</li> </li>
))} ))}
@ -55,5 +54,3 @@ const Links: React.FC<LinkProps> = ({ links }) => {
</div> </div>
); );
}; };
export default Links;

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,3 +0,0 @@
export { default as Links } from "./Links";
export { default as Editor } from "./Editor";
export { default as Preview } from "./Preview";

View File

@ -10,11 +10,11 @@ const devConfig = {
return [ return [
{ {
source: "/api", source: "/api",
destination: "http://localhost:5000/editor/links", destination: "http://localhost:5000",
}, },
{ {
source: "/api/:slug", source: "/api/:path*",
destination: "http://localhost:5000/:slug", destination: "http://localhost:5000/:path*",
}, },
]; ];
}, },

View File

@ -6,12 +6,14 @@
"dev": "next dev", "dev": "next dev",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"type-check": "tsc",
"format": "prettier --write './**/*'", "format": "prettier --write './**/*'",
"format:check": "prettier --check './**/*'", "format:check": "prettier --check './**/*'",
"lint": "eslint \"{pages,components}/**/*.{js,ts,tsx,jsx}\" --quiet --fix", "lint": "eslint \"{pages,components}/**/*.{js,ts,tsx,jsx}\" --quiet --fix",
"lint:check": "eslint \"{pages,components}/**/*.{js,ts,tsx,jsx}\" --quiet", "lint:check": "eslint \"{pages,components}/**/*.{js,ts,tsx,jsx}\" --quiet",
"check": "npm run format:check && npm run lint:check", "check": "npm run format:check && npm run lint:check",
"check:fix": "npm run format && npm run lint" "check:fix": "npm run format && npm run lint",
"clean-cache": "rm -rf ./.next"
}, },
"dependencies": { "dependencies": {
"fast-deep-equal": "^3.1.3", "fast-deep-equal": "^3.1.3",

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: [
{
title: "dummlink1",
url: "www.helloworld.com",
clicks: 0,
active: true,
},
{
title: "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>
); );
} }

View File

@ -1,29 +1,27 @@
import React from "react"; import React from "react";
import { GetStaticProps } from "next"; import { GetStaticProps } from "next";
import { Links } from "components"; import { Link, Links } from "components/Links";
import { readFileSync } from "fs";
// TODO: change export const getStaticProps: GetStaticProps<Props> = async () => {
const API = "https://api.thedogapi.com/v1/breeds?limit=10&page=0"; if (!process.env.LINKS_FILE) {
throw new Error("Set the LINKS_FILE environment variable");
}
export const getStaticProps: GetStaticProps = async () => { const links = JSON.parse(readFileSync(process.env.LINKS_FILE).toString());
// fetch data here
const data = await fetch(API).then((res) => res.json());
return { return {
props: { data }, // will be passed to the page component as props props: { links },
revalidate: 1, revalidate: 1,
}; };
}; };
const Home: React.FC = ({ data }: any) => { interface Props {
return ( links: Link[];
<Links }
links={data.map((dog: any) => ({
title: dog.name, const Home: React.FC<Props> = ({ links }) => {
url: "https://www.google.com/", return <Links links={links} />;
}))}
/>
);
}; };
export default Home; export default Home;