I have set up authorization using the JWT token. Now I want to give the user access to the protected view, which requires authorization.
class GetUser(APIView):
authentication_classes = [JWTAuthentication]
permission_classes = [IsAuthenticated]
def post(self, request):
return Response({'username': request.user.username})
How do I check if the user is logged in on the server side? I wrote an asynchronous function that accesses the django rest framework api. But this function always returns a promise no matter what I do.
function saveToken(data) {
localStorage.setItem('access_token', data.access)
localStorage.setItem('refresh_token', data.refresh)
return true
}
async function isLoggedIn() {
return await axios.post('api/getuser/', {}, {headers: {Authorization: 'Bearer ' + localStorage.getItem('access_token')}})
.then(async function (response) { return true })
.catch(async function (error) {
return await axios.post('api/token/refresh/', {refresh: localStorage.getItem('refresh_token')})
.then(async function (response) { return saveToken(response.data) })
.catch(async function (error) { return false })
})
}
As I understand it, I can't get the value from promise in any way. That's why I decided to write the component this way, but React throws an error.
const ComponentMainArea = () => {
const location = useLocation()
const element = useOutlet()
return isLoggedIn().then((value) => {
if (!value) { return (<Navigate to="/proxy/8000/login"/>) }
else {
return (
<div className='mainarea'>
<AnimatePresence mode='wait' initial={true}>
{element && React.cloneElement(element, { key: location.pathname })}
</AnimatePresence>
</div>
)
}
})
}
How do I implement server-side authorization verification?
I also tried to use this asynchronous function in useEffect, but promise does not allow me to work with it normally, or I do not know how to do it
/account/. Then i have a interceptor which does a token refresh call when i get a 401, if it fails i will navigate the user to the login page. levelup.gitconnected.com/…