Skip to content

Instantly share code, notes, and snippets.

@thuyanduong
Last active February 10, 2023 15:38
Show Gist options
  • Save thuyanduong/2cf79b79555d4f69753ee2e6525c771b to your computer and use it in GitHub Desktop.
Save thuyanduong/2cf79b79555d4f69753ee2e6525c771b to your computer and use it in GitHub Desktop.
Frontend Registration, Log-in and Auth

Authentication in a Full-Stack App

Fellows will be able to:

  1. Implement User Sign-up from their React apps.
  2. Store use data in state (Context) and display in the UI.
  3. Implement User Sing-in from their React apps.
  4. Use jwt and localStorage to persist user log-in upon refresh of the page.
  5. Implement Log-out.

Review

We have two backend routes that allow us to register and log in:

  • POST http://localhost:8000/users/register
  • POST http://localhost:8000/users/login

Body: {"username": "ann", "password": "123"}

Step 0. Familiarize ourselves with the React starter code

Our starter app has four pages:

  • / for our Home Page
  • /register for our Register Page
  • /login for our Log-in Page
  • /dashboard for when a user logs in

It also has Context which stores users and usersRobots.

Step 1. Implement User Sign-up/Sign-in in React

function submitForm(e){
  console.log("submitting sign up form")
  e.preventDefault()
  const options = {
    method: "POST",
    headers: {
      "Content-Type" : "application/json"
    },
    body: JSON.stringify({username, password, bio})
  }

  fetch("http://localhost:8000/users/register", options)
    .then(res => res.json())
    .then(data => {
      console.log(data)
    })
}

Step 2. Store use data in state (Context) and display in the UI.

if(data.user){
  setUser(data.user)
  setUsersRobots(data.usersRobots)
}else{
  alert(data.detail)
}
navigate('/dashboard')	

Step 3. Implement User Sign-up/Sign-in in React

if(res.status === 200){
  return res.json()
}else{
  alert("Incorrect username or password")
}

Step 4. Use jwt and localStorage to persist user log-in

Backend Code

const jwt = require('jsonwebtoken');

const token = jwt.sign({ id: user.id }, 'sankofa');
res.send({token, user, usersRobots})  

Frontend Code

localStorage.setItem("token", data.token) //when a user has been authenticated on the front-end

Step 4.5 If there is a token on load of the page, make a fetch call

useEffect(() => {
  const token = localStorage.getItem("token")
  if(token){
    console.log(token)
    //make a fetch call with the token to decode which user is already authenticated.
  }
}, [])

Backend Code

router.post('/verifytoken', verifyToken)
async function verifyToken(req, res){
  const token = req.body.token
  try {
    const userId = jwt.verify(token, 'sankofa').id
    const user = await UserModel.getSingleUserFromDB(userId) 
    const usersRobots = await UserModel.getUsersRobotsFromDB(userId)
    res.send({token, user, usersRobots})     
  } catch(err) {
    res.status(401).send("bad token")
  }
}

Frontend Code

useEffect(() => {
  const token = localStorage.getItem("token")
  if(token){
    fetch("http://localhost:8000/users/verifytoken", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({token})
    }).then(res => res.json())
    .then(data => {
      setUser(data.user)
      setUsersRobots(data.usersRobots)
    })
  }
}, [])

Step 5. Implement Log-out.

const handleLogout = (e) => {
  console.log("Logging out")
  setUser(null)
  setUsersRobots([])
  localStorage.removeItem("token")
  navigate("/")
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment