From af7010500ab0e347c6bc2f583eafa2d41902f507 Mon Sep 17 00:00:00 2001
From: DewanaGustavus <76590469+DewanaGustavus@users.noreply.github.com>
Date: Fri, 17 Nov 2023 13:21:57 +0700
Subject: [PATCH] feat: integrate jwt

---
 src/api/History.ts                 |  8 +++++---
 src/components/Navbar.tsx          |  2 +-
 src/interfaces/UserInterface.ts    |  2 +-
 src/pages/AvailableOrderDetail.tsx |  6 +++---
 src/pages/Balance.tsx              | 12 ++++++------
 src/pages/History.tsx              |  4 +---
 src/pages/Login.tsx                |  6 +++---
 src/pages/PickedOrder.tsx          |  4 ++--
 src/pages/Profile.tsx              |  3 ++-
 src/pages/Register.tsx             |  4 ++--
 src/utils/History.ts               |  4 ++--
 src/utils/LocalStorage.ts          |  9 ++++++---
 src/utils/Login.ts                 |  6 ++----
 13 files changed, 36 insertions(+), 34 deletions(-)

diff --git a/src/api/History.ts b/src/api/History.ts
index 41c7f69..97a9420 100644
--- a/src/api/History.ts
+++ b/src/api/History.ts
@@ -1,13 +1,15 @@
 import axios from "axios";
 import HistoryInterface from "../interfaces/HistoryInterface";
 import HistoryDetailInterface from "../interfaces/HistoryDetailInterface";
+import { getUser } from "../utils/LocalStorage";
 
 const REST_URL = "http://localhost:5000"; // TODO : using env
 
-export async function fetchHistory(username : string) {
+export async function fetchHistory() {
     try {
-        const API_URL = REST_URL + "/history/" + username;
-        const response = await axios.get<HistoryInterface[]>(API_URL);
+        const API_URL = REST_URL + "/history";
+        let header = { headers: {"Authorization" : `Bearer ${getUser().jwt}`} };
+        const response = await axios.get<HistoryInterface[]>(API_URL, header);
         return response;
     } catch(err) {
         alert(err);
diff --git a/src/components/Navbar.tsx b/src/components/Navbar.tsx
index 87c79d2..27297a7 100644
--- a/src/components/Navbar.tsx
+++ b/src/components/Navbar.tsx
@@ -92,7 +92,7 @@ export default function Navbar() {
             _hover={{
               bg: 'pink.300',
             }}>
-            {getUser()}
+            {getUser().username}
           </Button>
           <Button
             as={'a'}
diff --git a/src/interfaces/UserInterface.ts b/src/interfaces/UserInterface.ts
index 4a1de14..8af9458 100644
--- a/src/interfaces/UserInterface.ts
+++ b/src/interfaces/UserInterface.ts
@@ -1,6 +1,6 @@
 
 export default interface UserInterface {
-    id : number
+    id ?: number
     username : string
     name : string
     email : string
diff --git a/src/pages/AvailableOrderDetail.tsx b/src/pages/AvailableOrderDetail.tsx
index 7fd9a22..546e393 100644
--- a/src/pages/AvailableOrderDetail.tsx
+++ b/src/pages/AvailableOrderDetail.tsx
@@ -29,13 +29,13 @@ export default function AvailableOrderDetail() {
   const navigate = useNavigate();
 
   function pickOrderAction() {
-    const username = getUser();
-    if(!username) {
+    const user = getUser();
+    if(!user.username) {
       alert("Perlu log in");
       return;
     }
     
-    pickOrder(orderId, username);
+    pickOrder(orderId, user.username);
     navigate("/PickedOrder");
   }
 
diff --git a/src/pages/Balance.tsx b/src/pages/Balance.tsx
index 0908398..a6c1f4e 100644
--- a/src/pages/Balance.tsx
+++ b/src/pages/Balance.tsx
@@ -15,16 +15,16 @@ import { getBalance, withdrawFunction } from '../utils/Balance';
 import { getUser } from '../utils/LocalStorage';
 
 export default function Balance() {
-  const username = getUser();
+  const user = getUser();
   const [balance, setBalance] = useState(0);
   const [withdrawBalance, setWithdrawBalance] = useState(0);
   
   function handleSubmit() {
-    if(!username) {
+    if(!user.username) {
       alert("Perlu login");
       return;
     }
-    const response = withdrawFunction(username, withdrawBalance);
+    const response = withdrawFunction(user.username, withdrawBalance);
     response.then((success) => {
       if(success) {
         setBalance(balance - withdrawBalance);
@@ -36,15 +36,15 @@ export default function Balance() {
   }
 
   useEffect(() => {
-    if(!username) {
+    if(!user.username) {
       alert("Perlu login");
       return;
     }
-    getBalance(username).then((res) => {
+    getBalance(user.username).then((res) => {
       console.log(res);
       setBalance(res.data);
     });
-  }, [username]);
+  }, [user]);
 
   return (
     <Flex
diff --git a/src/pages/History.tsx b/src/pages/History.tsx
index ad57adf..99420f6 100644
--- a/src/pages/History.tsx
+++ b/src/pages/History.tsx
@@ -6,16 +6,14 @@ import {
 import HistoryInterface from '../interfaces/HistoryInterface';
 import { useEffect, useState } from 'react'
 import HistoryCard from '../components/HistoryCard';
-import { getUser } from '../utils/LocalStorage';
 import { getHistory } from '../utils/History';
 
 
 export default function History() {
-  const username = getUser();
   const [histories, setHistories] = useState<HistoryInterface[]>([]);
 
   useEffect(() => {
-    const response = getHistory(username ? username : "");
+    const response = getHistory();
     response.then((history) => {
       setHistories(history);
     });
diff --git a/src/pages/Login.tsx b/src/pages/Login.tsx
index 0b9985d..f1aa334 100644
--- a/src/pages/Login.tsx
+++ b/src/pages/Login.tsx
@@ -43,9 +43,9 @@ export default function Login() {
     if(usernameValid) {
       const response = validateLogin(formData.username,
                                       formData.password);
-      response.then((success) => {
-        if(success) {
-          setUser(formData.username);
+      response.then((responseData) => {
+        if(responseData !== "gagal") {
+          setUser(formData.username, responseData);
           navigate('/');
         }else {
           setPasswordValid(false);
diff --git a/src/pages/PickedOrder.tsx b/src/pages/PickedOrder.tsx
index 3f37944..dc72fa8 100644
--- a/src/pages/PickedOrder.tsx
+++ b/src/pages/PickedOrder.tsx
@@ -12,11 +12,11 @@ import { getUserDetail } from '../utils/Profile';
 
 
 export default function PickedOrder() {
-  const username = getUser();
+  const user = getUser();
   const [orders, setOrders] = useState<OrderInterface[]>([]);
 
   useEffect(() => {
-    getUserDetail(username ? username : "").then(
+    getUserDetail(user.username ? user.username : "").then(
       (userDetail) => {
         const response = getOrderByCourier(userDetail.data.id);
         response.then((order) => {
diff --git a/src/pages/Profile.tsx b/src/pages/Profile.tsx
index df775ad..c8d3a56 100644
--- a/src/pages/Profile.tsx
+++ b/src/pages/Profile.tsx
@@ -22,7 +22,8 @@ import { validateEmail } from '../utils/Login';
 
 
 export default function Profile() {
-  const username = getUser();
+  const user = getUser();
+  const username = user.username;
   const [isEditing, setIsEditing] = useState(false);
   const [userDetail, setUserDetail] = useState<UserInterface>({username : "",
                                                                 name : "",
diff --git a/src/pages/Register.tsx b/src/pages/Register.tsx
index 62548a8..a3fe10c 100644
--- a/src/pages/Register.tsx
+++ b/src/pages/Register.tsx
@@ -61,8 +61,8 @@ export default function Register() {
                                         formData.name,
                                         formData.email,
                                         formData.password);
-      response.then(() => {
-        setUser(formData.username);
+      response.then((res) => {
+        setUser(formData.username, res);
         navigate('/');
       });
     }
diff --git a/src/utils/History.ts b/src/utils/History.ts
index f366baa..d676c17 100644
--- a/src/utils/History.ts
+++ b/src/utils/History.ts
@@ -1,7 +1,7 @@
 import { fetchHistory, fetchHistoryById, fetchHistoryDetails } from "../api/History";
 
-export async function getHistory(username : string) {
-    const response = await fetchHistory(username);
+export async function getHistory() {
+    const response = await fetchHistory();
     const histories = response.data;
     return histories;
 }
diff --git a/src/utils/LocalStorage.ts b/src/utils/LocalStorage.ts
index a82db20..acd397f 100644
--- a/src/utils/LocalStorage.ts
+++ b/src/utils/LocalStorage.ts
@@ -1,19 +1,22 @@
 
-export function setUser(username : string) {
+export function setUser(username : string, jwt : string) {
     // TODO : async issue
     localStorage.setItem('username', username);
+    localStorage.setItem('jwt', jwt);
 }
 
 export function unsetUser() {
     localStorage.removeItem('username');
+    localStorage.removeItem('jwt');
 }
 
 export function getUser() {
     const username = localStorage.getItem('username');
-    return username;
+    const jwt = localStorage.getItem('jwt');
+    return {username, jwt};
 }
 
 export function isLoggedIn() {
-    const loggedIn = (getUser() !== null);
+    const loggedIn = (getUser().jwt !== null);
     return loggedIn;
 }
diff --git a/src/utils/Login.ts b/src/utils/Login.ts
index 9a84b4e..6e51a62 100644
--- a/src/utils/Login.ts
+++ b/src/utils/Login.ts
@@ -19,12 +19,10 @@ export function validateConfirmPassword(password : string, confirmPassword : str
 
 export async function validateRegister(username : string, name : string, email : string, password : string) {
     const response = await register(username, name, email, password);
-    const success = (response.data === "success");
-    return success;
+    return response.data;
 }
 
 export async function validateLogin(username : string, password : string) {
     const response = await login(username, password);
-    const success = (response.data === "success");
-    return success;
+    return response.data;
 }
-- 
GitLab