How to prevent user from signing in once signed in nodejs app?

Viewed 36

I´m working on registering and signin in customer in nodejs. I want to be able to not login once the user has logged in successfully. my signing screen is like this:

import { signin } from "../api";
import { showLoading, hideLoading, showMessage } from '../utils';
import { getCustomerInfo, setCustomerInfo} from "../localStorage";


const SigninScreen = {
    //after_render function
    after_render: () =>{
        document.getElementById('signin-form').addEventListener
        ('submit', async (e) => {
            e.preventDefault();
            showLoading();
            const data = await signin({
                email: document.getElementById('email').value,
                password: document.getElementById('password').value,
            });
            hideLoading();
            if(data.error){
                showMessage(data.error);
            }else{
                setCustomerInfo(data);
                document.location.hash ='/';
            }
        })
    },
    //render function which returns signin form
    render: () => {
        if(getCustomerInfo().firstName){
            document.location.hash = '/';
        }
        return `
        <section class="menu-section">
        <div class="form-container">
            <form id="signin-form">
                <ul class="form-items">
                    <li>
                    <h1>Sign-In</h1>
                    </li>
                    <li>
                        <label for="email"> Email :</label>
                        <input type="email" name="email" id="email"/>
                    </li>
                    <li>
                        <label for="password">Password : </label>
                        <input type="password" name="password" id="password"/>
                    </li>
                    <li>
                        <button type="submit" class="btn btn-default">Sign In!</button>
                    </li>
                    <li>
                        <div>
                            New Customer?
                            <a href="/#/register"> Create Your Account </a>
                        </div>
                    </li>
                </ul>
            </form>
        </div>
        </section>
        `;
    },
};

export default SigninScreen;

my signing API looks like this:

export const signin = async({email, password}) => {
    try{
        const response = await axios({
            url: `${apiUrl}/api/customers/signin`,
            method: 'POST',
            header: {
                'Content-Type' : 'application/json',
            },
            data:{
                email,
                password,
            },
        });
        if(response.statusText !== 'OK'){
            throw new Error(response.data.message);
        }
        return response.data;
    }catch(err){
        console.log(err);
        return {error: err.response.data.message || err.message};
    }
};

I have a header component that is like this which should retrieve the firstname of the customer and display it instead of the sign-in text

import { getCustomerInfo } from '../localStorage';

 const Header = {
   render: () => {
     const { firstName } = getCustomerInfo();
     return ` 
     <div class="container">
     <nav>
       <div class="Rlogo"><h4>At Home</h4></div>
       
       <ul class="nav-links">
         <li><a href="/#home">Home</a></li>
         <li><a href="/#about">About Us</a></li>
         <li><a href="/#menu">Menu</a></li>
         <li><a href="/#resturant">Resturant</a></li>
         ${ 
          firstName
          ? `<li><a href="/#/profile">${firstName}</a></li>`
          : `<li><a href="/#/signin">Sign-In</a></li>`
        }
         <li><a href="/#/cart">Cart</a></li>
       </ul>
       <div class="burger">
         <div class="line1"></div>
         <div class="line2"></div>
         <div class="line3"></div>
       </div>
     </nav>
     </div>
     `;
   },
   after_render: () => {},
 };

export default Header;

my index.js in the front-end looks like this:

import SigninScreen from './screens/SigninScreen';
import Header from './components/Header'
import { parseRequestURL, showLoading, hideLoading} from './utils';

const routes = {
  '/': homeScreen,
  '/product/:id': mealScreen,
  '/cart/:id': CartScreen,
  '/cart': CartScreen,
  '/signin': SigninScreen,
  '/register': RegisterScreen
};
const router = async () => {
  showLoading();
  const request = parseRequestURL();
  const parseUrl = 
        (request.resource ? `/${request.resource}` : '/')
        + (request.id ? '/:id' : '')
        + (request.verb ? `/${request.verb}` : '');
  const screen = routes[parseUrl] ? routes[parseUrl] : Error404Screen;
  const header = document.getElementById('header-container');
  header.innerHTML = await Header.render();
  await Header.after_render();
  const main = document.getElementById('main-container');
  main.innerHTML = await screen.render();
  await screen.after_render();
  hideLoading();
};
window.addEventListener('load', router);
window.addEventListener('hashchange', router);

And my localStorage looks like this:

export const setCustomerInfo = ({
    id = '',
    firstName ='',
    lastName = '',
    email = '',
    password ='',
    token = '',
    isAdmin = false
}) =>{
    localStorage.setItem(
        'customerInfo',
        JSON.stringify({
            id,
            firstName ,
            lastName ,
            email ,
            password ,
            token,
            isAdmin 
        })
    );
};

export const getCustomerInfo = () => {
    return localStorage.getItem('customerInfo')
    ? JSON.parse(localStorage.getItem('customerInfo'))
    : {firstName: '', email: '', password: ''};
};

As mentioned I believe I am able to successfully login as I don't get any error when inputting correct customer info, any help of guidance is much appreciated.

1 Answers

My suggestion is using node.js express-session . I suggest this because once the user logs in, you can set session variables that can be used for each user. for example:

//after login

req.session.loggedin = true

so now you create a global function that you can access and use as middleware in your functions, that look like this:

func checkIfLoggedIn(req, res, next) {

      if (req.session.loggedin === true) {
          next()
      } else {
          req.session.destroy()
          res.redirect("/logout")
      }

and then call that from within your functions that you want to be protected by login:

app.get("/index", checkIfLoggedIn, (req, res) {
     //your code
}
Related