From d08639f04f83068568718632feee2e1c72fafe16 Mon Sep 17 00:00:00 2001
From: Hannah <hz018@hdm-stuttgart.de>
Date: Tue, 28 Nov 2023 00:15:37 +0100
Subject: [PATCH] Login Page Frontend and Backend

---
 growbros-frontend/src/App.tsx                 | 11 +++++-
 .../components/NavbarRegistrationAndLogin.tsx | 26 ++++++++++++++
 growbros-frontend/src/jwt/Cookies.ts          |  9 -----
 growbros-frontend/src/pages/Register.tsx      | 36 +++++++++++++------
 .../controllers/AuthenticationController.java | 12 +++----
 5 files changed, 66 insertions(+), 28 deletions(-)
 create mode 100644 growbros-frontend/src/components/NavbarRegistrationAndLogin.tsx

diff --git a/growbros-frontend/src/App.tsx b/growbros-frontend/src/App.tsx
index eb1602e..f138f52 100644
--- a/growbros-frontend/src/App.tsx
+++ b/growbros-frontend/src/App.tsx
@@ -8,11 +8,20 @@ import Wunschliste from "./pages/Wunschliste";
 import PlantDetails from "./components/PlantDetails";
 import Register from "./pages/Register.tsx";
 import Login from "./pages/Login.tsx";
+import {useEffect, useState} from "react";
+import {getCookie} from "./jwt/Cookies.ts";
+import NavbarRegistrationAndLogin from "./components/NavbarRegistrationAndLogin.tsx";
 
 function App() {
+    const [isLoggedIn, setIsLoggedIn] = useState(false);
+    useEffect(() => {
+        const token = getCookie('Jwt');
+        setIsLoggedIn(!!token);
+    }, []);
+
   return (
     <div className="App">
-      <Navbar />
+      {isLoggedIn ? <Navbar /> : <NavbarRegistrationAndLogin />}
       <Routes>
         <Route path="/" element={<Home />} />
         <Route path="/garten" element={<Garten />} />
diff --git a/growbros-frontend/src/components/NavbarRegistrationAndLogin.tsx b/growbros-frontend/src/components/NavbarRegistrationAndLogin.tsx
new file mode 100644
index 0000000..ff89b21
--- /dev/null
+++ b/growbros-frontend/src/components/NavbarRegistrationAndLogin.tsx
@@ -0,0 +1,26 @@
+import {NavLink} from "react-router-dom";
+
+function NavbarRegistrationAndLogin() {
+    return (
+        <nav>
+            <ul>
+                <li>
+                    <NavLink className="title" to="/">
+                        GrowBros
+                    </NavLink>
+                </li>
+                <div className="navLinks">
+                    <li>
+                        <NavLink to="/api/v1/auth/register">Registrieren</NavLink>
+                    </li>
+
+                    <li>
+                        <NavLink to="/api/v1/auth/authenticate">Login</NavLink>
+                    </li>
+                </div>
+            </ul>
+        </nav>
+    );
+}
+
+export default NavbarRegistrationAndLogin;
\ No newline at end of file
diff --git a/growbros-frontend/src/jwt/Cookies.ts b/growbros-frontend/src/jwt/Cookies.ts
index a4e4da6..401677a 100644
--- a/growbros-frontend/src/jwt/Cookies.ts
+++ b/growbros-frontend/src/jwt/Cookies.ts
@@ -10,23 +10,14 @@ export function setCookie(name: string, value: any, daysToLive: number){
 export function getCookie(name: string | any[]){
 
     const cDecoded = decodeURIComponent(document.cookie);
-
     const cArray = cDecoded.split("; ");
-
     let result = null;
 
-
-
     cArray.forEach(element => {
 
         if(element.indexOf(<string>name) == 0){
-
             result = element.substring(name.length + 1)
-
         }
-
     })
-
     return result;
-
 }
diff --git a/growbros-frontend/src/pages/Register.tsx b/growbros-frontend/src/pages/Register.tsx
index a3e0107..5aa9697 100644
--- a/growbros-frontend/src/pages/Register.tsx
+++ b/growbros-frontend/src/pages/Register.tsx
@@ -1,29 +1,45 @@
-import {useState} from "react";
+import {FormEvent, useState} from "react";
 import {setCookie} from "../jwt/Cookies.ts";
+import { useNavigate } from 'react-router-dom';
 
 function Register() {
+    const navigate = useNavigate();
+
     const [firstname, setFirstname] = useState('');
     const [lastname, setLastname] = useState('');
     const [email, setEmail] = useState('');
     const [password, setPassword] = useState('');
 
-    const handleSubmit = async (e: { preventDefault: () => void; }) => {
+    const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
         e.preventDefault(); //verhindert, dass die Seite neu geladen wird, wenn das Formular abgeschickt wird
         await handleRegister();
     };
+
     const handleRegister = async () => {
+        console.log("handle register")
         try {
-            const res = await fetch("http://localhost:8080/api/v1/auth/register",
-                {method:"POST",body:JSON.stringify({
-                    firstname:firstname,
-                    lastname:lastname,
-                    email:email,
-                    password:password})})
+            const requestBody = {
+                firstname:firstname,
+                lastname:lastname,
+                email:email,
+                password:password
+            };
+            console.log(requestBody)
+            const res = await fetch("http://localhost:8080/api/v1/auth/register", {
+                    method:"POST",
+                    headers: {
+                        "Content-Type": "application/json"
+                    },
+                    body:JSON.stringify(requestBody
+                    )}
+            )
             const {token} = await res.json();
             setCookie("Jwt",token, 1);
             console.log(token);
+            navigate('/');
         } catch (error:any) {
             console.error('Fehler bei der Anmeldung:', error.message);
+            console.dir(error)
         }
     };
 
@@ -31,7 +47,7 @@ function Register() {
         <main>
             <div>
                 <h2>Login</h2>
-                <form>
+                <form onSubmit={handleSubmit}>
                     <div>
                         <label>Vorname:</label>
                         <input
@@ -65,9 +81,7 @@ function Register() {
                         />
                     </div>
                     <div>
-                        <form onSubmit={handleSubmit}>
                             <button type="submit">Anmelden</button>
-                        </form>
                     </div>
                 </form>
             </div>
diff --git a/src/main/java/hdm/mi/growbros/controllers/AuthenticationController.java b/src/main/java/hdm/mi/growbros/controllers/AuthenticationController.java
index 207ba55..2bafd5d 100644
--- a/src/main/java/hdm/mi/growbros/controllers/AuthenticationController.java
+++ b/src/main/java/hdm/mi/growbros/controllers/AuthenticationController.java
@@ -6,27 +6,25 @@ import hdm.mi.growbros.auth.AuthenticationService;
 import hdm.mi.growbros.auth.RegisterRequest;
 import lombok.RequiredArgsConstructor;
 import org.springframework.http.ResponseEntity;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
 
 @RestController
+@CrossOrigin
 @RequestMapping("/api/v1/auth")
 @RequiredArgsConstructor
 public class AuthenticationController {
-    private final AuthenticationService service;
+    private final AuthenticationService authenticationService;
     @PostMapping("/register")
     public ResponseEntity<AuthenticationResponse> register(
          @RequestBody RegisterRequest request
     ) {
-        return ResponseEntity.ok(service.register(request));
+        return ResponseEntity.ok(authenticationService.register(request));
     }
 
     @PostMapping("/authenticate")
     public ResponseEntity<AuthenticationResponse> authenticate(
             @RequestBody AuthenticationRequest request
     ) {
-        return ResponseEntity.ok(service.authenticate(request));
+        return ResponseEntity.ok(authenticationService.authenticate(request));
     }
 }
-- 
GitLab