Private route does not check whether the user is logged in or not

Asked

Viewed 46 times

1

Good morning, I am trying to check if the user is logged in or not, I have an endpoint that returns me a token, on the front I am taking this token and doing this check, the problem is that even erasing the token and trying to access the route that was to be private he manages to access, when consoling he returns a pending promisse, but do not know why it is pending, since I am using async and await

In the file below I have my verification service if it is logged in or not.

import axios from "../cross-cutting/data-access";

export default {
    isSignedIn: async () => {
        try {
            const config = {
                headers: { Authorization: localStorage.getItem("token") }
            }
            const response = await axios.post("/login/verifyToken", config);

            if (response.status === 200) {
                return true
            } else return false;

        } catch (e) {
            return false;
        }
    }
}

Just below is my code where I request for this endpoint, the problem is in this function that I called "test", it is returning a pending promise

import React from "react";
import { BrowserRouter, Route, Switch, Redirect } from "react-router-dom";
import { useHistory } from "react-router-dom";


import Login from "./common-components/login";
import Home from "./Home";
import Panel from "./Panel";
import service from './services/login'

export default function Routes() {
  async function teste() {
    try {
      let response = await service.isSignedIn()
      return response;
    } catch (err) {
      return false
    }
  }
  return (

    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/login" component={Login} />
        <Route
          render={props =>
            teste() ? (
              <Panel />
            ) : (
                <Redirect to="/login" />
              )
          }
        />
      </Switch>
    </BrowserRouter>
  );
}

By deleting the token and accessing the route that was supposed to be protected, the api detorna 401, but it is still possible to access the route

inserir a descrição da imagem aqui

When consoling the "test" function it returns a pending promisse

inserir a descrição da imagem aqui

If you can tell me what I’m doing wrong I’ll be grateful, thank you !

1 answer

1


You could do to instead of passing the header, perform a previous validation off the upload for the route, then if you do not have authentication or will call the route. I don’t know if this is valid for you but I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.