From 36dd32b8bb9afb2d00c04ff7e3c8c76e3434d40c Mon Sep 17 00:00:00 2001
From: jejejery <13521131@std.stei.itb.ac.id>
Date: Thu, 16 Nov 2023 06:14:58 +0700
Subject: [PATCH] add: auth for main and search

---
 src/components/Navbar/Navbar.tsx |  3 +--
 src/config/configs.ts            |  9 ++++++++-
 src/pages/Login/Login.tsx        |  2 +-
 src/pages/Main/Main.tsx          |  5 +++--
 src/pages/Search/Search.tsx      |  4 ++--
 src/pages/Top Up/TopUp.tsx       | 13 ++++---------
 6 files changed, 19 insertions(+), 17 deletions(-)

diff --git a/src/components/Navbar/Navbar.tsx b/src/components/Navbar/Navbar.tsx
index c2759db..50cb96c 100644
--- a/src/components/Navbar/Navbar.tsx
+++ b/src/components/Navbar/Navbar.tsx
@@ -16,7 +16,6 @@ import { Box,
 import React, {
 } from "react";
 
-import { Navigate, BrowserRouter as Router, Routes, Route } from 'react-router-dom';
 
 import _ from 'lodash';
 
@@ -212,7 +211,7 @@ render(): React.ReactNode {
         window.innerWidth> 1280 ? this.laptopMenu() : this.mobileMenu()
     }
     {
-        this.state.search !== '' ? <Navigate to={`/search?title=${this.state.search}`} /> : null
+        this.state.search !== '' ? window.location.href = `/search?title=${this.state.search}` : null
     }
  </Box>
     )
diff --git a/src/config/configs.ts b/src/config/configs.ts
index 7d33a2f..05b928d 100644
--- a/src/config/configs.ts
+++ b/src/config/configs.ts
@@ -1,3 +1,10 @@
+import CookieManager from "../auth/cookie"; 
 
+export const restUrl = `http://localhost:${import.meta.env.VITE_SPOTYPHIE_REST_PORT_HOST}`;
 
-export const restUrl = `http://localhost:${import.meta.env.VITE_SPOTYPHIE_REST_PORT_HOST}`;
\ No newline at end of file
+export const authHeader = {
+    headers: {
+      Authorization: `Bearer ${CookieManager.readCookie('token')}`,
+      'Content-Type': 'application/json',
+    },
+};
\ No newline at end of file
diff --git a/src/pages/Login/Login.tsx b/src/pages/Login/Login.tsx
index 16ed6d4..c8a8fb8 100644
--- a/src/pages/Login/Login.tsx
+++ b/src/pages/Login/Login.tsx
@@ -62,7 +62,7 @@ class Login extends React.Component <{}, {isLogin : boolean, failLogin : string}
         // Check if isLogin state has changed
         if (this.state.isLogin && this.state.isLogin !== prevState.isLogin) {
             // Navigate to the Main page
-            window.location.href = "/Main";
+            window.location.href = "/";
         }
     }
     
diff --git a/src/pages/Main/Main.tsx b/src/pages/Main/Main.tsx
index 31429df..a46b74a 100644
--- a/src/pages/Main/Main.tsx
+++ b/src/pages/Main/Main.tsx
@@ -2,7 +2,7 @@ import React, { useEffect, useState } from 'react';
 import { Box, Button, Center, Flex, Grid, GridItem, Heading, Image } from '@chakra-ui/react';
 import axios from 'axios';
 import Navbar from '../../components/Navbar/Navbar';
-import { restUrl } from '../../config/configs';
+import { restUrl, authHeader } from '../../config/configs';
 
 const Main: React.FC = () => {
     const [forYou, setForYou] = useState<any[]>([]);
@@ -13,7 +13,8 @@ const Main: React.FC = () => {
 
         const fetchData = async () => {
             try {
-                const response = await axios.get(`${restUrl}/main`);
+                
+                const response = await axios.get(`${restUrl}/main`, authHeader);
                 setForYou(response.data.for_you);
                 setTopSongs(response.data.top_song);
                 console.log(response.data);
diff --git a/src/pages/Search/Search.tsx b/src/pages/Search/Search.tsx
index ced65ff..6a5affc 100644
--- a/src/pages/Search/Search.tsx
+++ b/src/pages/Search/Search.tsx
@@ -2,7 +2,7 @@ import React, { useEffect, useState } from 'react';
 import { Box, Button, Center, Flex, Grid, GridItem, Heading, Image } from '@chakra-ui/react';
 import Navbar from '../../components/Navbar/Navbar';
 import axios from 'axios';
-import { restUrl } from '../../config/configs';
+import { restUrl, authHeader } from '../../config/configs';
 
 const Search: React.FC = () => {
     const [songRenderer, setSongRenderer] = useState<React.ReactNode[]>([]);
@@ -36,7 +36,7 @@ const Search: React.FC = () => {
             try {
                 const params = new URLSearchParams(window.location.search);
                 const paramsObj = Object.fromEntries(params.entries());
-                const res = await axios.get(`${restUrl}/search?title=${paramsObj.title}`);
+                const res = await axios.get(`${restUrl}/search?title=${paramsObj.title}`, authHeader);
 
                 setSongRenderer(renderSongs(res.data));
             } catch (error) {
diff --git a/src/pages/Top Up/TopUp.tsx b/src/pages/Top Up/TopUp.tsx
index a973caf..441e98f 100644
--- a/src/pages/Top Up/TopUp.tsx	
+++ b/src/pages/Top Up/TopUp.tsx	
@@ -2,7 +2,7 @@ import React, { useState } from 'react';
 import { Box, Flex, Heading, Text, Select, Input, Button } from '@chakra-ui/react';
 import Navbar from "../../components/Navbar/Navbar";
 import axios, { AxiosError } from 'axios';
-import { restUrl} from '../../config/configs';
+import { restUrl, authHeader} from '../../config/configs';
 import CookieManager from '../../auth/cookie';
 
 const TopUp: React.FC = () => {
@@ -64,12 +64,7 @@ const TopUp: React.FC = () => {
       setError('');
 
       const topUpUrl = `${restUrl}/topup`;
-      const topUpHeader = {
-        headers: {
-          'Content-Type': 'application/json',
-          Authorization: `Bearer ${CookieManager.readCookie('token')}`,
-        },
-      };
+      const topUpHeader = authHeader;
 
       const topUpData = {
         user_id: parseInt(localStorage.getItem('user_id') as string),
@@ -86,10 +81,10 @@ const TopUp: React.FC = () => {
     }
     catch(e : any){
       if(e.response.status === 401){
-        alert('Top-up failed! token is deprecated!');
+        alert('top up failed! token is deprecated!');
       }
       else if(e.response.status === 403){
-        alert('Top-up failed! invalid token!');
+        alert('top up failed! invalid token!');
       }
         localStorage.clear();
         window.location.href = '/';
-- 
GitLab