Skip to content

Commit

Permalink
wip login and logout states
Browse files Browse the repository at this point in the history
  • Loading branch information
Lorezz committed Sep 10, 2024
1 parent 8668bb9 commit 81e1cce
Show file tree
Hide file tree
Showing 10 changed files with 163 additions and 68 deletions.
28 changes: 25 additions & 3 deletions src/components/layout/Header.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,20 @@
import React, { useEffect, useState } from "react";
import * as auth from "../../lib/auth";

export default function Header() {
const logged = auth.useAuth();

// useEffect(() => {
// if (!logged) {
// window.location.href = "/enter";
// }
// }, [logged]);

function logoutAndRedir() {
auth.logout();
// window.location.href = "/enter";
}

return (
<div className="navbar bg-primary text-primary-content shadow-xl mb-2">
<div className="navbar-start">
Expand Down Expand Up @@ -70,9 +86,15 @@ export default function Header() {
</ul>
</div>
<div className="navbar-end px-4">
<a className="btn btn-ghost" href="/enter">
Sign In / Up
</a>
{!logged ? (
<a className="btn btn-ghost" href="/enter">
Sign In / Up
</a>
) : (
<button className="btn btn-ghost" onClick={() => logoutAndRedir()}>
Logout
</button>
)}
</div>
</div>
);
Expand Down
29 changes: 20 additions & 9 deletions src/lib/api.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as auth from "./auth";
const SERVER_URL = import.meta.env.VITE_SERVER_URL;

export async function upsertChart(
Expand All @@ -11,7 +12,7 @@ export async function upsertChart(
},
id?: string
) {
const token = sessionStorage.getItem("token");
const token = auth.getAuth();
if (!token) return null;

const url = id ? `${SERVER_URL}/charts/${id}` : `${SERVER_URL}/charts/`;
Expand All @@ -29,6 +30,11 @@ export async function upsertChart(
body: payload,
});
console.log("upsertChart", response.status);

if (response.status === 401) {
return auth.logout();
}

if (response.status === 200) {
const data = await response.json();
return data;
Expand All @@ -37,7 +43,7 @@ export async function upsertChart(
}

export async function deleteChart(id: string) {
const token = sessionStorage.getItem("token");
const token = auth.getAuth();
if (!token) return null;

const response = await fetch(`${SERVER_URL}/charts/${id}`, {
Expand All @@ -48,6 +54,9 @@ export async function deleteChart(id: string) {
},
});
console.log("deleteChart", response.status);
if (response.status === 401) {
return auth.logout();
}
if (response.status === 200) {
const data = await response.json();
return data;
Expand All @@ -56,7 +65,7 @@ export async function deleteChart(id: string) {
}

export async function getCharts() {
const token = sessionStorage.getItem("token");
const token = auth.getAuth();
if (!token) return null;
const response = await fetch(`${SERVER_URL}/charts`, {
method: "GET",
Expand All @@ -65,6 +74,11 @@ export async function getCharts() {
Authorization: `Bearer ${token}`,
},
});

console.log("getCharts", response.status);
if (response.status === 401) {
return auth.logout();
}
if (response.status === 200) {
const data = await response.json();
return data;
Expand All @@ -91,11 +105,8 @@ export async function login({
});
if (response.status === 200) {
const data = await response.json();
if (rememberMe) {
console.log("remember me!");
// localStorage.setItem("token", data.token);
}
sessionStorage.setItem("token", data.accessToken);

auth.saveAuth(data.accessToken, rememberMe || false);
return true;
} else {
const data = await response.json();
Expand All @@ -121,7 +132,7 @@ export async function register({
});
if (response.status === 200) {
const data = await response.json();
sessionStorage.setItem("token", data.accessToken);
auth.saveAuth(data.accessToken, false);
return true;
} else {
const data = await response.json();
Expand Down
39 changes: 39 additions & 0 deletions src/lib/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { useEffect, useState } from "react";

function getItem(name: string) {
return sessionStorage.getItem(name) || localStorage.getItem(name);
}

export function isAuth() {
const token = getItem("token");
return token ? true : false;
}

export function getAuth() {
return getItem("token");
}

export function saveAuth(token: string, remember: boolean) {
if (remember) {
localStorage.setItem("token", token);
} else {
sessionStorage.setItem("token", token);
}
}

export function logout() {
localStorage.removeItem("token");
sessionStorage.removeItem("token");
try {
window.location.reload();
} catch (error) {}
}

export function useAuth() {
const item = getItem("token");
const [auth, setAuth] = useState(isAuth());
useEffect(() => {
setAuth(isAuth());
}, [item]);
return auth;
}
50 changes: 0 additions & 50 deletions src/lib/store.ts

This file was deleted.

50 changes: 50 additions & 0 deletions src/lib/storeState.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";
import { defaultConfig } from "./constants";
import { MatrixType, StoreStateType } from "../types";
// import { immer } from 'zustand/middleware/immer';

const useStoreState = create<StoreStateType>()(
// persist(
(set) => ({
data: null,
chart: "bar",
config: defaultConfig,
rawData: null,
description: "",
publish: false,
name: "",
id: null,
setId: (value: string) => set(() => ({ id: value })),
setName: (value: string) => set(() => ({ name: value })),
setConfig: (value: object) => set(() => ({ config: value })),
setChart: (value: string) => set(() => ({ chart: value })),
setRawData: (value: any) => set(() => ({ rawData: value })),
setData: (value: MatrixType | null) => set(() => ({ data: value })),
loadItem: (value: any) =>
set((state) => ({
chart: value.chart,
config: value.config,
rawData: null,
data: value.data,
description: value.description,
publish: value.publish,
name: value.name,
id: value.id,
})),
resetItem: () =>
set(() => ({
id: null,
name: "",
description: "",
chart: "bar",
data: null,
config: defaultConfig,
rawData: null,
publish: true,
})),
})
// { name: "persistedStore" }
// )
);
export default useStoreState;
2 changes: 1 addition & 1 deletion src/pages/GenerateDataPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useEffect } from "react";
import { getAvailablePalettes, getPalette, transposeData } from "../lib/utils";
import DataTable from "../components/DataTable";

import useStoreState from "../lib/store";
import useStoreState from "../lib/storeState";
import GenerateRandomData from "../components/GenerateRandomData";
import { downloadCSV, dataToCSV } from "../lib/downloadUtils";

Expand Down
23 changes: 20 additions & 3 deletions src/pages/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import DataTable from "../components/DataTable";
import RenderChart from "../components/RenderChart";

import useChartsStoreState from "../lib/chartListStore";
import useStoreState from "../lib/store";
import useStoreState from "../lib/storeState";
import CSVUpload from "../components/CSVUpload";
import SelectChart from "../components/SelectChart";
import ChartOptions from "../components/ChartOptions";
Expand All @@ -14,6 +14,7 @@ import { dataToCSV, downloadCSV } from "../lib/downloadUtils";
import ChartSave from "../components/ChartSave";
import { useEffect } from "react";
import * as api from "../lib/api";
import * as auth from "../lib/auth";

function Home() {
const [state, send] = useMachine(stepMachine);
Expand Down Expand Up @@ -44,6 +45,9 @@ function Home() {
}

useEffect(() => {
if (!auth.isAuth()) {
window.location.href = "/enter";
}
fetchCharts();
}, []);

Expand Down Expand Up @@ -210,10 +214,23 @@ function Home() {
>
<div className="grow flex flex-col">
<div className="text-lg">{item.name}</div>
<small className="text-xxs text-content opacity-70 pr-4">
{item.id}
<small
className={`text-xxs text-content opacity-70 pr-4 ${
item.publish ? "text-success" : "text-content"
}`}
>
{item.publish ? "public" : "private"}
</small>
</div>
{item.publish && (
<a
className="btn btn-outline btn-success btn-sm"
target="_blank"
href={`/chart/${item.id}`}
>
view
</a>
)}
<button
className="btn btn-outline btn-primary btn-sm"
onClick={() => {
Expand Down
2 changes: 1 addition & 1 deletion src/pages/LoadDataPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useEffect } from "react";
import { getAvailablePalettes, getPalette, transposeData } from "../lib/utils";
import DataTable from "../components/DataTable";

import useStoreState from "../lib/store";
import useStoreState from "../lib/storeState";
import LoadSource from "../components/LoadSource";
import { downloadCSV, dataToCSV } from "../lib/downloadUtils";

Expand Down
6 changes: 5 additions & 1 deletion src/pages/ShowChartPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,16 @@ function ShowChartPage() {
.then((data) => setChartData(data));
}, []);

let description = (chartData as any)?.description ?? "";
return (
<div className="">
<div>ID: {id}</div>
<h1 className="text-4xl font-bold">
{`${(chartData as any)?.name ?? "Show Chart"}`}{" "}
</h1>
<div>ID: {id}</div>
{description && (
<p dangerouslySetInnerHTML={{ __html: `${description}` }} />
)}
<div className="p-4">
{chartData && <RenderChart {...(chartData as any)} />}
</div>
Expand Down
2 changes: 2 additions & 0 deletions src/sharedTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ export type FieldDataType = {
data: MatrixType | null;
name?: string;
id?: string;
description?: string;
publish: boolean;
};

export type Step = {
Expand Down

0 comments on commit 81e1cce

Please sign in to comment.