Merge pull request #63 from TurTaskProject/feature/tasks-api

Clean with ESlint and fix bug in signup
This commit is contained in:
Sirin Puenggun 2023-11-23 06:18:04 +07:00 committed by GitHub
commit 24a04b8239
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
45 changed files with 151 additions and 509 deletions

View File

@ -1,13 +1,11 @@
from django.urls import path
from rest_framework_simplejwt import views as jwt_views
from authentications.views import ObtainTokenPairWithCustomView, GreetingView, GoogleLogin, GoogleRetrieveUserInfo, CheckAccessTokenAndRefreshToken
from authentications.views import ObtainTokenPairWithCustomView, GoogleRetrieveUserInfo, CheckAccessTokenAndRefreshToken
urlpatterns = [
path('token/obtain/', jwt_views.TokenObtainPairView.as_view(), name='token_create'),
path('token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'),
path('token/custom_obtain/', ObtainTokenPairWithCustomView.as_view(), name='token_create_custom'),
path('hello/', GreetingView.as_view(), name='hello_world'),
path('dj-rest-auth/google/', GoogleLogin.as_view(), name="google_login"),
path('auth/google/', GoogleRetrieveUserInfo.as_view()),
path('auth/status/', CheckAccessTokenAndRefreshToken.as_view(), name='check_token_status')
]

View File

@ -7,17 +7,12 @@ from django.conf import settings
from django.contrib.auth.hashers import make_password
from rest_framework import status
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.authentication import JWTAuthentication
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from dj_rest_auth.registration.views import SocialLoginView
from google_auth_oauthlib.flow import InstalledAppFlow
from authentications.access_token_cache import store_token
@ -69,39 +64,6 @@ class ObtainTokenPairWithCustomView(APIView):
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class GreetingView(APIView):
"""
Hello World View.
Returns a greeting and user information for authenticated users.
"""
permission_classes = (IsAuthenticated,)
def get(self, request):
"""
Retrieve a greeting message and user information.
"""
user = request.user
user_info = {
"username": user.username,
}
response_data = {
"message": "Hello, world!",
"user_info": user_info,
}
return Response(response_data, status=status.HTTP_200_OK)
class GoogleLogin(SocialLoginView):
"""
Google Login View.
Handles Google OAuth2 authentication.
"""
# permission_classes = (AllowAny,)
adapter_class = GoogleOAuth2Adapter
# client_class = OAuth2Client
# callback_url = 'http://localhost:8000/accounts/google/login/callback/'
class GoogleRetrieveUserInfo(APIView):
"""
Retrieve user information from Google and create a user if not exists.

View File

@ -25,7 +25,7 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='userstats',
name='luck',
field=models.IntegerField(default=users.models.random_luck, validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(50)]),
field=models.IntegerField(default=1, validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(50)]),
),
migrations.AlterField(
model_name='userstats',

View File

@ -31,14 +31,12 @@ class CustomUser(AbstractBaseUser, PermissionsMixin):
# Fields for authentication
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'first_name']
REQUIRED_FIELDS = []
def __str__(self):
# String representation of the user
return self.username
def random_luck():
return random.randint(1, 50)
class UserStats(models.Model):
"""

View File

@ -7,6 +7,8 @@ from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser
from rest_framework_simplejwt.tokens import RefreshToken
from users.serializers import CustomUserSerializer, UpdateProfileSerializer
from users.models import CustomUser
@ -25,7 +27,9 @@ class CustomUserCreate(APIView):
if serializer.is_valid():
user = serializer.save()
if user:
return Response(serializer.data, status=status.HTTP_201_CREATED)
refresh = RefreshToken.for_user(user)
return Response(data={'access_token': str(refresh.access_token), 'refresh_token': str(refresh),},
status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

View File

@ -13,5 +13,6 @@ module.exports = {
plugins: ["react-refresh"],
rules: {
"react-refresh/only-export-components": ["warn", { allowConstantExport: true }],
"react/prop-types": 0,
},
};

View File

@ -1,21 +1,19 @@
import { useEffect } from "react";
import "./App.css";
import { Route, Routes, Navigate } from "react-router-dom";
import axios from "axios";
import TestAuth from "./components/testAuth";
import LoginPage from "./components/authentication/LoginPage";
import SignUpPage from "./components/authentication/SignUpPage";
import NavBar from "./components/navigations/Navbar";
import Calendar from "./components/calendar/calendar";
import KanbanPage from "./components/kanbanBoard/kanbanPage";
import IconSideNav from "./components/navigations/IconSideNav";
import Eisenhower from "./components/EisenhowerMatrix/Eisenhower";
import PrivateRoute from "./PrivateRoute";
import ProfileUpdatePage from "./components/profilePage";
import Dashboard from "./components/dashboard/dashboard";
import { useEffect } from "react";
import { Route, Routes, Navigate } from "react-router-dom";
import { LoginPage } from "./components/authentication/LoginPage";
import { SignUp } from "./components/authentication/SignUpPage";
import { NavBar } from "./components/navigations/Navbar";
import { Calendar } from "./components/calendar/calendar";
import { KanbanPage } from "./components/kanbanBoard/kanbanPage";
import { SideNav } from "./components/navigations/IconSideNav";
import { Eisenhower } from "./components/EisenhowerMatrix/Eisenhower";
import { PrivateRoute } from "./PrivateRoute";
import { ProfileUpdatePage } from "./components/profile/profilePage";
import { Dashboard } from "./components/dashboard/dashboard";
import { LandingPage } from "./components/landingPage/LandingPage";
import PublicRoute from "./PublicRoute";
import { PublicRoute } from "./PublicRoute";
import { useAuth } from "./hooks/AuthHooks";
const baseURL = import.meta.env.VITE_BASE_URL;
@ -48,9 +46,7 @@ const App = () => {
setIsAuthenticated(false);
}
})
.catch((error) => {
console.error("Error checking login status:", error.message);
});
.catch((error) => {});
};
checkLoginStatus();
@ -70,7 +66,7 @@ const NonAuthenticatedComponents = () => {
<Route exact path="/login" element={<LoginPage />} />
</Route>
<Route exact path="/signup" element={<PublicRoute />}>
<Route exact path="/signup" element={<SignUpPage />} />
<Route exact path="/signup" element={<SignUp />} />
</Route>
<Route path="*" element={<Navigate to="/l" />} />
</Routes>
@ -81,7 +77,7 @@ const NonAuthenticatedComponents = () => {
const AuthenticatedComponents = () => {
return (
<div className="display: flex">
<IconSideNav />
<SideNav />
<div className="flex-1 ml-[76px] overflow-hidden">
<NavBar />
<div className="overflow-x-auto">
@ -90,7 +86,6 @@ const AuthenticatedComponents = () => {
<Route exact path="/tasks" element={<PrivateRoute />}>
<Route exact path="/tasks" element={<KanbanPage />} />
</Route>
<Route path="/testAuth" element={<TestAuth />} />
<Route exact path="/profile" element={<PrivateRoute />}>
<Route exact path="/profile" element={<ProfileUpdatePage />} />
</Route>

View File

@ -1,9 +1,7 @@
import { Navigate, Outlet } from "react-router-dom";
import { useAuth } from "src/hooks/AuthHooks";
const PrivateRoute = () => {
export const PrivateRoute = () => {
const { isAuthenticated } = useAuth();
return isAuthenticated ? <Outlet /> : <Navigate to="/" />;
};
export default PrivateRoute;

View File

@ -1,9 +1,7 @@
import { Navigate, Outlet } from "react-router-dom";
import { useAuth } from "src/hooks/AuthHooks";
const PublicRoute = () => {
export const PublicRoute = () => {
const { isAuthenticated } = useAuth();
return isAuthenticated ? <Navigate to="/d" /> : <Outlet />;
};
export default PublicRoute;

View File

@ -1,10 +1,10 @@
import axios from "axios";
import axiosInstance from "./AxiosConfig";
import { axiosInstance } from "./AxiosConfig";
const baseURL = import.meta.env.VITE_BASE_URL;
// Function for user login
const apiUserLogin = (data) => {
export const apiUserLogin = (data) => {
return axiosInstance
.post("token/obtain/", data)
.then((response) => response)
@ -14,14 +14,14 @@ const apiUserLogin = (data) => {
};
// Function for user logout
const apiUserLogout = () => {
export const apiUserLogout = () => {
axiosInstance.defaults.headers["Authorization"] = ""; // Clear authorization header
localStorage.removeItem("access_token"); // Remove access token
localStorage.removeItem("refresh_token"); // Remove refresh token
};
// Function for Google login
const googleLogin = async (token) => {
export const googleLogin = async (token) => {
axios.defaults.withCredentials = true;
let res = await axios.post(`${baseURL}auth/google/`, {
code: token,
@ -30,35 +30,14 @@ const googleLogin = async (token) => {
return await res;
};
// Function to get 'hello' data
const getGreeting = () => {
return axiosInstance
.get("hello")
.then((response) => {
return response;
})
.catch((error) => {
return error;
});
};
// Function to register
const createUser = async (formData) => {
export const createUser = async (formData) => {
try {
axios.defaults.withCredentials = true;
const response = axios.post(`${baseURL}user/create/`, formData);
// const response = await axiosInstance.post('/user/create/', formData);
const response = await axios.post(`${baseURL}user/create/`, formData);
return response.data;
} catch (e) {
console.log(e);
console.error("Error in createUser function:", e);
throw e;
}
};
// Export the functions and Axios instance
export default {
apiUserLogin,
apiUserLogout,
getGreeting: getGreeting,
googleLogin,
createUser,
};

View File

@ -3,7 +3,7 @@ import { redirect } from "react-router-dom";
const baseURL = import.meta.env.VITE_BASE_URL;
const axiosInstance = axios.create({
export const axiosInstance = axios.create({
baseURL: baseURL,
timeout: 5000,
headers: {
@ -13,6 +13,14 @@ const axiosInstance = axios.create({
},
});
axiosInstance.interceptors.request.use((config) => {
const access_token = localStorage.getItem("access_token");
if (access_token) {
config.headers.Authorization = `Bearer ${access_token}`;
}
return config;
});
// handling token refresh on 401 Unauthorized errors
axiosInstance.interceptors.response.use(
(response) => response,
@ -43,5 +51,3 @@ axiosInstance.interceptors.response.use(
return Promise.reject(error);
}
);
export default axiosInstance;

View File

@ -1,4 +1,4 @@
import axiosInstance from "src/api/AxiosConfig";
import { axiosInstance } from "src/api/AxiosConfig";
const baseURL = import.meta.env.VITE_BASE_URL;

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.6 KiB

View File

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

Before

Width:  |  Height:  |  Size: 4.0 KiB

View File

@ -1,7 +1,7 @@
import { useState, useEffect } from "react";
import { FiAlertCircle, FiClock, FiXCircle, FiCheckCircle } from "react-icons/fi";
import { readTodoTasks } from "../../api/TaskApi";
import axiosInstance from "src/api/AxiosConfig";
import { axiosInstance } from "src/api/AxiosConfig";
function EachBlog({ name, colorCode, contentList, icon }) {
const [tasks, setTasks] = useState(contentList);
@ -55,7 +55,7 @@ function EachBlog({ name, colorCode, contentList, icon }) {
);
}
function Eisenhower() {
export function Eisenhower() {
const [tasks, setTasks] = useState([]);
useEffect(() => {
@ -108,5 +108,3 @@ function Eisenhower() {
</div>
);
}
export default Eisenhower;

View File

@ -1,13 +1,13 @@
import { useState } from "react";
import { useNavigate, redirect } from "react-router-dom";
import { useGoogleLogin } from "@react-oauth/google";
import axiosapi from "../../api/AuthenticationApi";
import { FcGoogle } from "react-icons/fc";
import { useAuth } from "src/hooks/AuthHooks";
import { FloatingParticles } from "../FlaotingParticles";
import { NavPreLogin } from "../navigations/NavPreLogin";
import { apiUserLogin, googleLogin } from "src/api/AuthenticationApi";
function LoginPage() {
export function LoginPage() {
const { setIsAuthenticated } = useAuth();
const Navigate = useNavigate();
@ -27,11 +27,10 @@ function LoginPage() {
event.preventDefault();
// Send a POST request to the authentication API
axiosapi
.apiUserLogin({
email: email,
password: password,
})
apiUserLogin({
email: email,
password: password,
})
.then((res) => {
localStorage.setItem("access_token", res.data.access);
localStorage.setItem("refresh_token", res.data.refresh);
@ -48,7 +47,7 @@ function LoginPage() {
redirect_uri: "postmessage",
onSuccess: async (response) => {
try {
const loginResponse = await axiosapi.googleLogin(response.code);
const loginResponse = await googleLogin(response.code);
if (loginResponse && loginResponse.data) {
const { access_token, refresh_token } = loginResponse.data;
@ -141,5 +140,3 @@ function LoginPage() {
</div>
);
}
export default LoginPage;

View File

@ -1,13 +1,12 @@
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import axiosapi from "../../api/AuthenticationApi";
import { FcGoogle } from "react-icons/fc";
import { useGoogleLogin } from "@react-oauth/google";
import { NavPreLogin } from "../navigations/NavPreLogin";
import { useAuth } from "src/hooks/AuthHooks";
import { createUser, googleLogin } from "src/api/AuthenticationApi";
export default function SignUp() {
export function SignUp() {
const Navigate = useNavigate();
const { setIsAuthenticated } = useAuth();
@ -24,20 +23,33 @@ export default function SignUp() {
setIsSubmitting(true);
setError(null);
const delay = (ms) => new Promise((res) => setTimeout(res, ms));
try {
axiosapi.createUser(formData);
const data = await createUser(formData);
localStorage.setItem("access_token", data.access_token);
localStorage.setItem("refresh_token", data.refresh_token);
await delay(200);
setIsAuthenticated(true);
Navigate("/");
} catch (error) {
console.error("Error creating user:", error);
setError("Registration failed. Please try again.");
} finally {
setIsSubmitting(false);
}
Navigate("/login");
};
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
const handleEmailChange = (e) => {
setFormData({ ...formData, email: e.target.value });
};
const handleUsernameChange = (e) => {
setFormData({ ...formData, username: e.target.value });
};
const handlePasswordChange = (e) => {
setFormData({ ...formData, password: e.target.value });
};
const googleLoginImplicit = useGoogleLogin({
@ -45,14 +57,14 @@ export default function SignUp() {
redirect_uri: "postmessage",
onSuccess: async (response) => {
try {
const loginResponse = await axiosapi.googleLogin(response.code);
const loginResponse = await googleLogin(response.code);
if (loginResponse && loginResponse.data) {
const { access_token, refresh_token } = loginResponse.data;
localStorage.setItem("access_token", access_token);
localStorage.setItem("refresh_token", refresh_token);
setIsAuthenticated(true);
Navigate("/");
Navigate("/profile");
}
} catch (error) {
console.error("Error with the POST request:", error);
@ -64,12 +76,9 @@ export default function SignUp() {
return (
<div>
<NavPreLogin text="Already have account?" btn_text="Log In" link="/login" />
<NavPreLogin text="Already have an account?" btn_text="Log In" link="/login" />
<div className="h-screen flex items-center justify-center bg-gradient-to-r from-zinc-100 via-gray-200 to-zinc-100">
<div aria-hidden="true" className="absolute inset-0 grid grid-cols-2 -space-x-52 opacity-40">
<div className="blur-[106px] h-56 bg-gradient-to-br from-primary to-purple-400"></div>
<div className="blur-[106px] h-32 bg-gradient-to-r from-cyan-400 to-sky-300"></div>
</div>
{/* ... (other code) */}
<div className="w-1/4 h-1 flex items-center justify-center z-10">
<div className="w-96 bg-white rounded-lg p-8 space-y-4 z-10">
{/* Register Form */}
@ -81,7 +90,13 @@ export default function SignUp() {
Email<span className="text-red-500 text-bold">*</span>
</p>
</label>
<input className="input" type="email" id="email" placeholder="Enter your email" onChange={handleChange} />
<input
className="input"
type="email"
id="email"
placeholder="Enter your email"
onChange={handleEmailChange}
/>
</div>
{/* Username Input */}
<div className="form-control">
@ -95,7 +110,7 @@ export default function SignUp() {
type="text"
id="Username"
placeholder="Enter your username"
onChange={handleChange}
onChange={handleUsernameChange}
/>
</div>
{/* Password Input */}
@ -110,7 +125,7 @@ export default function SignUp() {
type="password"
id="password"
placeholder="Enter your password"
onChange={handleChange}
onChange={handlePasswordChange}
/>
</div>
<br></br>

View File

@ -1,39 +0,0 @@
import axios from "axios";
const baseURL = import.meta.env.VITE_BASE_URL;
async function refreshAccessToken() {
const refresh_token = localStorage.getItem("refresh_token");
const access_token = localStorage.getItem("access_token");
if (access_token) {
return true;
}
if (!refresh_token) {
return false;
}
const refreshUrl = `${baseURL}token/refresh/`;
try {
const response = await axios.post(refreshUrl, { refresh: refresh_token });
if (response.status === 200) {
// Successful refresh - save the new access token and refresh token
const newAccessToken = response.data.access;
const newRefreshToken = response.data.refresh;
localStorage.setItem("access_token", newAccessToken);
localStorage.setItem("refresh_token", newRefreshToken);
return true;
} else {
return false;
}
} catch (error) {
return false;
}
}
export default refreshAccessToken;

View File

@ -1,9 +1,9 @@
import { readTodoTasks } from "../../api/TaskApi";
import { readTodoTasks } from "src/api/TaskApi";
let eventGuid = 0;
const mapResponseToEvents = response => {
return response.map(item => ({
const mapResponseToEvents = (response) => {
return response.map((item) => ({
id: item.id,
title: item.title,
start: item.start_event,

View File

@ -5,9 +5,9 @@ import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin from "@fullcalendar/interaction";
import { getEvents, createEventId } from "./TaskDataHandler";
import axiosInstance from "src/api/AxiosConfig";
import { axiosInstance } from "src/api/AxiosConfig";
export default class Calendar extends React.Component {
export class Calendar extends React.Component {
state = {
weekendsVisible: true,
currentEvents: [],

View File

@ -1,6 +1,6 @@
import { AreaChart, Title } from "@tremor/react";
import { useState, useEffect } from "react";
import axiosInstance from "src/api/AxiosConfig";
import { axiosInstance } from "src/api/AxiosConfig";
export const AreaChartGraph = () => {
const [areaChartDataArray, setAreaChartDataArray] = useState([]);

View File

@ -1,6 +1,6 @@
import { BarChart, Title } from "@tremor/react";
import { useState, useEffect } from "react";
import axiosInstance from "src/api/AxiosConfig";
import { axiosInstance } from "src/api/AxiosConfig";
export const BarChartGraph = () => {
const [barchartDataArray, setBarChartDataArray] = useState([]);

View File

@ -1,8 +1,8 @@
import { DonutChart } from "@tremor/react";
import axiosInstance from "src/api/AxiosConfig";
import { axiosInstance } from "src/api/AxiosConfig";
import { useState, useEffect } from "react";
export default function DonutChartGraph() {
export function DonutChartGraph() {
const [donutData, setDonutData] = useState([]);
useEffect(() => {

View File

@ -1,8 +1,8 @@
import { BadgeDelta, Card, Flex, Metric, ProgressBar, Text } from "@tremor/react";
import { useEffect, useState } from "react";
import axiosInstance from "src/api/AxiosConfig";
import { axiosInstance } from "src/api/AxiosConfig";
export default function KpiCard() {
export function KpiCard() {
const [kpiCardData, setKpiCardData] = useState({
completedThisWeek: 0,
completedLastWeek: 0,

View File

@ -1,8 +1,8 @@
import { Card, Flex, ProgressCircle } from "@tremor/react";
import { useState, useEffect } from "react";
import axiosInstance from "src/api/AxiosConfig";
import { axiosInstance } from "src/api/AxiosConfig";
export default function ProgressCircleChart() {
export function ProgressCircleChart() {
const [progressData, setProgressData] = useState(0);
useEffect(() => {

View File

@ -1,17 +1,16 @@
import { Card, Grid, Tab, TabGroup, TabList, TabPanel, TabPanels, Text, Title, Legend } from "@tremor/react";
import KpiCard from "./KpiCard";
import { KpiCard } from "./KpiCard";
import { BarChartGraph } from "./Barchart";
import DonutChartGraph from "./DonutChart";
import { DonutChartGraph } from "./DonutChart";
import { AreaChartGraph } from "./Areachart";
import ProgressCircleChart from "./ProgressCircle";
import { ProgressCircleChart } from "./ProgressCircle";
import { useState } from "react";
export default function Dashboard() {
export function Dashboard() {
const [value, setValue] = useState({
from: new Date(2021, 0, 1),
to: new Date(2023, 0, 7),
});
console.log(value);
return (
<div className="flex flex-col p-12">
<div>

View File

@ -3,13 +3,13 @@ import { BsFillTrashFill } from "react-icons/bs";
import { AiOutlinePlusCircle } from "react-icons/ai";
import { CSS } from "@dnd-kit/utilities";
import { useMemo, useState } from "react";
import TaskCard from "./taskCard";
import { TaskCard } from "./taskCard";
function ColumnContainer({ column, deleteColumn, updateColumn, createTask, tasks, deleteTask, updateTask }) {
export function ColumnContainer({ column, deleteColumn, updateColumn, createTask, tasks, deleteTask, updateTask }) {
const [editMode, setEditMode] = useState(false);
const tasksIds = useMemo(() => {
return tasks.map(task => task.id);
return tasks.map((task) => task.id);
}, [tasks]);
const { setNodeRef, attributes, listeners, transform, transition, isDragging } = useSortable({
@ -78,12 +78,12 @@ function ColumnContainer({ column, deleteColumn, updateColumn, createTask, tasks
<input
className="bg-gray-200 focus:border-blue-500 border rounded-md outline-none px-2"
value={column.title}
onChange={e => updateColumn(column.id, e.target.value)}
onChange={(e) => updateColumn(column.id, e.target.value)}
autoFocus
onBlur={() => {
setEditMode(false);
}}
onKeyDown={e => {
onKeyDown={(e) => {
if (e.key !== "Enter") return;
setEditMode(false);
}}
@ -109,7 +109,7 @@ function ColumnContainer({ column, deleteColumn, updateColumn, createTask, tasks
{/* Column task container */}
<div className="flex flex-grow flex-col gap-2 p-1 overflow-x-hidden overflow-y-auto">
<SortableContext items={tasksIds}>
{tasks.map(task => (
{tasks.map((task) => (
<TaskCard key={task.id} task={task} deleteTask={deleteTask} updateTask={updateTask} />
))}
</SortableContext>
@ -126,5 +126,3 @@ function ColumnContainer({ column, deleteColumn, updateColumn, createTask, tasks
</div>
);
}
export default ColumnContainer;

View File

@ -1,6 +1,6 @@
import ColumnContainer from "./columnContainer";
import { ColumnContainer } from "./columnContainer";
function ColumnContainerCard({ column, deleteColumn, updateColumn, createTask, tasks, deleteTask, updateTask }) {
export function ColumnContainerCard({ column, deleteColumn, updateColumn, createTask, tasks, deleteTask, updateTask }) {
return (
<div className="card bg-[#f1f2f4] shadow p-1 my-2 border-2">
<ColumnContainer
@ -15,5 +15,3 @@ function ColumnContainerCard({ column, deleteColumn, updateColumn, createTask, t
</div>
);
}
export default ColumnContainerCard;

View File

@ -1,13 +1,12 @@
import { useMemo, useState, useEffect } from "react";
import ColumnContainerCard from "./columnContainerWrapper";
import { ColumnContainerCard } from "./columnContainerWrapper";
import { DndContext, DragOverlay, PointerSensor, useSensor, useSensors } from "@dnd-kit/core";
import { SortableContext, arrayMove } from "@dnd-kit/sortable";
import { createPortal } from "react-dom";
import TaskCard from "./taskCard";
import { AiOutlinePlusCircle } from "react-icons/ai";
import axiosInstance from "src/api/AxiosConfig";
import { TaskCard } from "./taskCard";
import { axiosInstance } from "src/api/AxiosConfig";
function KanbanBoard() {
export function KanbanBoard() {
const [columns, setColumns] = useState([]);
const columnsId = useMemo(() => columns.map((col) => col.id), [columns]);
const [boardId, setBoardData] = useState();
@ -26,40 +25,6 @@ function KanbanBoard() {
})
);
// Example
// {
// "id": 95,
// "title": "Test Todo",
// "notes": "Test TodoTest TodoTest Todo",
// "importance": 1,
// "difficulty": 1,
// "challenge": false,
// "fromSystem": false,
// "creation_date": "2023-11-20T19:50:16.369308Z",
// "last_update": "2023-11-20T19:50:16.369308Z",
// "is_active": true,
// "is_full_day_event": false,
// "start_event": "2023-11-20T19:49:49Z",
// "end_event": "2023-11-23T18:00:00Z",
// "google_calendar_id": null,
// "completed": true,
// "completion_date": "2023-11-20T19:50:16.369308Z",
// "priority": 3,
// "user": 1,
// "list_board": 1,
// "tags": []
// }
// ]
// [
// {
// "id": 8,
// "name": "test",
// "position": 2,
// "board": 3
// }
// ]
useEffect(() => {
const fetchData = async () => {
try {
@ -73,7 +38,6 @@ function KanbanBoard() {
difficulty: task.difficulty,
notes: task.notes,
importance: task.importance,
difficulty: task.difficulty,
challenge: task.challenge,
fromSystem: task.fromSystem,
creation_date: task.creation_date,
@ -149,31 +113,6 @@ function KanbanBoard() {
))}
</SortableContext>
</div>
{/* create new column */}
<button
onClick={() => {
createNewColumn();
}}
className="
h-[60px]
w-[268px]
max-w-[268px]
cursor-pointer
rounded-xl
bg-[#f1f2f4]
border-2
p-4
hover:bg-gray-200
flex
gap-2
my-2
bg-opacity-60
">
<div className="my-1">
<AiOutlinePlusCircle />
</div>
Add Column
</button>
</div>
{createPortal(
@ -409,10 +348,4 @@ function KanbanBoard() {
});
}
}
function generateId() {
return Math.floor(Math.random() * 10001);
}
}
export default KanbanBoard;

View File

@ -1,12 +1,12 @@
import KanbanBoard from "./kanbanBoard";
import React, { useState } from 'react';
import { KanbanBoard } from "./kanbanBoard";
import { useState } from "react";
const KanbanPage = () => {
const [activeTab, setActiveTab] = useState('kanban');
export const KanbanPage = () => {
const [activeTab, setActiveTab] = useState("kanban");
const handleTabClick = (tabId) => {
setActiveTab(tabId);
};
const handleTabClick = (tabId) => {
setActiveTab(tabId);
};
return (
<div className="flex flex-col">
@ -29,10 +29,7 @@ const KanbanPage = () => {
</div>
</div>
<KanbanBoard />
<div className="flex justify-center border-2 ">
</div>
<div className="flex justify-center border-2 "></div>
</div>
);
};
export default KanbanPage;

View File

@ -2,9 +2,9 @@ import { useState } from "react";
import { BsFillTrashFill } from "react-icons/bs";
import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import TaskDetailModal from "./taskDetailModal";
import { TaskDetailModal } from "./taskDetailModal";
function TaskCard({ task, deleteTask, updateTask}) {
export function TaskCard({ task, deleteTask, updateTask }) {
const [mouseIsOver, setMouseIsOver] = useState(false);
const { setNodeRef, attributes, listeners, transform, transition, isDragging } = useSortable({
@ -15,7 +15,6 @@ function TaskCard({ task, deleteTask, updateTask}) {
},
});
const style = {
transition,
transform: CSS.Transform.toString(transform),
@ -79,5 +78,3 @@ function TaskCard({ task, deleteTask, updateTask}) {
</div>
);
}
export default TaskCard;

View File

@ -1,9 +1,9 @@
import React, { useState } from "react";
import { useState } from "react";
import { FaTasks, FaRegListAlt } from "react-icons/fa";
import { FaPlus } from "react-icons/fa6";
import { TbChecklist } from "react-icons/tb";
function TaskDetailModal({ title, description, tags, difficulty, challenge, importance, taskId }) {
export function TaskDetailModal({ title, description, tags, difficulty, challenge, importance, taskId }) {
const [isChallengeChecked, setChallengeChecked] = useState(challenge);
const [isImportantChecked, setImportantChecked] = useState(importance);
const [currentDifficulty, setCurrentDifficulty] = useState(difficulty);
@ -28,7 +28,8 @@ function TaskDetailModal({ title, description, tags, difficulty, challenge, impo
<div className="flex flex-col">
<h3 className="font-bold text-lg">
<span className="flex gap-2">
{<FaTasks className="my-2" />}{title}
{<FaTasks className="my-2" />}
{title}
</span>
</h3>
<p className="text-xs">{title}</p>
@ -45,13 +46,13 @@ function TaskDetailModal({ title, description, tags, difficulty, challenge, impo
<ul tabIndex={0} className="dropdown-content z-[1] menu p-2 shadow bg-base-100 rounded-box w-52">
<li>
<a>
<input type="checkbox" checked="checked" className="checkbox checkbox-sm"/>
<input type="checkbox" checked="checked" className="checkbox checkbox-sm" />
Item 2
</a>
</li>
</ul>
</div>
</div>
</div>
<div className="flex flex-nowrap overflow-x-auto"></div>
</div>
@ -144,5 +145,3 @@ function TaskDetailModal({ title, description, tags, difficulty, challenge, impo
</dialog>
);
}
export default TaskDetailModal;

View File

@ -1,9 +1,9 @@
import { useState } from "react";
import { AiOutlineHome, AiOutlineSchedule, AiOutlineUnorderedList, AiOutlinePieChart } from "react-icons/ai";
import { AiOutlineHome, AiOutlineSchedule, AiOutlineUnorderedList } from "react-icons/ai";
import { PiStepsDuotone } from "react-icons/pi";
import { IoSettingsOutline } from "react-icons/io5";
import { AnimatePresence, motion } from "framer-motion";
import { Link, useNavigate } from "react-router-dom";
import { useNavigate } from "react-router-dom";
const menuItems = [
{ id: 0, path: "/", icon: <AiOutlineHome /> },
@ -13,20 +13,12 @@ const menuItems = [
{ id: 4, path: "/priority", icon: <PiStepsDuotone /> },
];
const IconSideNav = () => {
return (
<div className="bg-slate-900 text-slate-100 flex">
<SideNav />
</div>
);
};
const SideNav = () => {
export const SideNav = () => {
const [selected, setSelected] = useState(0);
return (
<nav className="bg-slate-950 p-4 flex flex-col items-center gap-2 h-full fixed top-0 left-0 z-50">
{menuItems.map(item => (
{menuItems.map((item) => (
<NavItem
key={item.id}
icon={item.icon}
@ -65,5 +57,3 @@ const NavItem = ({ icon, selected, id, setSelected, logo, path }) => {
</motion.button>
);
};
export default IconSideNav;

View File

@ -1,5 +1,5 @@
import { useNavigate } from "react-router-dom";
import axiosapi from "../../api/AuthenticationApi";
import { apiUserLogout } from "src/api/AuthenticationApi";
import { useAuth } from "src/hooks/AuthHooks";
const settings = {
@ -7,13 +7,12 @@ const settings = {
Account: "/account",
};
function NavBar() {
export function NavBar() {
const Navigate = useNavigate();
const { isAuthenticated, setIsAuthenticated } = useAuth();
console.log(isAuthenticated);
const logout = () => {
axiosapi.apiUserLogout();
apiUserLogout();
setIsAuthenticated(false);
Navigate("/");
};
@ -66,4 +65,3 @@ function NavBar() {
</div>
);
}
export default NavBar;

View File

@ -1,7 +1,7 @@
import { useState, useRef } from "react";
import { ApiUpdateUserProfile } from "../api/UserProfileApi";
import { ApiUpdateUserProfile } from "src/api/UserProfileApi";
function ProfileUpdateComponent() {
export function ProfileUpdateComponent() {
const [file, setFile] = useState(null);
const [username, setUsername] = useState("");
const [fullName, setFullName] = useState("");
@ -100,5 +100,3 @@ function ProfileUpdateComponent() {
</div>
);
}
export default ProfileUpdateComponent;

View File

@ -1,6 +1,6 @@
import ProfileUpdateComponent from "./ProfileUpdateComponent";
import { ProfileUpdateComponent } from "./ProfileUpdateComponent";
function ProfileUpdatePage() {
export function ProfileUpdatePage() {
return (
<div>
<div className="stats shadow mt-3">
@ -142,4 +142,3 @@ function ProfileUpdatePage() {
</div>
);
}
export default ProfileUpdatePage;

View File

@ -1,115 +0,0 @@
import { useState } from "react";
import axiosapi from "../api/axiosapi";
import TextField from "@material-ui/core/TextField";
import Typography from "@material-ui/core/Typography";
import CssBaseline from "@material-ui/core/CssBaseline";
import Container from "@material-ui/core/Container";
import Button from "@material-ui/core/Button";
import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles((theme) => ({
// Styles for various elements
paper: {
marginTop: theme.spacing(8),
display: "flex",
flexDirection: "column",
alignItems: "center",
},
avatar: {
margin: theme.spacing(1),
backgroundColor: theme.palette.secondary.main,
},
form: {
width: "100%",
marginTop: theme.spacing(1),
},
submit: {
margin: theme.spacing(3, 0, 2),
},
}));
const Signup = () => {
const classes = useStyles();
const [formData, setFormData] = useState({
email: "",
username: "",
password: "",
});
const [error, setError] = useState(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
setIsSubmitting(true);
setError(null);
try {
axiosapi.createUser(formData);
} catch (error) {
console.error("Error creating user:", error);
setError("Registration failed. Please try again."); // Set an error message
} finally {
setIsSubmitting(false);
}
};
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
};
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Typography component="h1" variant="h5">
Sign Up
</Typography>
<form className={classes.form} onSubmit={handleSubmit}>
<TextField
variant="outlined"
margin="normal"
type="email"
name="email"
fullWidth
value={formData.email}
onChange={handleChange}
label="Email"
/>
<TextField
variant="outlined"
margin="normal"
type="text"
name="username"
fullWidth
value={formData.username}
onChange={handleChange}
label="Username"
/>
<TextField
variant="outlined"
margin="normal"
type="password"
name="password"
fullWidth
value={formData.password}
onChange={handleChange}
label="Password"
/>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
disabled={isSubmitting}>
{isSubmitting ? "Signing up..." : "Sign Up"}
</Button>
</form>
{error && <Typography color="error">{error}</Typography>}
</div>
</Container>
);
};
export default Signup;

View File

@ -1,7 +1,7 @@
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faGoogle, faGithub } from "@fortawesome/free-brands-svg-icons";
function Signup() {
export function Signup() {
return (
<div className="flex items-center justify-center h-screen">
<div className="flex flex-col items-center bg-white p-10 rounded-lg shadow-md">
@ -34,5 +34,3 @@ function Signup() {
</div>
);
}
export default Signup;

View File

@ -1,47 +0,0 @@
import { useState, useEffect } from "react";
import axiosapi from "../api/AuthenticationApi";
import { Button } from "@mui/material";
import { useNavigate } from "react-router-dom";
function TestAuth() {
let Navigate = useNavigate();
const [message, setMessage] = useState("");
useEffect(() => {
// Fetch the "hello" data from the server when the component mounts
axiosapi
.getGreeting()
.then((res) => {
console.log(res.data);
setMessage(res.data.user);
})
.catch((err) => {
console.log(err);
setMessage("");
});
}, []);
const logout = () => {
// Log out the user, clear tokens, and navigate to the "/testAuth" route
axiosapi.apiUserLogout();
Navigate("/testAuth");
};
return (
<div>
{message !== "" && (
<div>
<h1 className="text-xl font-bold">Login! Hello!</h1>
<h2>{message}</h2>
<Button variant="contained" onClick={logout}>
Logout
</Button>
</div>
)}
{message === "" && <h1 className="text-xl font-bold">Need to sign in, No authentication found</h1>}
</div>
);
}
export default TestAuth;

View File

@ -1,4 +1,4 @@
import React, { Fragment } from "react";
import { Fragment } from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { GoogleOAuthProvider } from "@react-oauth/google";

View File

@ -3,17 +3,14 @@
const defaultTheme = require("tailwindcss/defaultTheme");
export default {
content: [
"./src/**/*.{js,jsx}",
"./node_modules/@tremor/**/*.{js,ts,jsx,tsx}",
],
content: ["./src/**/*.{js,jsx}", "./node_modules/@tremor/**/*.{js,ts,jsx,tsx}"],
theme: {
extend: {
fontFamily: {
sans: ['"Proxima Nova"', ...defaultTheme.fontFamily.sans],
},
colors:{
colors: {
tremor: {
brand: {
faint: "#eff6ff", // blue-50
@ -42,10 +39,9 @@ export default {
strong: "#111827", // gray-900
inverted: "#ffffff", // white
},
},
},
boxShadow:{
boxShadow: {
"tremor-input": "0 1px 2px 0 rgb(0 0 0 / 0.05)",
"tremor-card": "0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",
"tremor-dropdown": "0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",
@ -92,12 +88,7 @@ export default {
/^(fill-(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(?:50|100|200|300|400|500|600|700|800|900|950))$/,
},
],
plugins: [
require("daisyui"),
require("@tailwindcss/typography"),
require("daisyui"),
require("@headlessui/tailwindcss"),
],
plugins: [require("daisyui"), require("@tailwindcss/typography"), require("@headlessui/tailwindcss")],
daisyui: {
themes: ["light", "night"],
},