back-end middleware cannot reach headers, but postman work fine - node.js

I'm creating new app(e-commerce) using react and react-redux with axios. For back-end using Mongo-DB(MERN stack).
There is no problem when saving data to database, but when i get that data from database middleware can not reach token from headers. But postman work fine both get and save data.
I use the same middleware when saving data to database, it work fine. But when i try to fetch data from database i get unauthorized error.
here is my code.
FOR BACK-END;
Server file;
import express from "express";
import connectDB from "./config/db.js";
import dotenv from "dotenv";
import colors from "colors";
import productRoutes from "./routes/productRoutes.js";
import userRouters from "./routes/userRoutes.js";
import shippingAddressRoutes from "./routes/shippingAddressRoutes.js";
import { notFound, errorHandler } from "./middleware/errorMiddleware.js";
dotenv.config();
connectDB();
const app = express();
// body parser
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// API route
app.get("/", (req, res) => {
res.send("API is running....");
});
// route for products
app.use("/api/products", productRoutes);
// route for users
app.use("/api/users", userRouters);
// route for shipping address
app.use("/api/shippingaddress", shippingAddressRoutes);
app.use(notFound);
app.use(errorHandler);
const PORT = process.env.PORT || 5000;
app.listen(
PORT,
console.log(
`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold
)
);
shippingAddressRoute file;
import express from "express";
import {
saveAddress,
changeAddress,
getAddress,
} from "../controllers/shippingAddressController.js";
import protect from "../middleware/authMiddleware.js";
const router = express.Router();
router
.route("/")
.get(protect, getAddress)
.post(protect, saveAddress)
.put(protect, changeAddress);
export default router;
shippingAddressController file;
import asyncHandler from "express-async-handler";
import ShippingAddress from "../models/shippingAddressModel.js";
import User from "../models/userModel.js";
// #desc get address
// #route GET /api/shippingaddress
// #access Private
const getAddress = asyncHandler(async (req, res) => {
const user = User.findById(req.user._id);
if (user) {
const { email } = req.body;
const shippingAddress = await ShippingAddress.findOne({
userEmail: email,
});
if (shippingAddress) {
res.status(200);
res.json({
address: shippingAddress.address,
city: shippingAddress.city,
postalCode: shippingAddress.postalCode,
county: shippingAddress.country,
email: shippingAddress.userEmail,
});
} else {
res.status(404);
throw new Error("Address not found");
}
} else {
res.status(404);
throw new Error("User not found");
}
});
// #desc save address
// #route POST /api/shippingaddress
// #access Private
const saveAddress = asyncHandler(async (req, res) => {
const user = User.findById(req.user._id);
if (user) {
const { address, city, postalCode, country, email } = req.body;
const existAddress = await ShippingAddress.findOne({ userEmail: email });
if (existAddress) {
res.status(400);
throw new Error(
"User already has an address. If you want to change address, try CHANGE ADDRESS."
);
} else {
const createdAddress = await ShippingAddress.create({
user: req.user._id,
address,
city,
postalCode,
country,
userEmail: email,
});
if (createdAddress) {
res.status(201);
res.json({
address: createdAddress.address,
city: createdAddress.city,
postalCode: createdAddress.postalCode,
county: createdAddress.country,
email: createdAddress.userEmail,
});
} else {
res.status(400);
throw new Error("Address did not save");
}
}
} else {
res.status(404);
throw new Error("User not found");
}
});
// #desc change address
// #route PUT /api/shippingaddress
// #access Private
const changeAddress = asyncHandler(async (req, res) => {
const user = await User.findById(req.user._id);
if (user) {
const { email } = req.body;
const shippingAddress = await ShippingAddress.findOne({
userEmail: email,
});
if (shippingAddress) {
shippingAddress.address = req.body.address || shippingAddress.address;
shippingAddress.city = req.body.city || shippingAddress.city;
shippingAddress.postalCode =
req.body.postalCode || shippingAddress.postalCode;
shippingAddress.country = req.body.country || shippingAddress.country;
const updatedShippingAddress = await shippingAddress.save();
res.status(200);
res.json({
address: updatedShippingAddress.address,
city: updatedShippingAddress.city,
postalCode: updatedShippingAddress.postalCode,
county: updatedShippingAddress.country,
email: updatedShippingAddress.userEmail,
});
} else {
res.status(404);
throw new Error("Address not found");
}
} else {
res.status(404);
throw new Error("User not found");
}
});
export { getAddress, saveAddress, changeAddress };
authMiddleware file;
import jwt from "jsonwebtoken";
import User from "../models/userModel.js";
import asyncHandler from "express-async-handler";
const protect = asyncHandler(async (req, res, next) => {
let token = req.headers.token;
if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
) {
try {
// get token from req
token = req.headers.authorization.split(" ")[1];
// verify token
const decode = jwt.verify(token, process.env.JWT_SECRET);
// get user from token
req.user = await User.findById(decode.id).select("-password");
next();
} catch (error) {
res.status(401);
throw new Error("Not1 Authorized");
}
}
if (!token) {
res.status(401);
throw new Error("Not2 Authorized");
}
});
export default protect;
FOR FRONT-END;
shippingAction file;
import { createAsyncThunk } from "#reduxjs/toolkit";
import shippingServices from "./shippingServices";
// get address
export const getAddress = createAsyncThunk(
"shipping/get",
async (userInfo, thunkAPI) => {
try {
return await shippingServices.get(userInfo);
} catch (error) {
const message =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
return thunkAPI.rejectWithValue(message);
}
}
);
// save address
export const saveAddress = createAsyncThunk(
"shipping/save",
async (addressInfo, thunkAPI) => {
try {
return await shippingServices.save(addressInfo);
} catch (error) {
const message =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
return thunkAPI.rejectWithValue(message);
}
}
);
// update address
export const updateAddress = createAsyncThunk(
"shipping/update",
async (addressInfo, thunkAPI) => {
try {
return await shippingServices.update(addressInfo);
} catch (error) {
const message =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
return thunkAPI.rejectWithValue(message);
}
}
);
shippingServices file;
import axios from "axios";
const SHIPPING_ADDRESS_URL = "/api/shippingaddress";
// save address
const save = async (addressInfo) => {
const config = {
headers: {
Authorization: `Bearer ${addressInfo.token}`,
},
};
const { data } = await axios.post(SHIPPING_ADDRESS_URL, addressInfo, config);
return data;
};
// get address
const get = async (userInfo) => {
const config = {
headers: {
Authorization: `Bearer ${userInfo.token}`,
},
};
const { data } = await axios.get(SHIPPING_ADDRESS_URL, userInfo, config);
return data;
};
// update address
const update = async (addressInfo) => {
const config = {
headers: {
Authorization: `Bearer ${addressInfo.token}`,
},
};
const { data } = await axios.put(SHIPPING_ADDRESS_URL, addressInfo, config);
return data;
};
const shippingServices = {
save,
get,
update,
};
export default shippingServices;
shippigPage file;
import React, { useState, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import { Form, Button } from "react-bootstrap";
import { useDispatch, useSelector } from "react-redux";
import FormContainer from "../components/FormContainer";
import Message from "../components/Message";
import Loader from "../components/Loader";
import { shippingSliceAction } from "../features/shipping/shippingSlice";
import { saveAddress, getAddress } from "../features/shipping/shippingAction";
function ShippingPage() {
const { user } = useSelector((state) => state.auth);
const { shippingAddress, isLoading, isSuccess, isError, message } =
useSelector((state) => state.shipping);
const [address, setAddress] = useState("");
const [city, setCity] = useState("");
const [postalCode, setPostalCode] = useState("");
const [country, setCountry] = useState("");
const [comMessage, setComMessage] = useState(null);
const dispatch = useDispatch();
const navigate = useNavigate();
useEffect(() => {
if (shippingAddress) {
setAddress(shippingAddress.address);
setCity(shippingAddress.city);
setPostalCode(shippingAddress.postalCode);
setCountry(shippingAddress.country);
} else {
const userInfo = {
token: user.token,
email: user.email,
};
dispatch(getAddress(userInfo));
}
}, []);
const submitHandler = (e) => {
e.preventDefault();
if (!user) {
navigate("/login");
} else {
if (!address || !city || !postalCode || !country) {
setComMessage("Please fill all fields");
setTimeout(() => setComMessage(null), 3000);
} else {
dispatch(
shippingSliceAction.takeAddress({
email: user.email,
address,
city,
postalCode,
country,
})
);
localStorage.setItem(
"userAddress",
JSON.stringify({
email: user.email,
address,
city,
postalCode,
country,
})
);
}
}
};
const saveContinue = () => {
if (!user) {
navigate("/login");
} else {
dispatch(
saveAddress({
email: user.email,
address,
city,
postalCode,
country,
token: user.token,
})
);
if (isSuccess) {
setComMessage("Your Address Saved");
setTimeout(() => dispatch(shippingSliceAction.reset()), 3000);
setTimeout(() => setComMessage(null), 3000);
setTimeout(() => navigate("/payment"), 4000);
}
}
};
return (
<FormContainer>
<h1>Shipping</h1>
{comMessage && <Message variant="danger">{comMessage}</Message>}
<Form onSubmit={submitHandler}>
<Form.Group controlId="address">
<Form.Label>Address</Form.Label>
<Form.Control
type="text"
placeholder="Enter Address"
value={address}
onChange={(e) => setAddress(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group controlId="city">
<Form.Label>City</Form.Label>
<Form.Control
type="text"
placeholder="Enter City"
value={city}
onChange={(e) => setCity(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group controlId="postalCode">
<Form.Label>Postal Code</Form.Label>
<Form.Control
type="number"
placeholder="Enter Postal Code"
value={postalCode}
onChange={(e) => setPostalCode(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group controlId="country">
<Form.Label>Country</Form.Label>
<Form.Control
type="text"
placeholder="Enter Country"
value={country}
onChange={(e) => setCountry(e.target.value)}
></Form.Control>
</Form.Group>
<Button className="shippingButton" type="submit" variant="primary">
Continue without saving
</Button>
{isLoading && <Loader />}
{isSuccess && <Message variant="success"></Message>}
{isError && <Message variant="danger">{message}</Message>}
<Button
className="shippingButton save"
type="button"
variant="secondary"
onClick={saveContinue}
>
Save my address and continue
</Button>
</Form>
</FormContainer>
);
}
export default ShippingPage;

// shippingServices.js
const { data } = await axios.get(SHIPPING_ADDRESS_URL, userInfo, config);
this should be
const { data } = await axios.get(SHIPPING_ADDRESS_URL, config);
Also stop using unnecessary packages like express-async-handler,
just cover entire middle-ware function body with try/catch block, call next(error) in catch block & it will work just fine.

Related

React Node js Jwt Expired Control and reflesh token

Hi i am working check jwt expired and logout or reflesh token. i try a lot of thing but i didn't solve it. I use react for frontend and node for backend.
Frontend (react.js) AuthContent.js
import axios from "axios";
import { createContext, useEffect, useState } from "react";
import jwt_decode from "jwt-decode";
import { withRouter } from "../components/with-router";
export const AuthContext = createContext();
export const AuthContexProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState(
JSON.parse(localStorage.getItem("user")) || null
);
const login = async (inputs) => {
const res = await axios.post("/auth/login", inputs);
setCurrentUser(res.data);
console.log(res.data)
};
const logout = async (inputs) => {
await axios.post("/auth/logout");
setCurrentUser(null);
};
useEffect(() => {
localStorage.setItem("user", JSON.stringify(currentUser));
}, [currentUser]);
return (
<AuthContext.Provider value={{ currentUser, login, logout }}>
{children}
</AuthContext.Provider>
);
};
backend (node.js) auth.js
`
import {db} from "../db.js"
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
export const register = (req,res) => {
const q = "SELECT * FROM users WHERE email = ? "
db.query(q, [req.body.email], (err, data) => {
if (err) return res.status(500).json(err);
if (data.length) return res.status(409).json("User already exists!");
//Hash the password and create a user
const salt = bcrypt.genSaltSync(10);
const hash = bcrypt.hashSync(req.body.password, salt);
const q = "INSERT INTO users(`firstname`,`lastname`,`email`,`password`) VALUES (?)";
const values = [req.body.firstName, req.body.lastName, req.body.email, hash];
db.query(q, [values], (err, data) => {
if (err) return res.status(500).json(err);
return res.status(200).json("User has been created.");
});
});
};
export const login = (req,res) => {
//CHECK USER
const q = "SELECT * FROM users WHERE email = ?";
db.query(q, [req.body.email], (err, data) => {
if (err) return res.status(500).json(err);
if (data.length === 0) return res.status(404).json("User not found!");
//Check password
const isPasswordCorrect = bcrypt.compareSync(
req.body.password,
data[0].password
);
if (!isPasswordCorrect)
return res.status(400).json("Wrong username or password!");
const token = jwt.sign({ id: data[0].id, expiresIn: '24h' }, "jwtkey");
const { password, ...other } = data[0];
res
.cookie("access_token", token, {
httpOnly: true,
})
.status(200)
.json(other);
});
};
export const logout = (req, res) => {
res.clearCookie("access_token",{
sameSite:"none",
secure:true
}).status(200).json("User has been logged out.")
};
I try reach access_token in frontend but always return null. i try axios interceptors but i cant solve it.

I'm in a perpetual state of loading

This webpage is in a perpetual state of loading and I don't know why. It's almost as if it's awaiting the data. I tested the backend and the user exists and should be being sent but it's just waiting. I also tried isolating the the code so that it's just the bare minimum needed and there's still the perpetual loading. The This is what it looks like: Edit user Error Below is the code:
UserEditScreens.js
import axios from "axios";
import React, { useContext, useEffect, useReducer, useState } from "react";
import Container from "react-bootstrap/Container";
import Button from "react-bootstrap/Button";
import Form from "react-bootstrap/Form";
import { Helmet } from "react-helmet-async";
import { useNavigate, useParams } from "react-router-dom";
import { toast } from "react-toastify";
import LoadingBox from "../components/LoadingBox";
import MessageBox from "../components/MessageBox";
import { getError } from "../utils";
import { Store } from "./Store";
const reducer = (state, action) => {
switch (action.value) {
case "FETCH_REQUEST":
return { ...state, loading: true };
case "FETCH_SUCCESS":
return { ...state, loading: false };
case "FETCH_FAIL":
return { ...state, loading: false, error: action.payload };
case "UPDATE_REQUEST":
return { ...state, loadingUpdate: true };
case "UPDATE_SUCCESS":
return { ...state, loadingUpdate: false };
case "UPDATE_FAIL":
return { ...state, loadingUpdate: false };
default:
return state;
}
};
export default function UserEditScreen() {
const [{ loading, error, loadingUpdate }, dispatch] = useReducer(reducer, {
loading: true,
error: "",
});
const { state } = useContext(Store);
const { userInfo } = state;
const params = useParams();
const { id: userId } = params;
const navigate = useNavigate();
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [email, setEmail] = useState("");
const [isAdmin, setIsAdmin] = useState(false);
useEffect(() => {
const fetchData = async () => {
try {
dispatch({ type: "FETCH_REQUEST" });
const { data } = await axios.get(`/api/users/${userId}`, {
headers: { authorization: `Bearer ${userInfo.token}` },
});
dispatch({ type: "FETCH_SUCCESS", payload: data });
} catch (err) {
dispatch({ type: "FETCH_FAIL", payload: getError(err) });
}
};
fetchData();
}, [userInfo, userId]);
const submitHandler = async (e) => {
e.preventDefault();
try {
dispatch({ type: "UPDATE_REQUEST" });
await axios.put(
`/api/users/${userId}`,
{ _id: userId, firstName, lastName, email, isAdmin },
{ headers: { Authorization: `Bearer ${userInfo.token}` } }
);
dispatch({ type: "UPDATE_SUCCESS" });
toast.success("User updated successfully");
navigate("/admin/users");
} catch (error) {
toast.error(getError(error));
dispatch({ type: "UPDATE_FAIL" });
}
};
return (
<Container>
<Helmet>Edit User #{userId}</Helmet>
<h1>Edit User #{userId}</h1>
{loading ? (
<LoadingBox></LoadingBox>
) : error ? (
<MessageBox variant="danger">{error}</MessageBox>
) : (
<Form onSubmit={submitHandler}>
<Form.Group className="mb-3" controlId="firstName">
<Form.Label>First Name</Form.Label>
<Form.Control
value={firstName}
type="name"
onChange={(e) => setFirstName(e.target.value)}
required
></Form.Control>
</Form.Group>
<Form.Group>
<Form.Label>Last Name</Form.Label>
<Form.Control
value={lastName}
type="name"
onChange={(e) => setLastName(e.target.value)}
required
></Form.Control>
</Form.Group>
<Form.Group className="mb-3" controlId="lastName">
<Form.Label>Email</Form.Label>
<Form.Control
value={email}
type="email"
onChange={(e) => setEmail(e.target.value)}
required
></Form.Control>
</Form.Group>
<Form.Check
className="mb-3"
type="checkbox"
id="isAdmin"
label="isAdmin"
checked={isAdmin}
onChange={(e) => setIsAdmin(e.target.checked)}
></Form.Check>
<div>
<Button disabled={loadingUpdate} type="submit">
Update
</Button>
{loadingUpdate && <LoadingBox></LoadingBox>}
</div>
</Form>
)}
</Container>
);
}
UserRoutes.js
import express from "express";
import User from "../models/userModel.js";
import bcrypt from "bcryptjs";
import { generateToken, isAuth } from "../utils.js";
import expressAsyncHandler from "express-async-handler";
const userRouter = express.Router();
userRouter.get(
"/",
isAuth,
expressAsyncHandler(async (req, res) => {
const users = await User.find();
res.send(users);
})
);
userRouter.get(
"/:id",
isAuth,
expressAsyncHandler(async (req, res) => {
const user = await User.findById(req.params.id);
if (user) {
console.log(user);
res.send(user);
} else {
res.status(404).send({ message: "User Not Found" });
}
})
);
userRouter.put(
"/:id",
isAuth,
expressAsyncHandler(async (req, res) => {
if (user) {
const user = await User.findById(req.params.id);
user.firstName = req.body.firstName || user.firstName;
user.lastName = req.body.lastName || user.lastName;
user.email = req.body.email || user.email;
user.isAdmin = Boolean(req.body.isAdmin);
const updatedUser = await user.save();
res.send({ message: "User Updated", user: updatedUser });
} else {
res.status(404).send({ message: "User Not Found" });
}
})
);
userRouter.post(
"/signin",
expressAsyncHandler(async (req, res) => {
const user = await User.findOne({ email: req.body.email });
if (user) {
if (bcrypt.compareSync(req.body.password, user.password)) {
res.send({
_id: user._id,
name: user.firstName,
email: user.email,
token: generateToken(user),
});
return;
}
}
res.status(401).send({ message: "Invalid email or password" });
})
);
userRouter.post(
"/signup",
expressAsyncHandler(async (req, res) => {
const newUser = new User({
firstName: req.body.firstName,
lastName: req.body.firstName,
email: req.body.email,
password: bcrypt.hashSync(req.body.password),
});
const user = await newUser.save();
res.send({
_id: user._id,
firstName: user.firstName,
email: user.email,
isAdmin: user.isAdmin,
token: generateToken(user),
});
})
);
userRouter.put(
"/profile",
isAuth,
expressAsyncHandler(async (req, res) => {
const user = await User.findById(req.user._id);
if (user) {
user.name = req.body.name || user.name;
user.email = req.body.email || user.email;
if (req.body.password) {
user.password = bcrypt.hashSync(req.body.password, 8);
}
const updatedUser = await user.save();
res.send({
_id: updatedUser._id,
name: updatedUser.name,
email: updatedUser.email,
isAdmin: updatedUser.isAdmin,
token: generateToken(updatedUser),
});
} else {
res.status(404).send({ message: "User not found" });
}
})
);
export default userRouter;

When activating the account, 2 messages are displayed. How to fix this? (MERN)

When activating the account, 2 messages are displayed. How to fix this? (MERN). I think the error message is displayed as double.
Does anyone know a solution to this
IMAGE 01
IMAGE 2
Here is my usercCntroller -> activating code
activate: async (req, res) => {
try {
const { activation_token } = req.body;
const user = jwt.verify(activation_token, process.env.ACTIVATION_TOKEN);
const { username, email, password } = user;
const check = await User.findOne({ email });
if (check)
return res
.status(400)
.json({ msg: "This email is already registered." });
const newUser = new User({
username,
email,
password,
});
await newUser.save();
res
.status(200)
.json({ msg: "Your account has been activated, you can now sign in." });
} catch (err) {
res.status(500).json({ msg: err.message });
}
},
Here is my frontend code
import { useParams } from "react-router-dom";
import axios from "axios";
import { message } from "antd";
import { useEffect } from "react";
const Activate = ({ history }) => {
const { activation_token } = useParams();
useEffect(() => {
if (activation_token) {
const activateUser = async () => {
try {
const res = await axios.post("/api/auth/activation", {
activation_token,
});
message.success(res.data.msg);
} catch (error) {
message.error(error.response.data.msg);
}
};
activateUser();
}
}, [activation_token]);
};
return (
<div className="">
<p>
activated
</p>
</div>
);
};
export default Activate;

why is my res.status showing nothing when I console log it?

I'm trying to check a login form with passport js and I want that when the status is correct, to log the user in but when it is incorrect to return him to the login page. I've tried doing this with an if else statement but it is not working as I've tried to console log the status and it shows nothing.
This is my frontend:
import React, {useState} from 'react'
import './login.css'
import axios from 'axios'
import { useHistory } from "react-router-dom";
function Login() {
const [username, setUsername] = useState("")
const [password, setPassword] = useState("")
const [data, setData] = useState(null)
const history = useHistory()
const onChangeUsername = (e) => {
setUsername(e.target.value)
}
const onChangePassword = (e) => {
setPassword(e.target.value)
}
const onSubmit = (e) => {
e.preventDefault()
const users = {
username: username,
password: password
}
axios.post('http://localhost:4000/users/login', users)
.then(res => console.log(res.data))
}
const loginUser = () => {
axios.get("http://localhost:4000/users/login", {
withCredentials: true
}).then(res => {
if(res.status === 200) {
setData(res)
return history.push("/home")
}
else if(res.status === 400) {
return history.push("/login")
}
console.log(res.status)
})
}
return (
<div>
<img src="https://www.freepnglogos.com/uploads/twitter-logo-png/twitter-logo-vector-png-clipart-1.png" className="twitterlogo____image"/>
<h1 className="login_____headertext">Log in to Twitter</h1>
<div className="placeholder_____global">
<form onSubmit={onSubmit}>
<input className="placeholder____div" placeholder="Phone, email or username" onChange={onChangeUsername}/>
<div>
<input className="placeholder____div" placeholder="Password" type="password" onChange={onChangePassword}/>
</div>
<div>
<button className="twitter___loginbuttonpage" onClick={loginUser}>Log in</button>
</div>
</form>
<div className="forgetPassword_____div">
<p>Forgot password?</p>
<p>ยท</p>
<p>Sign up for Twitter</p>
</div>
</div>
</div>
)
}
export default Login
Server side code:
const express = require('express');
const router = express.Router();
const Users = require('../models/users.model.js')
const passport = require("passport")
require('../authentication/passportConfig.js')(passport)
router.route('/').get((req, res) => {
Users.find()
.then(users => res.json(users))
.catch(err => res.status(400).json('Error:' + err))
})
router.route('/login').post((req, res, next) => {
passport.authenticate("local" , (err, user, info) => {
if (err) throw err;
if (!user) res.status(400).send("No user exists");
else {
req.logIn(user, err => {
if (err) throw error;
res.status(200).send("Succesfully Authenticated")
})
}
})(req, res, next)
})
router.route('/login').get((req, res) => {
res.send(req.user)
})
router.route('/add').post(async(req,res) => {
const hashedPassword = await bcrypt.hash(req.body.password, 10)
const username = req.body.username
const password = hashedPassword
const email = req.body.email
const phone = req.body.phone
const monthOfBirth = req.body.monthOfBirth
const dayOfBirth = req.body.dayOfBirth
const yearOfBirth = req.body.yearOfBirth
const newUsers = new Users({
username,
password,
email,
phone,
monthOfBirth,
dayOfBirth,
yearOfBirth
})
newUsers.save()
.then (() => res.json("User Added"))
.catch(err => res.status(400).json('error' + err))
})
module.exports = router
Before reaching console you are returning the control in if else conditions.
move your console.log before if else.
const loginUser = () => {
axios.get("http://localhost:4000/users/login", {
withCredentials: true
}).then(res => {
console.log(res.status)
if(res.status === 200) {
setData(res)
return history.push("/home")
}
else if(res.status === 400) {
return history.push("/login")
}
})
}

Authorizing the admin in React

Good day,
i am trying to check if the user is an admin if the user is an admin, he/she will be able to see the content on the page. If not then he/she will be redirected back to the home page. How can i do that? Should i use the backend code for that or can i check it on the frontend.
Route for admin page (this works perfectly fine):
router.get("/adminPanel", isAuth, isAdmin, (req, res) => {
return res.json({
title: "ADMIN PANEL",
});
});
Login page:
const [user, setUser] = useContext(userContext);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [modal, setModal] = useState(false);
useEffect(() => {
localStorage.setItem("token", JSON.stringify(user));
}, [user]);
//handlesubmit
const handleSubmit = e => {
e.preventDefault();
Axios.post("http://localhost:5000/users/login", {
email,
password,
})
.then(response => {
// localStorage.setItem(
// "token",
// JSON.stringify(response.data.token),
// )((window.location = "/"));
setUser({
token: response.data.token,
isAdmin: response.data.isAdmin,
});
window.location = "/";
// console.log(response.data.token);
// console.log(response.data.isAdmin);
})
.catch(err => {
console.log(err);
});
};
setting the role and the token in the localstorage:
const getLocalStorage = () => {
let token = localStorage.getItem("token");
let admin = localStorage.getItem("admin");
if (token) {
return JSON.parse(localStorage.getItem("token"));
} else if (token && admin) {
return JSON.parse(localStorage.getItem("admin"));
} else {
return "";
}
};
const logoutCallback = () => {
// Axios.post("http://localhost:5000/users/logout");
setUser({});
localStorage.clear("token");
window.location = "/";
};
const [user, setUser] = useState(getLocalStorage());
useEffect(() => {
setUser({ token: localStorage.getItem("token") });
}, []);
console.log(user);
Admin panel:
import React, { useContext, useEffect, useState } from "react";
import Axios from "axios";
import { userContext } from "../../App";
export default function Home() {
const [user] = useContext(userContext);
const [content, setContent] = useState("login plz to display the content");
useEffect(() => {
// if (user.isAdmin) {
// alert("is Admin");
// }
// Axios.get("http://localhost:5000/users/adminPanel").then(response =>
// console.log(user),
// );
async function fetchProtected() {
const result = await (
await fetch("http://localhost:5000/users/adminPanel", {
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${user.isAdmin}`,
},
})
).json();
if (result.data) setContent(result.data);
}
fetchProtected();
}, [user]);
return <div>{content}</div>;
}

Resources