User authentication using fake back end: db.json
Tags: javascript, beginners, programming, react
Published: 2023-11-20 00:23:00

**Introduction**

Hello everyone,
In this post, I will share with you how I authenticate my users using a fake database db.json, in my Front-end React project. We will first ask them to provide a correct password after registration, and also we will prevent them from going back to the app or accessing the functionality after they log out. 

**Authentication during the Login process.**
First, let's assume that we have a login component with two controlled inputs: Email and Password.
Also, this form is created using React-Bootstrap.

```JSX
import React from "react"

function Login(){
//All the other codes controlled the form. See the Previous post for more on that

return(
<div>
<form onSubmit={handleSubmit}>
<label htmlFor="email">email</label>
<input name="email" value={email}>
<label htmlFor="password">password</label>
<input name="password" value="password">
<button type="submit">login</button>
</form>
</div>
})
```
This is a simple login form. We will not talk about how to control the inputs in React for that, as we already talked about that in the previous post. see this [post](https://dev.to/kande/how-i-built-my-single-page-reactjs-web-app-1emc).
Instead, here, we will only talk about the `handleSubmit()` function.

Let's also assume that we have created the Login component in our components folder, so write this code in `Login.js`.

```JSX
import React from "react"

function Login(){
//All the other codes controlled the form.

function validation(){
let result = true;
if(email ==="" || email===null){
result = false;
alert("please enter email")
}
if(password==="" || password ===null){
result=false;
alert("please enter your password")
}
else{
return result;
}

}
function handleSubmit(e){
e.preventDefault();
fetch("your url"){
.then(response=>response.json)
.then(users=>{
if(object.keys(users).length===0){
alert("please provide valid informations")
}else{
const aUser = users.find(user =>user.password === password);
sessionStorage.setItem("email", email)

if(aUser){
alert("successfully login")
history.push("/home")
}else{
alert("invalid email or password")
}}
)})
}
}
return(<div>
<form onSubmit={handleSubmit}>
<label htmlFor="email">email</label>
<input name="email" value={email}>
<label htmlFor="password">password</label>
<input name="password" value="password">
<button type="submit">login</button>
</form>
</div>)
}
```
Here, we first created a function named `validation()`. This function is used to validate whether an email and password are entered.
If validation is verified, then in our `handleSubmit()` function, we fetch our users' array from the db.json file.

object.keys(users) is used to get an array of keys from the users' object. More on that here [Object.key()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)

this code is used to check if the users' object is empty by examining its keys. If the object has no keys (i.e., it's empty), a warning message is displayed to prompt the user to provide valid information.

If the user provides the information, then we check if the `Email` and `Password` provided by the user correspond to a user in our database. We do that using the JavaScript `fin()` function.
If the `Email` and `Password` are correct, we redirect the user to the Home page using the react `useHistory()` hook. Otherwise, we ask him to enter the right informations.

We Also create a sessionStorage with the key=“email” and the value=email.

Session storage: is often used to store temporary user data or application state that needs to be available as long as the user is interacting with a specific page but doesn't need to persist beyond that. It's a useful tool for maintaining data consistency within a single session without the need for server-side storage or cookies.

**Logout process**
Let’s create a Logout Component in our components folder.

```JSX
import React, {useEffect} from "react"
import {useHistory} from "react-router-dom"

function Logout(){
const history = useHistory()

useEffect(()=>{
const email = sessionStorage.getItem("email");
if(email==="" || email===null) history.replace("/login")
}, [history])

function handleLogout(){
sessionStorage.removeItem("email");
 history.replace("/login")
}
return (
<div>
<button onClick={handleLogout}>log out</button>
</div>)

}
```
Here, in React `useEffect()` hook, we use the variable "email" to get the `sessionStorage("email")`
And we redirect the user to the Login page when the sessionStorage becomes empty or null.

In the `handleLogout()` function, we remove the sessionStorage and redirect the user to the Login page when the Logout button is clicked. That will prevent them from accessing the app's functionality or using the browser's "back" and "forward" buttons to get back in the app.

**Conclusion**
And this concludes the Authentification process using db.json. Note that this process works just perfectly for my project as a new developer. I went through much research to get this working, so if there are any errors or mistakes, please help me correct them in the comment section. As I'm still learning, your feedback will be very helpful.

Thank you