User login best practices in React JS and Apollo

Viewed 73

I have multiple questions about user login logic.

I'm using React JS with Apollo client for the front end, and I use Node JS with GraphQL and Apollo server for the back end.

And that's how I handle the user login: I send the email and password from the front end to the back end via the Login mutation, and then I run the login logic

  const Login = async (props) => {
  const { prisma, email, password } = props;
  const user = await prisma.Users.findUnique({ where: { email } });
  if (user) {
    const check = CheckPasswords({ currentPassword, storedPassword });
        if (!check) {
            return { status: false, cause: 'password', response: 'Wrong password' };
        } else {
            const token = CreateToken({
                id: target.id,
                email: target.email,
                isAdmin: target.isAdmin,
            });
            return { status: true, response: 'Login successful', token: token }; // THIS IS THE RESPONSE OBJECT
        }
  } else {
        return { status: false, response: 'E-mail does not exist' };
  }
};

to check if the user is valid or not and if he is valid I generate a token with his ID, email and isAdmin property and send it back with the response object.

And then in the front end I run this Login function if the login is successfu:

import Cookies from 'universal-cookie';

const Login = (token, navigate) => {
  const cookies = new Cookies();
  cookies.set('token', token, { path: '/' });
  setTimeout(() => {
    navigate('/');
    window.location.reload(false);
  }, 2000);
};

export default Login;

I use Universal Cookie to set the user token and to remove the token if the user wants to logout :

import Cookies from 'universal-cookie';

const Logout = (navigate) => {
  const cookies = new Cookies();
  const cookie = cookies.get('token');

  if (cookie) {
    cookies.remove('token');
    navigate('/');
    window.location.reload(false);
  }
};

export default Logout;

So my questions are:

  1. Is this is a good approach ?
  2. Sometimes when I try to logout the token stays there so I have to press the logout button multiple times or sometimes I have to remove the cookie from the dev tools myself, so what's the problem here?
0 Answers
Related