Add Refress access token / Improve Authenticate State

This commit is contained in:
sosokker 2023-11-02 01:58:04 +07:00
parent fafb8cf5f9
commit bdfa1bc68e
5 changed files with 57 additions and 57 deletions

View File

@ -52,7 +52,7 @@ function NavBar() {
const logout = () => {
// Log out the user, clear tokens, and navigate to the "/testAuth" route
axiosapi.apiUserLogout();
Navigate('/testAuth');
Navigate('/');
}
return (

View File

@ -1,7 +1,6 @@
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useGoogleLogin } from '@react-oauth/google';
import axios from 'axios';
import Avatar from '@mui/material/Avatar';
import Button from '@mui/material/Button';
import CssBaseline from '@mui/material/CssBaseline';
@ -17,6 +16,7 @@ import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
import Typography from '@mui/material/Typography';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import refreshAccessToken from './refreshAcesstoken';
import axiosapi from '../../api/axiosapi';
@ -24,8 +24,8 @@ function Copyright(props) {
return (
<Typography variant="body2" color="text.secondary" align="center" {...props}>
{'Copyright © '}
<Link color="inherit" href="https://mui.com/">
Your Website
<Link color="inherit" href="https://github.com/TurTaskProject/TurTaskWeb">
TurTask
</Link>{' '}
{new Date().getFullYear()}
{'.'}
@ -40,6 +40,12 @@ export default function SignInSide() {
const Navigate = useNavigate();
useEffect(() => {
if (!refreshAccessToken()) {
Navigate("/");
}
}, []);
const [email, setEmail] = useState("");
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
@ -76,20 +82,6 @@ export default function SignInSide() {
});
}
const responseGoogle = async (response) => {
// Handle Google login response
let googleResponse = await axiosapi.googleLogin(response.access_token);
console.log('Google Response:\n', googleResponse);
if (googleResponse.status === 200) {
// Store Google login tokens and set the authorization header on success
localStorage.setItem('access_token', googleResponse.data.access_token);
localStorage.setItem('refresh_token', googleResponse.data.refresh_token);
axiosapi.axiosInstance.defaults.headers['Authorization'] = "Bearer " + googleResponse.data.access_token;
Navigate('/');
}
}
const googleLoginImplicit = useGoogleLogin({
flow: 'auth-code',
redirect_uri: 'postmessage',

View File

@ -1,48 +1,19 @@
import { useState, useEffect } from 'react';
import axiosapi from '../../api/axiosapi';
function IsAuthenticated() {
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
const checkAuthentication = async () => {
const access_token = localStorage.getItem('access_token');
const refresh_token = localStorage.getItem('refresh_token');
const access_token = localStorage.getItem('access_token');
if (access_token && refresh_token) {
const isAccessTokenExpired = checkIfAccessTokenExpired(access_token);
if (!isAccessTokenExpired) {
setIsAuthenticated(true);
} else {
try {
// Attempt to refresh the access token using the refresh token
const response = await axiosapi.refreshAccessToken(refresh_token);
if (response.status === 200) {
const newAccessToken = response.data.access_token;
localStorage.setItem('access_token', newAccessToken);
setIsAuthenticated(true);
} else {
setIsAuthenticated(false);
}
} catch (error) {
setIsAuthenticated(false);
}
}
} else {
setIsAuthenticated(false);
}
};
checkAuthentication();
if (access_token) {
setIsAuthenticated(true);
} else {
setIsAuthenticated(false);
}
}, []);
const checkIfAccessTokenExpired = (accessToken) => {
// Need to change logic again!
return !accessToken;
};
return isAuthenticated;
}
export default IsAuthenticated;
export default IsAuthenticated;

View File

@ -21,8 +21,8 @@ function Copyright(props) {
return (
<Typography variant="body2" color="text.secondary" align="center" {...props}>
{'Copyright © '}
<Link color="inherit" href="https://mui.com/">
Your Website
<Link color="inherit" href="https://github.com/TurTaskProject/TurTaskWeb">
TurTask
</Link>{' '}
{new Date().getFullYear()}
{'.'}

View File

@ -0,0 +1,37 @@
import axios from 'axios';
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 = 'http://127.0.0.1:8000/api/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;