Add login feature with local sesion storage and added tags to post request

This commit is contained in:
Alie 2024-04-27 18:03:58 +02:00
parent f753684abe
commit 0c1de423ef
3 changed files with 165 additions and 40 deletions

View File

@ -1,12 +1,32 @@
import { useState } from "react";
import "./App.css"; import "./App.css";
import ImageModerator from "./components/ImageModerator/ImageModerator"; import ImageModerator from "./components/ImageModerator/ImageModerator";
import Login from "./components/Login/Login";
function App() { function App() {
const [{ apiUrl, middlewareUrl, token }, setRemote] = useState({
apiUrl: "",
middlewareUrl: "",
token: "",
});
if (token) {
return ( return (
<> <>
<ImageModerator /> <ImageModerator
token={token}
apiUrl={apiUrl}
middlewareUrl={middlewareUrl}
/>
</> </>
); );
} else {
return (
<>
<Login setRemote={setRemote} />
</>
);
}
} }
export default App; export default App;

View File

@ -1,43 +1,32 @@
import Button from "../Button/Button"; import Button from "../Button/Button";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
// Let the user input the middleware URL, API url and app + secret interface ImageModeratorProps {
const MWURL = "http://localhost:8081"; token: string;
const APIURL = "http://localhost:8080"; apiUrl: string;
const app = "tester"; middlewareUrl: string;
const secret = "test"; }
export default function ImageModerator() { export default function ImageModerator({
token,
apiUrl,
middlewareUrl,
}: ImageModeratorProps) {
const acceptLabel = "Accept"; const acceptLabel = "Accept";
const discardLabel = "Discard"; const discardLabel = "Discard";
const endpoint = `${MWURL}/image`;
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const [imageSrc, setImageSrc] = useState(""); const [imageData, setImageData] = useState({ url: "", tags: [] });
const [imageAlt, setImageAlt] = useState("No image"); const [imageAlt, setImageAlt] = useState("No image");
const [token, setToken] = useState("");
useEffect(() => {
fetch(`${APIURL}/login`, {
method: "POST",
body: JSON.stringify({ app, secret }),
headers: { "Content-type": "application/json" },
})
.then((response) => {
return response.json();
})
.then((body) => {
setToken(body.token);
});
}, []);
console.log(token);
function acceptAction() { function acceptAction() {
fetch(`${APIURL}/images`, { fetch(`${apiUrl}/images`, {
method: "POST", method: "POST",
body: `{ "url": "${imageSrc}", "status": "available", "tags": [] }`, body: JSON.stringify({
url: imageData.url,
status: "available",
tags: imageData.tags,
}),
headers: { headers: {
"Content-type": "application/json", "Content-type": "application/json",
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
@ -47,9 +36,13 @@ export default function ImageModerator() {
} }
function discardAction() { function discardAction() {
fetch(`${APIURL}/images`, { fetch(`${apiUrl}/images`, {
method: "POST", method: "POST",
body: `{ "url": "${imageSrc}", "status": "unavailable", "tags": [] }`, body: JSON.stringify({
url: imageData.url,
status: "unavailable",
tags: imageData.tags,
}),
headers: { headers: {
"Content-type": "application/json", "Content-type": "application/json",
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
@ -59,8 +52,8 @@ export default function ImageModerator() {
} }
const getNewImage = () => { const getNewImage = () => {
setImageSrc(""); setImageData({ url: "", tags: [] });
fetch(endpoint, { fetch(`${middlewareUrl}/image`, {
method: "GET", method: "GET",
}) })
.then((response) => { .then((response) => {
@ -68,8 +61,9 @@ export default function ImageModerator() {
return response.json(); return response.json();
}) })
.then((data) => { .then((data) => {
const imageUrl = data.url; const url = data.url;
setImageSrc(imageUrl); const tags = data.tags;
setImageData({ url, tags });
}) })
.catch((error) => { .catch((error) => {
setImageAlt("Error"); setImageAlt("Error");
@ -96,7 +90,7 @@ export default function ImageModerator() {
<span>Loading...</span> <span>Loading...</span>
) : ( ) : (
<img <img
src={imageSrc} src={imageData.url}
alt={imageAlt} alt={imageAlt}
style={{ style={{
width: "100%", width: "100%",

View File

@ -0,0 +1,111 @@
import { useEffect, useState } from "react";
export default function Login({ setRemote }: { setRemote: Function }) {
const sendLabel = "Login";
const [middlewareUrl, setMiddlewareUrl] = useState("");
const [apiUrl, setApiUrl] = useState("");
const [app, setApp] = useState("");
const [secret, setSecret] = useState("");
function sendAction() {
event?.preventDefault();
try {
if (apiUrl && middlewareUrl && app && secret) {
localStorage.setItem(
"credentials",
JSON.stringify({ apiUrl, middlewareUrl, app, secret })
);
}
} catch (error) {
console.error(error);
}
fetch(`${apiUrl}/login`, {
method: "POST",
body: JSON.stringify({ app, secret }),
headers: { "Content-type": "application/json" },
})
.then((response) => {
return response.json();
})
.then((body) => {
setRemote({ apiUrl, middlewareUrl, token: body.token });
});
}
function handleChange(
e: {
target: { value: React.SetStateAction<string> };
},
setter: React.Dispatch<React.SetStateAction<string>>
): void {
setter(e.target.value);
}
useEffect(() => {
const savedRemote = localStorage.getItem("credentials");
if (savedRemote) {
const savedData = JSON.parse(savedRemote);
setApiUrl(savedData.apiUrl);
setMiddlewareUrl(savedData.middlewareUrl);
setApp(savedData.app);
setSecret(savedData.secret);
}
}, []);
useEffect(() => {
if (secret) {
sendAction();
}
}, [secret]);
return (
<div
style={{
height: "100vh",
width: "100vw",
}}>
<form
style={{
height: "100%",
width: "100%",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
}}
onSubmit={sendAction}>
<label>API URL: </label>
<input
type="url"
id="api"
name="api"
value={apiUrl}
onChange={(e) => handleChange(e, setApiUrl)}
/>
<label>Source URL: </label>
<input
type="url"
id="middleware"
name="middleware"
value={middlewareUrl}
onChange={(e) => handleChange(e, setMiddlewareUrl)}
/>
<label>App name: </label>
<input
type="text"
id="username"
name="username"
value={app}
onChange={(e) => handleChange(e, setApp)}
/>
<label>Secret: </label>
<input
type="password"
value={secret}
onChange={(e) => handleChange(e, setSecret)}
/>
<button type="submit">{sendLabel}</button>
</form>
</div>
);
}