Home > Blockchain >  request to login to a node server, using react
request to login to a node server, using react

Time:02-05

Here is the situation: I have a database which contains a user and password registered. My assignment, for now, is to create a login form, and login with a registered uname and pw. Uname and pw are registered in the server/database already. ps: I did not create the server nor database.

Node server code

import express from 'express';
import cors from 'cors';
import http from 'http';
import { Sequelize } from 'sequelize';
import { Data } from './database';
import { router } from './routes/Router';
import { initialData } from './database/someData';

const closeServer = async (
  server: http.Server,
  sequelize: Sequelize,
  signal?: string
) => {
  server.close();
  await sequelize.close();
  process.exit();
};

const runServer = async (): Promise<void> => {
  const PORT = process.env.PORT || 8082;
  const app = express();
  const sequelize = Data.init();

  app.use(
    cors({
      credentials: true,
      origin: 'http://localhost:3000',
    })
  );

  app.use('/api', router);
  const server = app.listen(PORT, () => {
    console.log(`Starting server at ${PORT}`);
  });
  try {
    await sequelize.authenticate();
    await sequelize.sync({
      force: process.env.SERVER === 'reset',
    });
    if (process.env.SERVER === 'reset') await initialData();
  } catch (e) {
    closeServer(server, sequelize);
    throw e;
  }
};

runServer()
  .then(() => {
    console.log('Run successfully');
  })
  .catch((ex: Error) => {
    console.log('Unable to run:', ex);
  });

I need help on what is that I have to do.

When I input username and pw, on the form, what are the methods to use for sending the info? And then, when the info reaches the server, i think the username and pw need to be validated with jwt, and then check if the user and pw exists. how do i do that?

What i have understood so far is that i gotta use axios to send info to server, but thats it. Do i need to use jwt for the login?

What is the normal flow for this kind of mechanism? I am using react as a framework.

CodePudding user response:

So there are quite few steps here.

  1. First you have to create endpoint on your backend server for issuing jwt tokens. Jwt tokens can be used as a pass for user to login. So in your router you would add something like this:

    router.post('/login', (req, res)=> {
        const username = req.body.username
        const password = req.body.password
        // Then you make db call to verify username and password are correct.
        if Credentials are valid, you would issue jwt token
        jwt.sign({ 
          // here you can save extra information of user. Also remember this information must be public since anyone can see it. Do not put user password here
          email: 'email',
           userId: 'id',
         }, "secret")
    
    })
    
  2. After this, you need some kind of middleware on backend, so that on each user request, you check and verify this jwt token which is sent from react application. For example you could write isAuth middleware:


const jwt =require("jsonwebtoken");

export const isAuth= (req, res, next) => {
  try {
    // here we attach request in auth header, with Bearer "jwt token" format. So we extract jwt token and verify it
    const authHeader = req.get("Authorization");
    if (!authHeader) {
      return res.status(401).json({ message: "no token" });
    }
    const token = authHeader.split(" ")[1];
    let decodedToken;

    decodedToken = jwt.verify(token, "secret");

    if (!decodedToken) {
      return res.status(401).json({ message: "Wrong token" });
    }
 
    req.userId = decodedToken.userId;

    next();
  } catch (err) {
    console.error(err);
    return res.status(401).json({ message: err });
  }
};

Now you would be able to have backend endpoints like this:

// This is how you would require login on some routes
router.post("/getMyPrivateInfo", isAuth, QueryPrivatInfo)
  1. Now on React side, you would make request for login like this:
axios.post("/login", {
username: '1',
password: "2"
})
This would return jwt token, now you would save this token in local storage.

After its saved in local storage and you make request with axios for private info you would do following

axios.post("/getMyPrivateInfo", {any request body info neeeded}, {
 headers: {
  Authorization: "Bearer jwtTokenFromLocalStorage"
}
})

This is how whole flow will work, hope it makes sense

  • Related