mirror of
https://github.com/TurTaskProject/TurTaskWeb.git
synced 2025-12-19 22:14:07 +01:00
Merge pull request #56 from TurTaskProject/feature/user-authentication
Fix Bug when logout
This commit is contained in:
commit
aa2dd95f94
@ -1,6 +1,6 @@
|
|||||||
from django.urls import path
|
from django.urls import path
|
||||||
from rest_framework_simplejwt import views as jwt_views
|
from rest_framework_simplejwt import views as jwt_views
|
||||||
from authentications.views import ObtainTokenPairWithCustomView, GreetingView, GoogleLogin, GoogleRetrieveUserInfo
|
from authentications.views import ObtainTokenPairWithCustomView, GreetingView, GoogleLogin, GoogleRetrieveUserInfo, CheckAccessTokenAndRefreshToken
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path('token/obtain/', jwt_views.TokenObtainPairView.as_view(), name='token_create'),
|
path('token/obtain/', jwt_views.TokenObtainPairView.as_view(), name='token_create'),
|
||||||
@ -9,4 +9,5 @@ urlpatterns = [
|
|||||||
path('hello/', GreetingView.as_view(), name='hello_world'),
|
path('hello/', GreetingView.as_view(), name='hello_world'),
|
||||||
path('dj-rest-auth/google/', GoogleLogin.as_view(), name="google_login"),
|
path('dj-rest-auth/google/', GoogleLogin.as_view(), name="google_login"),
|
||||||
path('auth/google/', GoogleRetrieveUserInfo.as_view()),
|
path('auth/google/', GoogleRetrieveUserInfo.as_view()),
|
||||||
|
path('auth/status/', CheckAccessTokenAndRefreshToken.as_view(), name='check_token_status')
|
||||||
]
|
]
|
||||||
@ -1,6 +1,3 @@
|
|||||||
from django.shortcuts import render
|
|
||||||
|
|
||||||
# Create your views here.
|
|
||||||
"""This module defines API views for authentication, user creation, and a simple hello message."""
|
"""This module defines API views for authentication, user creation, and a simple hello message."""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
@ -14,6 +11,8 @@ from rest_framework.permissions import IsAuthenticated, AllowAny
|
|||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.views import APIView
|
from rest_framework.views import APIView
|
||||||
from rest_framework_simplejwt.tokens import RefreshToken
|
from rest_framework_simplejwt.tokens import RefreshToken
|
||||||
|
from rest_framework_simplejwt.authentication import JWTAuthentication
|
||||||
|
|
||||||
|
|
||||||
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
|
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
|
||||||
|
|
||||||
@ -27,6 +26,31 @@ from users.managers import CustomAccountManager
|
|||||||
from users.models import CustomUser
|
from users.models import CustomUser
|
||||||
|
|
||||||
|
|
||||||
|
class CheckAccessTokenAndRefreshToken(APIView):
|
||||||
|
permission_classes = (AllowAny,)
|
||||||
|
JWT_authenticator = JWTAuthentication()
|
||||||
|
|
||||||
|
def post(self, request, *args, **kwargs):
|
||||||
|
access_token = request.data.get('access_token')
|
||||||
|
refresh_token = request.data.get('refresh_token')
|
||||||
|
# Check if the access token is valid
|
||||||
|
if access_token:
|
||||||
|
response = self.JWT_authenticator.authenticate(request)
|
||||||
|
if response is not None:
|
||||||
|
return Response({'status': 'true'}, status=status.HTTP_200_OK)
|
||||||
|
|
||||||
|
# Check if the refresh token is valid
|
||||||
|
if refresh_token:
|
||||||
|
try:
|
||||||
|
refresh = RefreshToken(refresh_token)
|
||||||
|
access_token = str(refresh.access_token)
|
||||||
|
return Response({'access_token': access_token}, status=status.HTTP_200_OK)
|
||||||
|
except Exception as e:
|
||||||
|
return Response({'status': 'false'}, status=status.HTTP_401_UNAUTHORIZED)
|
||||||
|
|
||||||
|
return Response({'status': 'false'}, status=status.HTTP_400_BAD_REQUEST)
|
||||||
|
|
||||||
|
|
||||||
class ObtainTokenPairWithCustomView(APIView):
|
class ObtainTokenPairWithCustomView(APIView):
|
||||||
"""
|
"""
|
||||||
Custom Token Obtain Pair View.
|
Custom Token Obtain Pair View.
|
||||||
@ -165,4 +189,4 @@ class GoogleRetrieveUserInfo(APIView):
|
|||||||
response = requests.get(api_url, headers=headers)
|
response = requests.get(api_url, headers=headers)
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
return response.json()
|
return response.json()
|
||||||
raise Exception('Google API Error', response)
|
raise Exception('Google API Error', response)
|
||||||
8
frontend/jsconfig.json
Normal file
8
frontend/jsconfig.json
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"baseUrl": ".",
|
||||||
|
"paths": {
|
||||||
|
"src/*": ["./src/*"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -37,6 +37,7 @@
|
|||||||
"framer-motion": "^10.16.4",
|
"framer-motion": "^10.16.4",
|
||||||
"gapi-script": "^1.2.0",
|
"gapi-script": "^1.2.0",
|
||||||
"jwt-decode": "^4.0.0",
|
"jwt-decode": "^4.0.0",
|
||||||
|
"prop-types": "^15.8.1",
|
||||||
"react": "^18.2.0",
|
"react": "^18.2.0",
|
||||||
"react-beautiful-dnd": "^13.1.1",
|
"react-beautiful-dnd": "^13.1.1",
|
||||||
"react-bootstrap": "^2.9.1",
|
"react-bootstrap": "^2.9.1",
|
||||||
|
|||||||
@ -86,6 +86,9 @@ dependencies:
|
|||||||
jwt-decode:
|
jwt-decode:
|
||||||
specifier: ^4.0.0
|
specifier: ^4.0.0
|
||||||
version: 4.0.0
|
version: 4.0.0
|
||||||
|
prop-types:
|
||||||
|
specifier: ^15.8.1
|
||||||
|
version: 15.8.1
|
||||||
react:
|
react:
|
||||||
specifier: ^18.2.0
|
specifier: ^18.2.0
|
||||||
version: 18.2.0
|
version: 18.2.0
|
||||||
@ -3380,14 +3383,6 @@ packages:
|
|||||||
warning: 4.0.3
|
warning: 4.0.3
|
||||||
dev: false
|
dev: false
|
||||||
|
|
||||||
/react-day-picker@8.9.1(date-fns@2.30.0)(react@18.2.0):
|
|
||||||
resolution: {integrity: sha512-W0SPApKIsYq+XCtfGeMYDoU0KbsG3wfkYtlw8l+vZp6KoBXGOlhzBUp4tNx1XiwiOZwhfdGOlj7NGSCKGSlg5Q==}
|
|
||||||
peerDependencies:
|
|
||||||
date-fns: ^2.28.0
|
|
||||||
react: ^16.8.0 || ^17.0.0 || ^18.0.0
|
|
||||||
dependencies:
|
|
||||||
date-fns: 2.30.0
|
|
||||||
react: 18.2.0
|
|
||||||
/react-calendar@4.6.1(@types/react@18.2.37)(react-dom@18.2.0)(react@18.2.0):
|
/react-calendar@4.6.1(@types/react@18.2.37)(react-dom@18.2.0)(react@18.2.0):
|
||||||
resolution: {integrity: sha512-MvCPdvxEvq7wICBhFxlYwxS2+IsVvSjTcmlr0Kl3yDRVhoX7btNg0ySJx5hy9rb1eaM4nDpzQcW5c87nfQ8n8w==}
|
resolution: {integrity: sha512-MvCPdvxEvq7wICBhFxlYwxS2+IsVvSjTcmlr0Kl3yDRVhoX7btNg0ySJx5hy9rb1eaM4nDpzQcW5c87nfQ8n8w==}
|
||||||
peerDependencies:
|
peerDependencies:
|
||||||
@ -3479,6 +3474,16 @@ packages:
|
|||||||
- '@types/react-dom'
|
- '@types/react-dom'
|
||||||
dev: false
|
dev: false
|
||||||
|
|
||||||
|
/react-day-picker@8.9.1(date-fns@2.30.0)(react@18.2.0):
|
||||||
|
resolution: {integrity: sha512-W0SPApKIsYq+XCtfGeMYDoU0KbsG3wfkYtlw8l+vZp6KoBXGOlhzBUp4tNx1XiwiOZwhfdGOlj7NGSCKGSlg5Q==}
|
||||||
|
peerDependencies:
|
||||||
|
date-fns: ^2.28.0
|
||||||
|
react: ^16.8.0 || ^17.0.0 || ^18.0.0
|
||||||
|
dependencies:
|
||||||
|
date-fns: 2.30.0
|
||||||
|
react: 18.2.0
|
||||||
|
dev: false
|
||||||
|
|
||||||
/react-dom@18.2.0(react@18.2.0):
|
/react-dom@18.2.0(react@18.2.0):
|
||||||
resolution: {integrity: sha512-6IMTriUmvsjHUjNtEDudZfuDQUoWXVxKHhlEGSk81n4YFS+r/Kl99wXiwlVXtPBtJenozv2P+hxDsw9eA7Xo6g==}
|
resolution: {integrity: sha512-6IMTriUmvsjHUjNtEDudZfuDQUoWXVxKHhlEGSk81n4YFS+r/Kl99wXiwlVXtPBtJenozv2P+hxDsw9eA7Xo6g==}
|
||||||
peerDependencies:
|
peerDependencies:
|
||||||
@ -3511,8 +3516,6 @@ packages:
|
|||||||
tiny-warning: 1.0.3
|
tiny-warning: 1.0.3
|
||||||
dev: false
|
dev: false
|
||||||
|
|
||||||
/react-icons@4.11.0(react@18.2.0):
|
|
||||||
resolution: {integrity: sha512-V+4khzYcE5EBk/BvcuYRq6V/osf11ODUM2J8hg2FDSswRrGvqiYUYPRy4OdrWaQOBj4NcpJfmHZLNaD+VH0TyA==}
|
|
||||||
/react-icons@4.12.0(react@18.2.0):
|
/react-icons@4.12.0(react@18.2.0):
|
||||||
resolution: {integrity: sha512-IBaDuHiShdZqmfc/TwHu6+d6k2ltNCf3AszxNmjJc1KUfXdEeRJOKyNvLmAHaarhzGmTSVygNdyu8/opXv2gaw==}
|
resolution: {integrity: sha512-IBaDuHiShdZqmfc/TwHu6+d6k2ltNCf3AszxNmjJc1KUfXdEeRJOKyNvLmAHaarhzGmTSVygNdyu8/opXv2gaw==}
|
||||||
peerDependencies:
|
peerDependencies:
|
||||||
@ -3611,18 +3614,6 @@ packages:
|
|||||||
react-transition-group: 2.9.0(react-dom@18.2.0)(react@18.2.0)
|
react-transition-group: 2.9.0(react-dom@18.2.0)(react@18.2.0)
|
||||||
dev: false
|
dev: false
|
||||||
|
|
||||||
/react-transition-group@2.9.0(react-dom@18.2.0)(react@18.2.0):
|
|
||||||
resolution: {integrity: sha512-+HzNTCHpeQyl4MJ/bdE0u6XRMe9+XG/+aL4mCxVN4DnPBQ0/5bfHWPDuOZUzYdMj94daZaZdCCc1Dzt9R/xSSg==}
|
|
||||||
peerDependencies:
|
|
||||||
react: '>=15.0.0'
|
|
||||||
react-dom: '>=15.0.0'
|
|
||||||
dependencies:
|
|
||||||
dom-helpers: 3.4.0
|
|
||||||
loose-envify: 1.4.0
|
|
||||||
prop-types: 15.8.1
|
|
||||||
react: 18.2.0
|
|
||||||
react-dom: 18.2.0(react@18.2.0)
|
|
||||||
react-lifecycles-compat: 3.0.4
|
|
||||||
/react-time-picker@6.5.2(@types/react-dom@18.2.15)(@types/react@18.2.37)(react-dom@18.2.0)(react@18.2.0):
|
/react-time-picker@6.5.2(@types/react-dom@18.2.15)(@types/react@18.2.37)(react-dom@18.2.0)(react@18.2.0):
|
||||||
resolution: {integrity: sha512-xRamxjndpq3HfnEL+6T3VyirLMEn4D974OJgs9sTP8iJX/RB02rmwy09C9oBThTGuN3ycbozn06iYLn148vcdw==}
|
resolution: {integrity: sha512-xRamxjndpq3HfnEL+6T3VyirLMEn4D974OJgs9sTP8iJX/RB02rmwy09C9oBThTGuN3ycbozn06iYLn148vcdw==}
|
||||||
peerDependencies:
|
peerDependencies:
|
||||||
@ -3648,6 +3639,20 @@ packages:
|
|||||||
- '@types/react-dom'
|
- '@types/react-dom'
|
||||||
dev: false
|
dev: false
|
||||||
|
|
||||||
|
/react-transition-group@2.9.0(react-dom@18.2.0)(react@18.2.0):
|
||||||
|
resolution: {integrity: sha512-+HzNTCHpeQyl4MJ/bdE0u6XRMe9+XG/+aL4mCxVN4DnPBQ0/5bfHWPDuOZUzYdMj94daZaZdCCc1Dzt9R/xSSg==}
|
||||||
|
peerDependencies:
|
||||||
|
react: '>=15.0.0'
|
||||||
|
react-dom: '>=15.0.0'
|
||||||
|
dependencies:
|
||||||
|
dom-helpers: 3.4.0
|
||||||
|
loose-envify: 1.4.0
|
||||||
|
prop-types: 15.8.1
|
||||||
|
react: 18.2.0
|
||||||
|
react-dom: 18.2.0(react@18.2.0)
|
||||||
|
react-lifecycles-compat: 3.0.4
|
||||||
|
dev: false
|
||||||
|
|
||||||
/react-transition-group@4.4.5(react-dom@18.2.0)(react@18.2.0):
|
/react-transition-group@4.4.5(react-dom@18.2.0)(react@18.2.0):
|
||||||
resolution: {integrity: sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g==}
|
resolution: {integrity: sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g==}
|
||||||
peerDependencies:
|
peerDependencies:
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
|
import { useEffect } from "react";
|
||||||
import "./App.css";
|
import "./App.css";
|
||||||
import { Route, Routes, useLocation } from "react-router-dom";
|
import { Route, Routes } from "react-router-dom";
|
||||||
|
import axios from "axios";
|
||||||
import TestAuth from "./components/testAuth";
|
import TestAuth from "./components/testAuth";
|
||||||
import LoginPage from "./components/authentication/LoginPage";
|
import LoginPage from "./components/authentication/LoginPage";
|
||||||
import SignUpPage from "./components/authentication/SignUpPage";
|
import SignUpPage from "./components/authentication/SignUpPage";
|
||||||
@ -13,18 +14,66 @@ import PrivateRoute from "./PrivateRoute";
|
|||||||
import ProfileUpdatePage from "./components/profilePage";
|
import ProfileUpdatePage from "./components/profilePage";
|
||||||
import Dashboard from "./components/dashboard/dashboard";
|
import Dashboard from "./components/dashboard/dashboard";
|
||||||
|
|
||||||
|
import { useAuth } from "./hooks/AuthHooks";
|
||||||
|
|
||||||
const App = () => {
|
const App = () => {
|
||||||
const location = useLocation();
|
const { isAuthenticated, setIsAuthenticated } = useAuth();
|
||||||
const prevention = ["/login", "/signup"];
|
|
||||||
const isLoginPageOrSignUpPage = prevention.some(_ => location.pathname.includes(_));
|
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const checkLoginStatus = async () => {
|
||||||
|
const data = {
|
||||||
|
access_token: localStorage.getItem("access_token"),
|
||||||
|
refresh_token: localStorage.getItem("refresh_token"),
|
||||||
|
};
|
||||||
|
|
||||||
|
await axios
|
||||||
|
.post("http://127.0.0.1:8000/api/auth/status/", data, {
|
||||||
|
headers: {
|
||||||
|
Authorization: "Bearer " + localStorage.getItem("access_token"),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.then((response) => {
|
||||||
|
if (response.status === 200) {
|
||||||
|
if (response.data.access_token) {
|
||||||
|
localStorage.setItem("access_token", response.data.access_token);
|
||||||
|
setIsAuthenticated(true);
|
||||||
|
} else {
|
||||||
|
setIsAuthenticated(true);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
setIsAuthenticated(false);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.error("Error checking login status:", error.message);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
checkLoginStatus();
|
||||||
|
}, [setIsAuthenticated]);
|
||||||
|
|
||||||
|
return <div>{isAuthenticated ? <AuthenticatedComponents /> : <NonAuthenticatedComponents />}</div>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const NonAuthenticatedComponents = () => {
|
||||||
return (
|
return (
|
||||||
<div className={isLoginPageOrSignUpPage ? "" : "display: flex"}>
|
<div>
|
||||||
{!isLoginPageOrSignUpPage && <IconSideNav />}
|
<NavBar />
|
||||||
<div className={isLoginPageOrSignUpPage ? "" : "flex-1 ml-[76px] overflow-hidden"}>
|
<Routes>
|
||||||
|
<Route path="/login" element={<LoginPage />} />
|
||||||
|
<Route path="/signup" element={<SignUpPage />} />
|
||||||
|
</Routes>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const AuthenticatedComponents = () => {
|
||||||
|
return (
|
||||||
|
<div className="display: flex">
|
||||||
|
<IconSideNav />
|
||||||
|
<div className="flex-1 ml-[76px] overflow-hidden">
|
||||||
<NavBar />
|
<NavBar />
|
||||||
<div className={isLoginPageOrSignUpPage ? "" : "overflow-x-auto"}>
|
<div className="overflow-x-auto">
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/" element={<Dashboard />} />
|
<Route path="/" element={<Dashboard />} />
|
||||||
<Route exact path="/tasks" element={<PrivateRoute />}>
|
<Route exact path="/tasks" element={<PrivateRoute />}>
|
||||||
|
|||||||
@ -1,11 +1,9 @@
|
|||||||
import React from "react";
|
|
||||||
import { Navigate, Outlet } from "react-router-dom";
|
import { Navigate, Outlet } from "react-router-dom";
|
||||||
import { useAuth } from "./hooks/authentication/IsAuthenticated";
|
import { useAuth } from "src/hooks/AuthHooks";
|
||||||
|
|
||||||
const PrivateRoute = () => {
|
const PrivateRoute = () => {
|
||||||
const { isAuthenticated, setIsAuthenticated } = useAuth();
|
const { isAuthenticated } = useAuth();
|
||||||
const auth = isAuthenticated;
|
return isAuthenticated ? <Outlet /> : <Navigate to="/login" />;
|
||||||
return auth ? <Outlet /> : <Navigate to="/login" />;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export default PrivateRoute;
|
export default PrivateRoute;
|
||||||
|
|||||||
@ -1,15 +1,16 @@
|
|||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import axiosInstance from "./configs/AxiosConfig";
|
import axiosInstance from "./AxiosConfig";
|
||||||
|
|
||||||
// Function for user login
|
// Function for user login
|
||||||
const apiUserLogin = data => {
|
const apiUserLogin = (data) => {
|
||||||
return axiosInstance
|
return axiosInstance
|
||||||
.post("token/obtain/", data)
|
.post("token/obtain/", data)
|
||||||
.then(response => {
|
.then((response) => {
|
||||||
console.log(response.statusText);
|
console.log(response.statusText);
|
||||||
|
|
||||||
return response;
|
return response;
|
||||||
})
|
})
|
||||||
.catch(error => {
|
.catch((error) => {
|
||||||
console.log("apiUserLogin error: ", error);
|
console.log("apiUserLogin error: ", error);
|
||||||
return error;
|
return error;
|
||||||
});
|
});
|
||||||
@ -23,7 +24,7 @@ const apiUserLogout = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Function for Google login
|
// Function for Google login
|
||||||
const googleLogin = async token => {
|
const googleLogin = async (token) => {
|
||||||
axios.defaults.withCredentials = true;
|
axios.defaults.withCredentials = true;
|
||||||
let res = await axios.post("http://localhost:8000/api/auth/google/", {
|
let res = await axios.post("http://localhost:8000/api/auth/google/", {
|
||||||
code: token,
|
code: token,
|
||||||
@ -36,29 +37,23 @@ const googleLogin = async token => {
|
|||||||
const getGreeting = () => {
|
const getGreeting = () => {
|
||||||
return axiosInstance
|
return axiosInstance
|
||||||
.get("hello")
|
.get("hello")
|
||||||
.then(response => {
|
.then((response) => {
|
||||||
return response;
|
return response;
|
||||||
})
|
})
|
||||||
.catch(error => {
|
.catch((error) => {
|
||||||
return error;
|
return error;
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const config = {
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
// Function to register
|
// Function to register
|
||||||
const createUser = async formData => {
|
const createUser = async (formData) => {
|
||||||
try {
|
try {
|
||||||
axios.defaults.withCredentials = true;
|
axios.defaults.withCredentials = true;
|
||||||
const resposne = axios.post("http://localhost:8000/api/user/create/", formData);
|
const response = axios.post("http://localhost:8000/api/user/create/", formData);
|
||||||
// const response = await axiosInstance.post('/user/create/', formData);
|
// const response = await axiosInstance.post('/user/create/', formData);
|
||||||
return response.data;
|
return response.data;
|
||||||
} catch (error) {
|
} catch (e) {
|
||||||
throw error;
|
console.log(e);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
45
frontend/src/api/AxiosConfig.jsx
Normal file
45
frontend/src/api/AxiosConfig.jsx
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
import axios from "axios";
|
||||||
|
import { redirect } from "react-router-dom";
|
||||||
|
|
||||||
|
const axiosInstance = axios.create({
|
||||||
|
baseURL: "http://127.0.0.1:8000/api/",
|
||||||
|
timeout: 5000,
|
||||||
|
headers: {
|
||||||
|
Authorization: "Bearer " + localStorage.getItem("access_token"),
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
accept: "application/json",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// handling token refresh on 401 Unauthorized errors
|
||||||
|
axiosInstance.interceptors.response.use(
|
||||||
|
(response) => response,
|
||||||
|
(error) => {
|
||||||
|
const originalRequest = error.config;
|
||||||
|
const refresh_token = localStorage.getItem("refresh_token");
|
||||||
|
|
||||||
|
// Check if the error is due to 401 and a refresh token is available
|
||||||
|
if (error.response && error.response.status === 401) {
|
||||||
|
if (refresh_token) {
|
||||||
|
return axiosInstance
|
||||||
|
.post("/token/refresh/", { refresh: refresh_token })
|
||||||
|
.then((response) => {
|
||||||
|
localStorage.setItem("access_token", response.data.access);
|
||||||
|
|
||||||
|
axiosInstance.defaults.headers["Authorization"] = "Bearer " + response.data.access;
|
||||||
|
originalRequest.headers["Authorization"] = "Bearer " + response.data.access;
|
||||||
|
|
||||||
|
return axiosInstance(originalRequest);
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
console.log("Interceptors error: ", err);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
redirect("/login");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Promise.reject(error);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
export default axiosInstance;
|
||||||
@ -1,21 +1,21 @@
|
|||||||
import axiosInstance from "./configs/AxiosConfig";
|
import axiosInstance from "src/api/AxiosConfig";
|
||||||
|
|
||||||
const baseURL = "";
|
const baseURL = "";
|
||||||
|
|
||||||
export const createTask = (endpoint, data) => {
|
export const createTask = (endpoint, data) => {
|
||||||
return axiosInstance
|
return axiosInstance
|
||||||
.post(`${baseURL}${endpoint}/`, data)
|
.post(`${baseURL}${endpoint}/`, data)
|
||||||
.then(response => response.data)
|
.then((response) => response.data)
|
||||||
.catch(error => {
|
.catch((error) => {
|
||||||
throw error;
|
throw error;
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const readTasks = endpoint => {
|
export const readTasks = (endpoint) => {
|
||||||
return axiosInstance
|
return axiosInstance
|
||||||
.get(`${baseURL}${endpoint}/`)
|
.get(`${baseURL}${endpoint}/`)
|
||||||
.then(response => response.data)
|
.then((response) => response.data)
|
||||||
.catch(error => {
|
.catch((error) => {
|
||||||
throw error;
|
throw error;
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@ -23,8 +23,8 @@ export const readTasks = endpoint => {
|
|||||||
export const readTaskByID = (endpoint, id) => {
|
export const readTaskByID = (endpoint, id) => {
|
||||||
return axiosInstance
|
return axiosInstance
|
||||||
.get(`${baseURL}${endpoint}/${id}/`)
|
.get(`${baseURL}${endpoint}/${id}/`)
|
||||||
.then(response => response.data)
|
.then((response) => response.data)
|
||||||
.catch(error => {
|
.catch((error) => {
|
||||||
throw error;
|
throw error;
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@ -32,8 +32,8 @@ export const readTaskByID = (endpoint, id) => {
|
|||||||
export const updateTask = (endpoint, id, data) => {
|
export const updateTask = (endpoint, id, data) => {
|
||||||
return axiosInstance
|
return axiosInstance
|
||||||
.put(`${baseURL}${endpoint}/${id}/`, data)
|
.put(`${baseURL}${endpoint}/${id}/`, data)
|
||||||
.then(response => response.data)
|
.then((response) => response.data)
|
||||||
.catch(error => {
|
.catch((error) => {
|
||||||
throw error;
|
throw error;
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@ -41,16 +41,16 @@ export const updateTask = (endpoint, id, data) => {
|
|||||||
export const deleteTask = (endpoint, id) => {
|
export const deleteTask = (endpoint, id) => {
|
||||||
return axiosInstance
|
return axiosInstance
|
||||||
.delete(`${baseURL}${endpoint}/${id}/`)
|
.delete(`${baseURL}${endpoint}/${id}/`)
|
||||||
.then(response => response.data)
|
.then((response) => response.data)
|
||||||
.catch(error => {
|
.catch((error) => {
|
||||||
throw error;
|
throw error;
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// Create
|
// Create
|
||||||
export const createTodoTask = data => createTask("todo", data);
|
export const createTodoTask = (data) => createTask("todo", data);
|
||||||
export const createRecurrenceTask = data => createTask("daily", data);
|
export const createRecurrenceTask = (data) => createTask("daily", data);
|
||||||
export const createHabitTask = data => createTask("habit", data);
|
export const createHabitTask = (data) => createTask("habit", data);
|
||||||
|
|
||||||
// Read
|
// Read
|
||||||
export const readTodoTasks = () => readTasks("todo");
|
export const readTodoTasks = () => readTasks("todo");
|
||||||
@ -58,9 +58,9 @@ export const readRecurrenceTasks = () => readTasks("daily");
|
|||||||
export const readHabitTasks = () => readTasks("habit");
|
export const readHabitTasks = () => readTasks("habit");
|
||||||
|
|
||||||
// Read by ID
|
// Read by ID
|
||||||
export const readTodoTaskByID = id => readTaskByID("todo", id);
|
export const readTodoTaskByID = (id) => readTaskByID("todo", id);
|
||||||
export const readRecurrenceTaskByID = id => readTaskByID("daily", id);
|
export const readRecurrenceTaskByID = (id) => readTaskByID("daily", id);
|
||||||
export const readHabitTaskByID = id => readTaskByID("habit", id);
|
export const readHabitTaskByID = (id) => readTaskByID("habit", id);
|
||||||
|
|
||||||
// Update
|
// Update
|
||||||
export const updateTodoTask = (id, data) => updateTask("todo", id, data);
|
export const updateTodoTask = (id, data) => updateTask("todo", id, data);
|
||||||
@ -68,6 +68,6 @@ export const updateRecurrenceTask = (id, data) => updateTask("daily", id, data);
|
|||||||
export const updateHabitTask = (id, data) => updateTask("habit", id, data);
|
export const updateHabitTask = (id, data) => updateTask("habit", id, data);
|
||||||
|
|
||||||
// Delete
|
// Delete
|
||||||
export const deleteTodoTask = id => deleteTask("todo", id);
|
export const deleteTodoTask = (id) => deleteTask("todo", id);
|
||||||
export const deleteRecurrenceTask = id => deleteTask("daily", id);
|
export const deleteRecurrenceTask = (id) => deleteTask("daily", id);
|
||||||
export const deleteHabitTask = id => deleteTask("habit", id);
|
export const deleteHabitTask = (id) => deleteTask("habit", id);
|
||||||
|
|||||||
@ -1,45 +0,0 @@
|
|||||||
import axios from "axios";
|
|
||||||
import { redirect } from "react-router-dom";
|
|
||||||
|
|
||||||
const axiosInstance = axios.create({
|
|
||||||
baseURL: "http://127.0.0.1:8000/api/",
|
|
||||||
timeout: 5000,
|
|
||||||
headers: {
|
|
||||||
Authorization: "Bearer " + localStorage.getItem("access_token"),
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
accept: "application/json",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
// handling token refresh on 401 Unauthorized errors
|
|
||||||
axiosInstance.interceptors.response.use(
|
|
||||||
response => response,
|
|
||||||
error => {
|
|
||||||
const originalRequest = error.config;
|
|
||||||
const refresh_token = localStorage.getItem("refresh_token");
|
|
||||||
|
|
||||||
// Check if the error is due to 401 and a refresh token is available
|
|
||||||
if (
|
|
||||||
error.response.status === 401 &&
|
|
||||||
error.response.statusText === "Unauthorized" &&
|
|
||||||
refresh_token !== "undefined"
|
|
||||||
) {
|
|
||||||
return axiosInstance
|
|
||||||
.post("/token/refresh/", { refresh: refresh_token })
|
|
||||||
.then(response => {
|
|
||||||
localStorage.setItem("access_token", response.data.access);
|
|
||||||
|
|
||||||
axiosInstance.defaults.headers["Authorization"] = "Bearer " + response.data.access;
|
|
||||||
originalRequest.headers["Authorization"] = "Bearer " + response.data.access;
|
|
||||||
|
|
||||||
return axiosInstance(originalRequest);
|
|
||||||
})
|
|
||||||
.catch(err => {
|
|
||||||
console.log("Interceptors error: ", err);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return Promise.reject(error);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
export default axiosInstance;
|
|
||||||
@ -1,14 +1,14 @@
|
|||||||
import React, { useState, useEffect } from "react";
|
import React, { useState, useEffect } from "react";
|
||||||
import { FiAlertCircle, FiClock, FiXCircle, FiCheckCircle } from "react-icons/fi";
|
import { FiAlertCircle, FiClock, FiXCircle, FiCheckCircle } from "react-icons/fi";
|
||||||
import { readTodoTasks } from "../../api/TaskApi";
|
import { readTodoTasks } from "../../api/TaskApi";
|
||||||
import axiosInstance from "../../api/configs/AxiosConfig";
|
import axiosInstance from "src/api/AxiosConfig";
|
||||||
|
|
||||||
function EachBlog({ name, colorCode, contentList, icon }) {
|
function EachBlog({ name, colorCode, contentList, icon }) {
|
||||||
const [tasks, setTasks] = useState(contentList);
|
const [tasks, setTasks] = useState(contentList);
|
||||||
|
|
||||||
const handleCheckboxChange = async index => {
|
const handleCheckboxChange = async (index) => {
|
||||||
try {
|
try {
|
||||||
setTasks(contentList)
|
setTasks(contentList);
|
||||||
|
|
||||||
const updatedTasks = [...tasks];
|
const updatedTasks = [...tasks];
|
||||||
const taskId = updatedTasks[index].id;
|
const taskId = updatedTasks[index].id;
|
||||||
@ -60,12 +60,12 @@ function Eisenhower() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
readTodoTasks()
|
readTodoTasks()
|
||||||
.then(data => {
|
.then((data) => {
|
||||||
console.log(data);
|
console.log(data);
|
||||||
const contentList_ui = data.filter(task => task.priority === 1);
|
const contentList_ui = data.filter((task) => task.priority === 1);
|
||||||
const contentList_uni = data.filter(task => task.priority === 2);
|
const contentList_uni = data.filter((task) => task.priority === 2);
|
||||||
const contentList_nui = data.filter(task => task.priority === 3);
|
const contentList_nui = data.filter((task) => task.priority === 3);
|
||||||
const contentList_nuni = data.filter(task => task.priority === 4);
|
const contentList_nuni = data.filter((task) => task.priority === 4);
|
||||||
|
|
||||||
setTasks({
|
setTasks({
|
||||||
contentList_ui,
|
contentList_ui,
|
||||||
@ -74,7 +74,7 @@ function Eisenhower() {
|
|||||||
contentList_nuni,
|
contentList_nuni,
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
.catch(error => console.error("Error fetching tasks:", error));
|
.catch((error) => console.error("Error fetching tasks:", error));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@ -1,18 +1,17 @@
|
|||||||
import React, { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate, redirect } from "react-router-dom";
|
||||||
import { useGoogleLogin } from "@react-oauth/google";
|
import { useGoogleLogin } from "@react-oauth/google";
|
||||||
import { useCallback } from "react";
|
import { useCallback } from "react";
|
||||||
import Particles from "react-tsparticles";
|
import Particles from "react-tsparticles";
|
||||||
import { loadFull } from "tsparticles";
|
import { loadFull } from "tsparticles";
|
||||||
import refreshAccessToken from "./refreshAcesstoken";
|
import refreshAccessToken from "./refreshAcesstoken";
|
||||||
import axiosapi from "../../api/AuthenticationApi";
|
import axiosapi from "../../api/AuthenticationApi";
|
||||||
import { useAuth } from "../../hooks/authentication/IsAuthenticated";
|
|
||||||
import { FcGoogle } from "react-icons/fc";
|
import { FcGoogle } from "react-icons/fc";
|
||||||
|
import { useAuth } from "src/hooks/AuthHooks";
|
||||||
|
|
||||||
function LoginPage() {
|
function LoginPage() {
|
||||||
|
const { setIsAuthenticated } = useAuth();
|
||||||
const Navigate = useNavigate();
|
const Navigate = useNavigate();
|
||||||
const { isAuthenticated, setIsAuthenticated } = useAuth();
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!refreshAccessToken()) {
|
if (!refreshAccessToken()) {
|
||||||
@ -43,15 +42,13 @@ function LoginPage() {
|
|||||||
// On successful login, store tokens and set the authorization header
|
// On successful login, store tokens and set the authorization header
|
||||||
localStorage.setItem("access_token", res.data.access);
|
localStorage.setItem("access_token", res.data.access);
|
||||||
localStorage.setItem("refresh_token", res.data.refresh);
|
localStorage.setItem("refresh_token", res.data.refresh);
|
||||||
axiosapi.axiosInstance.defaults.headers["Authorization"] =
|
axiosapi.axiosInstance.defaults.headers["Authorization"] = "Bearer " + res.data.access;
|
||||||
"Bearer " + res.data.access;
|
|
||||||
setIsAuthenticated(true);
|
setIsAuthenticated(true);
|
||||||
Navigate("/");
|
redirect("/");
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
console.log("Login failed");
|
console.log("Login failed");
|
||||||
console.log(err);
|
console.log(err);
|
||||||
setIsAuthenticated(false);
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -71,7 +68,6 @@ function LoginPage() {
|
|||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error with the POST request:", error);
|
console.error("Error with the POST request:", error);
|
||||||
setIsAuthenticated(false);
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onError: (errorResponse) => console.log(errorResponse),
|
onError: (errorResponse) => console.log(errorResponse),
|
||||||
@ -89,10 +85,7 @@ function LoginPage() {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div data-theme="night" className="h-screen flex items-center justify-center">
|
||||||
data-theme="night"
|
|
||||||
className="h-screen flex items-center justify-center"
|
|
||||||
>
|
|
||||||
{/* Particles Container */}
|
{/* Particles Container */}
|
||||||
<div style={{ width: "0%", height: "100vh" }}>
|
<div style={{ width: "0%", height: "100vh" }}>
|
||||||
<Particles
|
<Particles
|
||||||
@ -206,11 +199,9 @@ function LoginPage() {
|
|||||||
</button>
|
</button>
|
||||||
<div className="divider">OR</div>
|
<div className="divider">OR</div>
|
||||||
{/* Login with Google Button */}
|
{/* Login with Google Button */}
|
||||||
<button
|
<button className="btn btn-outline btn-secondary w-full " onClick={() => googleLoginImplicit()}>
|
||||||
className="btn btn-outline btn-secondary w-full "
|
<FcGoogle className="rounded-full bg-white" />
|
||||||
onClick={() => googleLoginImplicit()}
|
Login with Google
|
||||||
>
|
|
||||||
<FcGoogle className="rounded-full bg-white"/>Login with Google
|
|
||||||
</button>
|
</button>
|
||||||
{/* Forgot Password Link */}
|
{/* Forgot Password Link */}
|
||||||
<div className="justify-left">
|
<div className="justify-left">
|
||||||
|
|||||||
@ -1,11 +1,11 @@
|
|||||||
import React, { useState } from "react";
|
import React from "react";
|
||||||
import { formatDate } from "@fullcalendar/core";
|
import { formatDate } from "@fullcalendar/core";
|
||||||
import FullCalendar from "@fullcalendar/react";
|
import FullCalendar from "@fullcalendar/react";
|
||||||
import dayGridPlugin from "@fullcalendar/daygrid";
|
import dayGridPlugin from "@fullcalendar/daygrid";
|
||||||
import timeGridPlugin from "@fullcalendar/timegrid";
|
import timeGridPlugin from "@fullcalendar/timegrid";
|
||||||
import interactionPlugin from "@fullcalendar/interaction";
|
import interactionPlugin from "@fullcalendar/interaction";
|
||||||
import { getEvents, createEventId } from "./TaskDataHandler";
|
import { getEvents, createEventId } from "./TaskDataHandler";
|
||||||
import axiosInstance from "../../api/configs/AxiosConfig";
|
import axiosInstance from "src/api/AxiosConfig";
|
||||||
|
|
||||||
export default class Calendar extends React.Component {
|
export default class Calendar extends React.Component {
|
||||||
state = {
|
state = {
|
||||||
@ -83,7 +83,7 @@ export default class Calendar extends React.Component {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
handleDateSelect = selectInfo => {
|
handleDateSelect = (selectInfo) => {
|
||||||
let title = prompt("Please enter a new title for your event");
|
let title = prompt("Please enter a new title for your event");
|
||||||
let calendarApi = selectInfo.view.calendar;
|
let calendarApi = selectInfo.view.calendar;
|
||||||
|
|
||||||
@ -100,20 +100,20 @@ export default class Calendar extends React.Component {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
handleEventClick = clickInfo => {
|
handleEventClick = (clickInfo) => {
|
||||||
if (confirm(`Are you sure you want to delete the event '${clickInfo.event.title}'`)) {
|
if (confirm(`Are you sure you want to delete the event '${clickInfo.event.title}'`)) {
|
||||||
axiosInstance
|
axiosInstance
|
||||||
.delete(`todo/${clickInfo.event.id}/`)
|
.delete(`todo/${clickInfo.event.id}/`)
|
||||||
.then(response => {
|
.then((response) => {
|
||||||
clickInfo.event.remove();
|
clickInfo.event.remove();
|
||||||
})
|
})
|
||||||
.catch(error => {
|
.catch((error) => {
|
||||||
console.error("Error deleting Task:", error);
|
console.error("Error deleting Task:", error);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
handleEvents = events => {
|
handleEvents = (events) => {
|
||||||
this.setState({
|
this.setState({
|
||||||
currentEvents: events,
|
currentEvents: events,
|
||||||
});
|
});
|
||||||
|
|||||||
@ -1,103 +1,36 @@
|
|||||||
import { AreaChart, Title } from "@tremor/react";
|
import { AreaChart, Title } from "@tremor/react";
|
||||||
import React from "react";
|
import { useState, useEffect } from "react";
|
||||||
import axiosInstance from "../../api/configs/AxiosConfig";
|
import axiosInstance from "src/api/AxiosConfig";
|
||||||
|
|
||||||
const fetchAreaChartData = async () => {
|
|
||||||
let res = await axiosInstance.get("/dashboard/weekly/");
|
|
||||||
console.log(res.data);
|
|
||||||
// const areaChartData = [
|
|
||||||
// {
|
|
||||||
// date: "Mon",
|
|
||||||
// "This Week": res.data[0]["This Week"],
|
|
||||||
// "Last Week": res.data[0]["Last Week"],
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// date: "Tue",
|
|
||||||
// "This Week": res.data[1]["This Week"],
|
|
||||||
// "Last Week": res.data[1]["Last Week"],
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// date: "Wed",
|
|
||||||
// "This Week": res.data[2]["This Week"],
|
|
||||||
// "Last Week": res.data[2]["Last Week"],
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// date: "Th",
|
|
||||||
// "This Week": res.data[3]["This Week"],
|
|
||||||
// "Last Week": res.data[3]["Last Week"],
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// date: "Fri",
|
|
||||||
// "This Week": res.data[4]["This Week"],
|
|
||||||
// "Last Week": res.data[4]["Last Week"],
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// date: "Sat",
|
|
||||||
// "This Week": res.data[5]["This Week"],
|
|
||||||
// "Last Week": res.data[5]["Last Week"],
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// date: "Sun",
|
|
||||||
// "This Week": res.data[6]["This Week"],
|
|
||||||
// "Last Week": res.data[6]["Last Week"],
|
|
||||||
// },
|
|
||||||
// ];
|
|
||||||
const areaChartData = [
|
|
||||||
{
|
|
||||||
date: "Mon",
|
|
||||||
"This Week": 1,
|
|
||||||
"Last Week": 2,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: "Tue",
|
|
||||||
"This Week": 5,
|
|
||||||
"Last Week": 2,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: "Wed",
|
|
||||||
"This Week": 7,
|
|
||||||
"Last Week": 9,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: "Th",
|
|
||||||
"This Week": 10,
|
|
||||||
"Last Week": 3,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: "Fri",
|
|
||||||
"This Week": 5,
|
|
||||||
"Last Week": 1,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: "Sat",
|
|
||||||
"This Week": 7,
|
|
||||||
"Last Week": 8,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: "Sun",
|
|
||||||
"This Week": 3,
|
|
||||||
"Last Week": 8,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
return areaChartData;
|
|
||||||
}
|
|
||||||
|
|
||||||
const areaChartDataArray = await fetchAreaChartData();
|
|
||||||
export const AreaChartGraph = () => {
|
export const AreaChartGraph = () => {
|
||||||
const [value, setValue] = React.useState(null);
|
const [areaChartDataArray, setAreaChartDataArray] = useState([]);
|
||||||
return (
|
|
||||||
<>
|
useEffect(() => {
|
||||||
<Title>Number of tasks statistics vs. last week</Title>
|
const fetchAreaChartData = async () => {
|
||||||
<AreaChart
|
try {
|
||||||
className="mt-6"
|
const response = await axiosInstance.get("/dashboard/weekly/");
|
||||||
data={areaChartDataArray}
|
const areaChartData = response.data;
|
||||||
index="date"
|
setAreaChartDataArray(areaChartData);
|
||||||
categories={["This Week", "Last Week"]}
|
} catch (error) {
|
||||||
colors={["neutral", "indigo"]}
|
console.error("Error fetching area chart data:", error);
|
||||||
yAxisWidth={30}
|
}
|
||||||
onValueChange={(v) => setValue(v)}
|
};
|
||||||
showAnimation
|
|
||||||
/>
|
fetchAreaChartData();
|
||||||
</>
|
}, []);
|
||||||
);
|
|
||||||
};
|
return (
|
||||||
|
<>
|
||||||
|
<Title>Number of tasks statistics vs. last week</Title>
|
||||||
|
<AreaChart
|
||||||
|
className="mt-6"
|
||||||
|
data={areaChartDataArray}
|
||||||
|
index="date"
|
||||||
|
categories={["This Week", "Last Week"]}
|
||||||
|
colors={["neutral", "indigo"]}
|
||||||
|
yAxisWidth={30}
|
||||||
|
showAnimation
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|||||||
@ -1,89 +1,24 @@
|
|||||||
import { BarChart, Title } from "@tremor/react";
|
import { BarChart, Title } from "@tremor/react";
|
||||||
import React from "react";
|
import { useState, useEffect } from "react";
|
||||||
import axiosInstance from "../../api/configs/AxiosConfig";
|
import axiosInstance from "src/api/AxiosConfig";
|
||||||
|
|
||||||
const fetchBarChartData = async () => {
|
|
||||||
let res = await axiosInstance.get("/dashboard/weekly/");
|
|
||||||
console.log(res.data);
|
|
||||||
// const barchartData = [
|
|
||||||
// {
|
|
||||||
// date: "Mon",
|
|
||||||
// "This Week": res.data[0]["Completed This Week"],
|
|
||||||
// "Last Week": res.data[0]["Completed Last Week"],
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// date: "Tue",
|
|
||||||
// "This Week": res.data[1]["Completed This Week"],
|
|
||||||
// "Last Week": res.data[1]["Completed Last Week"],
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// date: "Wed",
|
|
||||||
// "This Week": res.data[2]["Completed This Week"],
|
|
||||||
// "Last Week": res.data[2]["Completed Last Week"],
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// date: "Th",
|
|
||||||
// "This Week": res.data[3]["Completed This Week"],
|
|
||||||
// "Last Week": res.data[3]["Completed Last Week"],
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// date: "Fri",
|
|
||||||
// "This Week": res.data[4]["Completed This Week"],
|
|
||||||
// "Last Week": res.data[4]["Completed Last Week"],
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// date: "Sat",
|
|
||||||
// "This Week": res.data[5]["Completed This Week"],
|
|
||||||
// "Last Week": res.data[5]["Completed Last Week"],
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// date: "Sun",
|
|
||||||
// "This Week": res.data[6]["Completed This Week"],
|
|
||||||
// "Last Week": res.data[6]["Completed Last Week"],
|
|
||||||
// },
|
|
||||||
// ];
|
|
||||||
const barchartData = [
|
|
||||||
{
|
|
||||||
date: "Mon",
|
|
||||||
"This Week": 1,
|
|
||||||
"Last Week": 2,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: "Tue",
|
|
||||||
"This Week": 5,
|
|
||||||
"Last Week": 2,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: "Wed",
|
|
||||||
"This Week": 7,
|
|
||||||
"Last Week": 9,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: "Th",
|
|
||||||
"This Week": 10,
|
|
||||||
"Last Week": 3,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: "Fri",
|
|
||||||
"This Week": 5,
|
|
||||||
"Last Week": 1,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: "Sat",
|
|
||||||
"This Week": 7,
|
|
||||||
"Last Week": 8,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: "Sun",
|
|
||||||
"This Week": 3,
|
|
||||||
"Last Week": 8,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
return barchartData;
|
|
||||||
};
|
|
||||||
const barchartDataArray = await fetchBarChartData();
|
|
||||||
export const BarChartGraph = () => {
|
export const BarChartGraph = () => {
|
||||||
const [value, setValue] = React.useState(null);
|
const [barchartDataArray, setBarChartDataArray] = useState([]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchAreaChartData = async () => {
|
||||||
|
try {
|
||||||
|
const response = await axiosInstance.get("/dashboard/weekly/");
|
||||||
|
const barchartDataArray = response.data;
|
||||||
|
setBarChartDataArray(barchartDataArray);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching area chart data:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchAreaChartData();
|
||||||
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Title>Task completed statistics vs. last week</Title>
|
<Title>Task completed statistics vs. last week</Title>
|
||||||
@ -94,7 +29,6 @@ export const BarChartGraph = () => {
|
|||||||
categories={["This Week", "Last Week"]}
|
categories={["This Week", "Last Week"]}
|
||||||
colors={["neutral", "indigo"]}
|
colors={["neutral", "indigo"]}
|
||||||
yAxisWidth={30}
|
yAxisWidth={30}
|
||||||
onValueChange={(v) => setValue(v)}
|
|
||||||
showAnimation
|
showAnimation
|
||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
|
|||||||
@ -1,40 +1,37 @@
|
|||||||
import { DonutChart } from "@tremor/react";
|
import { DonutChart } from "@tremor/react";
|
||||||
import axiosInstance from "../../api/configs/AxiosConfig";
|
import axiosInstance from "src/api/AxiosConfig";
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
|
||||||
const fetchDonutData = async () => {
|
|
||||||
try {
|
|
||||||
let res = await axiosInstance.get("/dashboard/stats/");
|
|
||||||
// let todoCount = res.data.todo_count;
|
|
||||||
// let recurrenceCount = res.data.recurrence_count;
|
|
||||||
let todoCount = 10;
|
|
||||||
let recurrenceCount = 15;
|
|
||||||
if (todoCount === undefined) {
|
|
||||||
todoCount = 0;
|
|
||||||
}
|
|
||||||
if (recurrenceCount === undefined) {
|
|
||||||
recurrenceCount = 0;
|
|
||||||
}
|
|
||||||
const donutData = [
|
|
||||||
{ name: "Todo", count: todoCount },
|
|
||||||
{ name: "Recurrence", count: recurrenceCount },
|
|
||||||
];
|
|
||||||
return donutData;
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error fetching donut data:", error);
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const donutDataArray = await fetchDonutData();
|
|
||||||
export default function DonutChartGraph() {
|
export default function DonutChartGraph() {
|
||||||
|
const [donutData, setDonutData] = useState([]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchDonutData = async () => {
|
||||||
|
try {
|
||||||
|
const response = await axiosInstance.get("/dashboard/stats/");
|
||||||
|
const todoCount = response.data.todo_count || 0;
|
||||||
|
const recurrenceCount = response.data.recurrence_count || 0;
|
||||||
|
|
||||||
|
const donutData = [
|
||||||
|
{ name: "Todo", count: todoCount },
|
||||||
|
{ name: "Recurrence", count: recurrenceCount },
|
||||||
|
];
|
||||||
|
|
||||||
|
setDonutData(donutData);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching donut data:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
fetchDonutData();
|
||||||
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DonutChart
|
<DonutChart
|
||||||
className="mt-6"
|
className="mt-6"
|
||||||
data={donutDataArray}
|
data={donutData}
|
||||||
category="count"
|
category="count"
|
||||||
index="name"
|
index="name"
|
||||||
colors={["rose", "yellow", "orange"]}
|
colors={["rose", "yellow", "orange"]}
|
||||||
onValueChange={(v) => setValue(v)}
|
|
||||||
showAnimation
|
showAnimation
|
||||||
radius={25}
|
radius={25}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@ -1,42 +1,57 @@
|
|||||||
|
|
||||||
import { BadgeDelta, Card, Flex, Metric, ProgressBar, Text } from "@tremor/react";
|
import { BadgeDelta, Card, Flex, Metric, ProgressBar, Text } from "@tremor/react";
|
||||||
import React from "react";
|
import { useEffect, useState } from "react";
|
||||||
import axiosInstance from "../../api/configs/AxiosConfig";
|
import axiosInstance from "src/api/AxiosConfig";
|
||||||
|
|
||||||
const fetchKpiCardData = async () => {
|
|
||||||
let res = await axiosInstance.get("/dashboard/stats/");
|
|
||||||
// let completedThisWeek = res.data["completed_this_week"];
|
|
||||||
// let completedLastWeek = res.data["completed_last_week"];
|
|
||||||
let completedThisWeek = 4;
|
|
||||||
let completedLastWeek = 23;
|
|
||||||
let percentage = (completedThisWeek / completedLastWeek)*100;
|
|
||||||
let incOrdec = undefined;
|
|
||||||
if (completedThisWeek <= completedLastWeek) {
|
|
||||||
incOrdec = "moderateDecrease";
|
|
||||||
}
|
|
||||||
if (completedThisWeek > completedLastWeek) {
|
|
||||||
incOrdec = "moderateIncrease";
|
|
||||||
}
|
|
||||||
return {completedThisWeek, completedLastWeek, incOrdec, percentage};
|
|
||||||
}
|
|
||||||
|
|
||||||
const {kpiCardDataArray, completedThisWeek ,completedLastWeek, incOrdec, percentage} = await fetchKpiCardData();
|
|
||||||
|
|
||||||
|
|
||||||
export default function KpiCard() {
|
export default function KpiCard() {
|
||||||
|
const [kpiCardData, setKpiCardData] = useState({
|
||||||
|
completedThisWeek: 0,
|
||||||
|
completedLastWeek: 0,
|
||||||
|
incOrdec: undefined,
|
||||||
|
percentage: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchKpiCardData = async () => {
|
||||||
|
try {
|
||||||
|
const response = await axiosInstance.get("/dashboard/stats/");
|
||||||
|
const completedThisWeek = response.data.completed_this_week || 0;
|
||||||
|
const completedLastWeek = response.data.completed_last_week || 0;
|
||||||
|
const percentage = (completedThisWeek / completedLastWeek) * 100;
|
||||||
|
let incOrdec = undefined;
|
||||||
|
|
||||||
|
if (completedThisWeek <= completedLastWeek) {
|
||||||
|
incOrdec = "moderateDecrease";
|
||||||
|
}
|
||||||
|
if (completedThisWeek > completedLastWeek) {
|
||||||
|
incOrdec = "moderateIncrease";
|
||||||
|
}
|
||||||
|
|
||||||
|
setKpiCardData({
|
||||||
|
completedThisWeek,
|
||||||
|
completedLastWeek,
|
||||||
|
incOrdec,
|
||||||
|
percentage,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching KPI card data:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchKpiCardData();
|
||||||
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
||||||
<Card className="max-w-lg mx-auto">
|
<Card className="max-w-lg mx-auto">
|
||||||
<Flex alignItems="start">
|
<Flex alignItems="start">
|
||||||
<div>
|
<div>
|
||||||
<Metric>{completedThisWeek}</Metric>
|
<Metric>{kpiCardData.completedThisWeek}</Metric>
|
||||||
</div>
|
</div>
|
||||||
<BadgeDelta deltaType={incOrdec}>{percentage.toFixed(0)}%</BadgeDelta>
|
<BadgeDelta deltaType={kpiCardData.incOrdec}>{kpiCardData.percentage.toFixed(0)}%</BadgeDelta>
|
||||||
</Flex>
|
</Flex>
|
||||||
<Flex className="mt-4">
|
<Flex className="mt-4">
|
||||||
<Text className="truncate">vs. {completedLastWeek} (last week)</Text>
|
<Text className="truncate">vs. {kpiCardData.completedLastWeek} (last week)</Text>
|
||||||
</Flex>
|
</Flex>
|
||||||
<ProgressBar value={percentage} className="mt-2" />
|
<ProgressBar value={kpiCardData.percentage} className="mt-2" />
|
||||||
</Card>
|
</Card>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,38 +1,39 @@
|
|||||||
import { Card, Flex, ProgressCircle, Text, } from "@tremor/react";
|
import { Card, Flex, ProgressCircle } from "@tremor/react";
|
||||||
import React from "react";
|
import { useState, useEffect } from "react";
|
||||||
import axiosInstance from "../../api/configs/AxiosConfig";
|
import axiosInstance from "src/api/AxiosConfig";
|
||||||
|
|
||||||
const fetchProgressData = async () => {
|
|
||||||
try {
|
|
||||||
let res = await axiosInstance.get("/dashboard/stats/");
|
|
||||||
// let completedLastWeek = res.data.completed_last_week;
|
|
||||||
// let assignLastWeek = res.data.tasks_assigned_last_week;
|
|
||||||
let completedLastWeek = 15;
|
|
||||||
let assignLastWeek = 35;
|
|
||||||
if (completedLastWeek === undefined) {
|
|
||||||
completedLastWeek = 0;
|
|
||||||
}
|
|
||||||
if (assignLastWeek === undefined) {
|
|
||||||
assignLastWeek = 0;
|
|
||||||
}
|
|
||||||
return (completedLastWeek / assignLastWeek) * 100;
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error fetching progress data:", error);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const progressData = await fetchProgressData();
|
|
||||||
export default function ProgressCircleChart() {
|
export default function ProgressCircleChart() {
|
||||||
|
const [progressData, setProgressData] = useState(0);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchProgressData = async () => {
|
||||||
|
try {
|
||||||
|
const response = await axiosInstance.get("/dashboard/stats/");
|
||||||
|
let completedLastWeek = response.data.completed_last_week || 0;
|
||||||
|
let assignLastWeek = response.data.tasks_assigned_last_week || 0;
|
||||||
|
|
||||||
|
if (completedLastWeek === undefined) {
|
||||||
|
completedLastWeek = 0;
|
||||||
|
}
|
||||||
|
if (assignLastWeek === undefined) {
|
||||||
|
assignLastWeek = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const progress = (completedLastWeek / assignLastWeek) * 100;
|
||||||
|
|
||||||
|
setProgressData(progress);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching progress data:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchProgressData();
|
||||||
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className="max-w-lg mx-auto">
|
<Card className="max-w-lg mx-auto">
|
||||||
<Flex className="flex-col items-center">
|
<Flex className="flex-col items-center">
|
||||||
<ProgressCircle
|
<ProgressCircle className="mt-6" value={progressData} size={200} strokeWidth={10} radius={60} color="indigo">
|
||||||
className="mt-6" value={progressData}
|
|
||||||
size={200}
|
|
||||||
strokeWidth={10}
|
|
||||||
radius={60}
|
|
||||||
color="indigo">
|
|
||||||
<span className="h-12 w-12 rounded-full bg-indigo-100 flex items-center justify-center text-sm text-indigo-500 font-medium">
|
<span className="h-12 w-12 rounded-full bg-indigo-100 flex items-center justify-center text-sm text-indigo-500 font-medium">
|
||||||
{progressData.toFixed(0)} %
|
{progressData.toFixed(0)} %
|
||||||
</span>
|
</span>
|
||||||
|
|||||||
@ -5,11 +5,11 @@ import { SortableContext, arrayMove } from "@dnd-kit/sortable";
|
|||||||
import { createPortal } from "react-dom";
|
import { createPortal } from "react-dom";
|
||||||
import TaskCard from "./taskCard";
|
import TaskCard from "./taskCard";
|
||||||
import { AiOutlinePlusCircle } from "react-icons/ai";
|
import { AiOutlinePlusCircle } from "react-icons/ai";
|
||||||
import axiosInstance from "../../api/configs/AxiosConfig";
|
import axiosInstance from "src/api/AxiosConfig";
|
||||||
|
|
||||||
function KanbanBoard() {
|
function KanbanBoard() {
|
||||||
const [columns, setColumns] = useState([]);
|
const [columns, setColumns] = useState([]);
|
||||||
const columnsId = useMemo(() => columns.map(col => col.id), [columns]);
|
const columnsId = useMemo(() => columns.map((col) => col.id), [columns]);
|
||||||
const [boardId, setBoardData] = useState();
|
const [boardId, setBoardData] = useState();
|
||||||
|
|
||||||
const [tasks, setTasks] = useState([]);
|
const [tasks, setTasks] = useState([]);
|
||||||
@ -66,7 +66,7 @@ function KanbanBoard() {
|
|||||||
const tasksResponse = await axiosInstance.get("/todo");
|
const tasksResponse = await axiosInstance.get("/todo");
|
||||||
|
|
||||||
// Transform
|
// Transform
|
||||||
const transformedTasks = tasksResponse.data.map(task => ({
|
const transformedTasks = tasksResponse.data.map((task) => ({
|
||||||
id: task.id,
|
id: task.id,
|
||||||
columnId: task.list_board,
|
columnId: task.list_board,
|
||||||
content: task.title,
|
content: task.title,
|
||||||
@ -95,7 +95,7 @@ function KanbanBoard() {
|
|||||||
const columnsResponse = await axiosInstance.get("/lists");
|
const columnsResponse = await axiosInstance.get("/lists");
|
||||||
|
|
||||||
// Transform
|
// Transform
|
||||||
const transformedColumns = columnsResponse.data.map(column => ({
|
const transformedColumns = columnsResponse.data.map((column) => ({
|
||||||
id: column.id,
|
id: column.id,
|
||||||
title: column.name,
|
title: column.name,
|
||||||
}));
|
}));
|
||||||
@ -135,7 +135,7 @@ function KanbanBoard() {
|
|||||||
<div className="ml-2 flex gap-4">
|
<div className="ml-2 flex gap-4">
|
||||||
<div className="flex gap-4">
|
<div className="flex gap-4">
|
||||||
<SortableContext items={columnsId}>
|
<SortableContext items={columnsId}>
|
||||||
{columns.map(col => (
|
{columns.map((col) => (
|
||||||
<ColumnContainerCard
|
<ColumnContainerCard
|
||||||
key={col.id}
|
key={col.id}
|
||||||
column={col}
|
column={col}
|
||||||
@ -144,7 +144,7 @@ function KanbanBoard() {
|
|||||||
createTask={createTask}
|
createTask={createTask}
|
||||||
deleteTask={deleteTask}
|
deleteTask={deleteTask}
|
||||||
updateTask={updateTask}
|
updateTask={updateTask}
|
||||||
tasks={tasks.filter(task => task.columnId === col.id)}
|
tasks={tasks.filter((task) => task.columnId === col.id)}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</SortableContext>
|
</SortableContext>
|
||||||
@ -186,7 +186,7 @@ function KanbanBoard() {
|
|||||||
createTask={createTask}
|
createTask={createTask}
|
||||||
deleteTask={deleteTask}
|
deleteTask={deleteTask}
|
||||||
updateTask={updateTask}
|
updateTask={updateTask}
|
||||||
tasks={tasks.filter(task => task.columnId === activeColumn.id)}
|
tasks={tasks.filter((task) => task.columnId === activeColumn.id)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{activeTask && <TaskCard task={activeTask} deleteTask={deleteTask} updateTask={updateTask} />}
|
{activeTask && <TaskCard task={activeTask} deleteTask={deleteTask} updateTask={updateTask} />}
|
||||||
@ -213,35 +213,34 @@ function KanbanBoard() {
|
|||||||
|
|
||||||
axiosInstance
|
axiosInstance
|
||||||
.post("todo/", newTaskData)
|
.post("todo/", newTaskData)
|
||||||
.then(response => {
|
.then((response) => {
|
||||||
const newTask = {
|
const newTask = {
|
||||||
id: response.data.id,
|
id: response.data.id,
|
||||||
columnId,
|
columnId,
|
||||||
content: response.data.title,
|
content: response.data.title,
|
||||||
};
|
};
|
||||||
|
|
||||||
})
|
})
|
||||||
.catch(error => {
|
.catch((error) => {
|
||||||
console.error("Error creating task:", error);
|
console.error("Error creating task:", error);
|
||||||
});
|
});
|
||||||
setTasks(tasks => [...tasks, newTask]);
|
setTasks((tasks) => [...tasks, newTask]);
|
||||||
}
|
}
|
||||||
|
|
||||||
function deleteTask(id) {
|
function deleteTask(id) {
|
||||||
const newTasks = tasks.filter(task => task.id !== id);
|
const newTasks = tasks.filter((task) => task.id !== id);
|
||||||
axiosInstance
|
axiosInstance
|
||||||
.delete(`todo/${id}/`)
|
.delete(`todo/${id}/`)
|
||||||
.then(response => {
|
.then((response) => {
|
||||||
setTasks(newTasks);
|
setTasks(newTasks);
|
||||||
})
|
})
|
||||||
.catch(error => {
|
.catch((error) => {
|
||||||
console.error("Error deleting Task:", error);
|
console.error("Error deleting Task:", error);
|
||||||
});
|
});
|
||||||
setTasks(newTasks);
|
setTasks(newTasks);
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateTask(id, content) {
|
function updateTask(id, content) {
|
||||||
const newTasks = tasks.map(task => {
|
const newTasks = tasks.map((task) => {
|
||||||
if (task.id !== id) return task;
|
if (task.id !== id) return task;
|
||||||
return { ...task, content };
|
return { ...task, content };
|
||||||
});
|
});
|
||||||
@ -252,15 +251,15 @@ function KanbanBoard() {
|
|||||||
function createNewColumn() {
|
function createNewColumn() {
|
||||||
axiosInstance
|
axiosInstance
|
||||||
.post("lists/", { name: `Column ${columns.length + 1}`, position: 1, board: boardId.id })
|
.post("lists/", { name: `Column ${columns.length + 1}`, position: 1, board: boardId.id })
|
||||||
.then(response => {
|
.then((response) => {
|
||||||
const newColumn = {
|
const newColumn = {
|
||||||
id: response.data.id,
|
id: response.data.id,
|
||||||
title: response.data.name,
|
title: response.data.name,
|
||||||
};
|
};
|
||||||
|
|
||||||
setColumns(prevColumns => [...prevColumns, newColumn]);
|
setColumns((prevColumns) => [...prevColumns, newColumn]);
|
||||||
})
|
})
|
||||||
.catch(error => {
|
.catch((error) => {
|
||||||
console.error("Error creating ListBoard:", error);
|
console.error("Error creating ListBoard:", error);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -268,22 +267,22 @@ function KanbanBoard() {
|
|||||||
function deleteColumn(id) {
|
function deleteColumn(id) {
|
||||||
axiosInstance
|
axiosInstance
|
||||||
.delete(`lists/${id}/`)
|
.delete(`lists/${id}/`)
|
||||||
.then(response => {
|
.then((response) => {
|
||||||
setColumns(prevColumns => prevColumns.filter(col => col.id !== id));
|
setColumns((prevColumns) => prevColumns.filter((col) => col.id !== id));
|
||||||
})
|
})
|
||||||
.catch(error => {
|
.catch((error) => {
|
||||||
console.error("Error deleting ListBoard:", error);
|
console.error("Error deleting ListBoard:", error);
|
||||||
});
|
});
|
||||||
|
|
||||||
const tasksToDelete = tasks.filter(t => t.columnId === id);
|
const tasksToDelete = tasks.filter((t) => t.columnId === id);
|
||||||
|
|
||||||
tasksToDelete.forEach(task => {
|
tasksToDelete.forEach((task) => {
|
||||||
axiosInstance
|
axiosInstance
|
||||||
.delete(`todo/${task.id}/`)
|
.delete(`todo/${task.id}/`)
|
||||||
.then(response => {
|
.then((response) => {
|
||||||
setTasks(prevTasks => prevTasks.filter(t => t.id !== task.id));
|
setTasks((prevTasks) => prevTasks.filter((t) => t.id !== task.id));
|
||||||
})
|
})
|
||||||
.catch(error => {
|
.catch((error) => {
|
||||||
console.error("Error deleting Task:", error);
|
console.error("Error deleting Task:", error);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@ -293,10 +292,10 @@ function KanbanBoard() {
|
|||||||
// Update the column
|
// Update the column
|
||||||
axiosInstance
|
axiosInstance
|
||||||
.patch(`lists/${id}/`, { name: title }) // Adjust the payload based on your API requirements
|
.patch(`lists/${id}/`, { name: title }) // Adjust the payload based on your API requirements
|
||||||
.then(response => {
|
.then((response) => {
|
||||||
setColumns(prevColumns => prevColumns.map(col => (col.id === id ? { ...col, title } : col)));
|
setColumns((prevColumns) => prevColumns.map((col) => (col.id === id ? { ...col, title } : col)));
|
||||||
})
|
})
|
||||||
.catch(error => {
|
.catch((error) => {
|
||||||
console.error("Error updating ListBoard:", error);
|
console.error("Error updating ListBoard:", error);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -330,9 +329,9 @@ function KanbanBoard() {
|
|||||||
|
|
||||||
// Reorder columns if the dragged item is a column
|
// Reorder columns if the dragged item is a column
|
||||||
if (isActiveAColumn && isOverAColumn) {
|
if (isActiveAColumn && isOverAColumn) {
|
||||||
setColumns(columns => {
|
setColumns((columns) => {
|
||||||
const activeColumnIndex = columns.findIndex(col => col.id === activeId);
|
const activeColumnIndex = columns.findIndex((col) => col.id === activeId);
|
||||||
const overColumnIndex = columns.findIndex(col => col.id === overId);
|
const overColumnIndex = columns.findIndex((col) => col.id === overId);
|
||||||
|
|
||||||
const reorderedColumns = arrayMove(columns, activeColumnIndex, overColumnIndex);
|
const reorderedColumns = arrayMove(columns, activeColumnIndex, overColumnIndex);
|
||||||
|
|
||||||
@ -342,9 +341,9 @@ function KanbanBoard() {
|
|||||||
|
|
||||||
// Reorder tasks within the same column
|
// Reorder tasks within the same column
|
||||||
if (isActiveATask && isOverATask) {
|
if (isActiveATask && isOverATask) {
|
||||||
setTasks(tasks => {
|
setTasks((tasks) => {
|
||||||
const activeIndex = tasks.findIndex(t => t.id === activeId);
|
const activeIndex = tasks.findIndex((t) => t.id === activeId);
|
||||||
const overIndex = tasks.findIndex(t => t.id === overId);
|
const overIndex = tasks.findIndex((t) => t.id === overId);
|
||||||
|
|
||||||
const reorderedTasks = arrayMove(tasks, activeIndex, overIndex);
|
const reorderedTasks = arrayMove(tasks, activeIndex, overIndex);
|
||||||
|
|
||||||
@ -354,15 +353,15 @@ function KanbanBoard() {
|
|||||||
|
|
||||||
// Move tasks between columns and update columnId
|
// Move tasks between columns and update columnId
|
||||||
if (isActiveATask && isOverAColumn) {
|
if (isActiveATask && isOverAColumn) {
|
||||||
setTasks(tasks => {
|
setTasks((tasks) => {
|
||||||
const activeIndex = tasks.findIndex(t => t.id === activeId);
|
const activeIndex = tasks.findIndex((t) => t.id === activeId);
|
||||||
|
|
||||||
tasks[activeIndex].columnId = overId;
|
tasks[activeIndex].columnId = overId;
|
||||||
|
|
||||||
axiosInstance
|
axiosInstance
|
||||||
.put(`todo/change_task_list_board/`, { todo_id: activeId, new_list_board_id: overId, new_index: 0 })
|
.put(`todo/change_task_list_board/`, { todo_id: activeId, new_list_board_id: overId, new_index: 0 })
|
||||||
.then(response => {})
|
.then((response) => {})
|
||||||
.catch(error => {
|
.catch((error) => {
|
||||||
console.error("Error updating task columnId:", error);
|
console.error("Error updating task columnId:", error);
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -386,9 +385,9 @@ function KanbanBoard() {
|
|||||||
if (!isActiveATask) return;
|
if (!isActiveATask) return;
|
||||||
|
|
||||||
if (isActiveATask && isOverATask) {
|
if (isActiveATask && isOverATask) {
|
||||||
setTasks(tasks => {
|
setTasks((tasks) => {
|
||||||
const activeIndex = tasks.findIndex(t => t.id === activeId);
|
const activeIndex = tasks.findIndex((t) => t.id === activeId);
|
||||||
const overIndex = tasks.findIndex(t => t.id === overId);
|
const overIndex = tasks.findIndex((t) => t.id === overId);
|
||||||
|
|
||||||
if (tasks[activeIndex].columnId !== tasks[overIndex].columnId) {
|
if (tasks[activeIndex].columnId !== tasks[overIndex].columnId) {
|
||||||
tasks[activeIndex].columnId = tasks[overIndex].columnId;
|
tasks[activeIndex].columnId = tasks[overIndex].columnId;
|
||||||
@ -402,8 +401,8 @@ function KanbanBoard() {
|
|||||||
const isOverAColumn = over.data.current?.type === "Column";
|
const isOverAColumn = over.data.current?.type === "Column";
|
||||||
|
|
||||||
if (isActiveATask && isOverAColumn) {
|
if (isActiveATask && isOverAColumn) {
|
||||||
setTasks(tasks => {
|
setTasks((tasks) => {
|
||||||
const activeIndex = tasks.findIndex(t => t.id === activeId);
|
const activeIndex = tasks.findIndex((t) => t.id === activeId);
|
||||||
|
|
||||||
tasks[activeIndex].columnId = overId;
|
tasks[activeIndex].columnId = overId;
|
||||||
return arrayMove(tasks, activeIndex, activeIndex);
|
return arrayMove(tasks, activeIndex, activeIndex);
|
||||||
|
|||||||
@ -1,18 +1,17 @@
|
|||||||
import * as React from "react";
|
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import axiosapi from "../../api/AuthenticationApi";
|
import axiosapi from "../../api/AuthenticationApi";
|
||||||
import { useAuth } from "../../hooks/authentication/IsAuthenticated";
|
import { useAuth } from "src/hooks/AuthHooks";
|
||||||
|
|
||||||
const settings = {
|
const settings = {
|
||||||
Profile: '/profile',
|
Profile: "/profile",
|
||||||
Account: '/account',
|
Account: "/account",
|
||||||
};
|
};
|
||||||
|
|
||||||
function NavBar() {
|
function NavBar() {
|
||||||
const Navigate = useNavigate();
|
const Navigate = useNavigate();
|
||||||
|
|
||||||
const { isAuthenticated, setIsAuthenticated } = useAuth();
|
const { isAuthenticated, setIsAuthenticated } = useAuth();
|
||||||
|
|
||||||
|
console.log(isAuthenticated);
|
||||||
const logout = () => {
|
const logout = () => {
|
||||||
axiosapi.apiUserLogout();
|
axiosapi.apiUserLogout();
|
||||||
setIsAuthenticated(false);
|
setIsAuthenticated(false);
|
||||||
|
|||||||
29
frontend/src/contexts/AuthContextProvider.jsx
Normal file
29
frontend/src/contexts/AuthContextProvider.jsx
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
import { useEffect } from "react";
|
||||||
|
import PropTypes from "prop-types";
|
||||||
|
import { createContext, useState } from "react";
|
||||||
|
|
||||||
|
const AuthContext = createContext();
|
||||||
|
|
||||||
|
export const AuthProvider = ({ children }) => {
|
||||||
|
const [isAuthenticated, setIsAuthenticated] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const accessToken = localStorage.getItem("access_token");
|
||||||
|
if (accessToken) {
|
||||||
|
setIsAuthenticated(true);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const contextValue = {
|
||||||
|
isAuthenticated,
|
||||||
|
setIsAuthenticated,
|
||||||
|
};
|
||||||
|
|
||||||
|
return <AuthContext.Provider value={contextValue}>{children}</AuthContext.Provider>;
|
||||||
|
};
|
||||||
|
|
||||||
|
AuthProvider.propTypes = {
|
||||||
|
children: PropTypes.node.isRequired,
|
||||||
|
};
|
||||||
|
|
||||||
|
export default AuthContext;
|
||||||
36
frontend/src/hooks/AuthHooks.jsx
Normal file
36
frontend/src/hooks/AuthHooks.jsx
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
import { useContext } from "react";
|
||||||
|
import AuthContext from "src/contexts/AuthContextProvider";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* useAuth - Custom React Hook for Accessing Authentication Context
|
||||||
|
*
|
||||||
|
* @returns {Object} An object containing:
|
||||||
|
* - {boolean} isAuthenticated: A boolean indicating whether the user is authenticated.
|
||||||
|
* - {function} setIsAuthenticated: A function to set the authentication status manually.
|
||||||
|
*
|
||||||
|
* @throws {Error} If used outside the context of an AuthProvider.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* // Import the hook
|
||||||
|
* import useAuth from './AuthHooks';
|
||||||
|
*
|
||||||
|
* // Inside a functional component
|
||||||
|
* const { isAuthenticated, setIsAuthenticated } = useAuth();
|
||||||
|
*
|
||||||
|
* // Check authentication status
|
||||||
|
* if (isAuthenticated) {
|
||||||
|
* // User is authenticated
|
||||||
|
* } else {
|
||||||
|
* // User is not authenticated
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // Manually set authentication status
|
||||||
|
* setIsAuthenticated(true);
|
||||||
|
*/
|
||||||
|
export const useAuth = () => {
|
||||||
|
const context = useContext(AuthContext);
|
||||||
|
if (!context) {
|
||||||
|
throw new Error("useAuth must be used within an AuthProvider");
|
||||||
|
}
|
||||||
|
return context;
|
||||||
|
};
|
||||||
@ -1,39 +0,0 @@
|
|||||||
import React, { createContext, useContext, useState, useEffect } from "react";
|
|
||||||
|
|
||||||
const AuthContext = createContext();
|
|
||||||
|
|
||||||
export const AuthProvider = ({ children }) => {
|
|
||||||
const [isAuthenticated, setIsAuthenticated] = useState(() => {
|
|
||||||
const access_token = localStorage.getItem("access_token");
|
|
||||||
return !!access_token;
|
|
||||||
});
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const handleTokenChange = () => {
|
|
||||||
const newAccessToken = localStorage.getItem("access_token");
|
|
||||||
setIsAuthenticated(!!newAccessToken);
|
|
||||||
};
|
|
||||||
|
|
||||||
handleTokenChange();
|
|
||||||
|
|
||||||
window.addEventListener("storage", handleTokenChange);
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
window.removeEventListener("storage", handleTokenChange);
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<AuthContext.Provider value={{ isAuthenticated, setIsAuthenticated }}>
|
|
||||||
{children}
|
|
||||||
</AuthContext.Provider>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const useAuth = () => {
|
|
||||||
const context = useContext(AuthContext);
|
|
||||||
if (!context) {
|
|
||||||
throw new Error("useAuth must be used within an AuthProvider");
|
|
||||||
}
|
|
||||||
return context;
|
|
||||||
};
|
|
||||||
@ -3,7 +3,7 @@ import ReactDOM from "react-dom/client";
|
|||||||
import App from "./App";
|
import App from "./App";
|
||||||
import { GoogleOAuthProvider } from "@react-oauth/google";
|
import { GoogleOAuthProvider } from "@react-oauth/google";
|
||||||
import { BrowserRouter } from "react-router-dom";
|
import { BrowserRouter } from "react-router-dom";
|
||||||
import { AuthProvider } from "./hooks/authentication/IsAuthenticated";
|
import { AuthProvider } from "./contexts/AuthContextProvider";
|
||||||
|
|
||||||
const GOOGLE_CLIENT_ID = import.meta.env.VITE_GOOGLE_CLIENT_ID;
|
const GOOGLE_CLIENT_ID = import.meta.env.VITE_GOOGLE_CLIENT_ID;
|
||||||
|
|
||||||
@ -12,7 +12,7 @@ ReactDOM.createRoot(document.getElementById("root")).render(
|
|||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
<Fragment>
|
<Fragment>
|
||||||
<AuthProvider>
|
<AuthProvider>
|
||||||
<App />
|
<App />
|
||||||
</AuthProvider>
|
</AuthProvider>
|
||||||
</Fragment>
|
</Fragment>
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
|
|||||||
@ -1,7 +1,12 @@
|
|||||||
import { defineConfig } from 'vite'
|
import { defineConfig } from "vite";
|
||||||
import react from '@vitejs/plugin-react'
|
import react from "@vitejs/plugin-react";
|
||||||
|
|
||||||
// https://vitejs.dev/config/
|
// https://vitejs.dev/config/
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [react()],
|
plugins: [react()],
|
||||||
})
|
resolve: {
|
||||||
|
alias: {
|
||||||
|
src: "/src",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user