├── backend ├── Procfile ├── .env.example ├── images │ ├── galaxyS.png │ ├── iphone12.jpg │ └── iphone12pro.jpg ├── utils │ └── generateAuthToken.js ├── .gitignore ├── models │ └── user.js ├── package.json ├── middleware │ └── auth.js ├── products.js ├── routes │ ├── login.js │ └── register.js └── index.js └── frontend ├── public ├── robots.txt ├── favicon.ico ├── logo192.png ├── logo512.png ├── manifest.json └── index.html ├── src ├── components │ ├── NotFound.jsx │ ├── auth │ │ ├── StyledForm.js │ │ ├── Login.jsx │ │ └── Register.jsx │ ├── Home.jsx │ ├── NavBar.jsx │ └── Cart.jsx ├── slices │ ├── api.js │ ├── productsApi.js │ ├── productsSlice.js │ ├── cartSlice.js │ └── authSlice.js ├── index.js ├── App.js └── App.css ├── .gitignore ├── package.json └── README.md /backend/Procfile: -------------------------------------------------------------------------------- 1 | web: node index.js -------------------------------------------------------------------------------- /backend/.env.example: -------------------------------------------------------------------------------- 1 | DB_URI = <> 2 | JWT_SECRET_KEY = <> -------------------------------------------------------------------------------- /frontend/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /backend/images/galaxyS.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chaoocharles/auth-in-react-redux-toolkit-and-node/HEAD/backend/images/galaxyS.png -------------------------------------------------------------------------------- /backend/images/iphone12.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chaoocharles/auth-in-react-redux-toolkit-and-node/HEAD/backend/images/iphone12.jpg -------------------------------------------------------------------------------- /frontend/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chaoocharles/auth-in-react-redux-toolkit-and-node/HEAD/frontend/public/favicon.ico -------------------------------------------------------------------------------- /frontend/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chaoocharles/auth-in-react-redux-toolkit-and-node/HEAD/frontend/public/logo192.png -------------------------------------------------------------------------------- /frontend/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chaoocharles/auth-in-react-redux-toolkit-and-node/HEAD/frontend/public/logo512.png -------------------------------------------------------------------------------- /backend/images/iphone12pro.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chaoocharles/auth-in-react-redux-toolkit-and-node/HEAD/backend/images/iphone12pro.jpg -------------------------------------------------------------------------------- /frontend/src/components/NotFound.jsx: -------------------------------------------------------------------------------- 1 | const NotFound = () => { 2 | return ( 3 |
4 |

404

5 |

Page not found

6 |
7 | ); 8 | }; 9 | 10 | export default NotFound; 11 | -------------------------------------------------------------------------------- /frontend/src/slices/api.js: -------------------------------------------------------------------------------- 1 | export const url = "http://localhost:5000/api"; 2 | 3 | export const setHeaders = () => { 4 | const headers = { 5 | headers: { 6 | "x-auth-token": localStorage.getItem("token"), 7 | }, 8 | }; 9 | 10 | return headers; 11 | }; 12 | -------------------------------------------------------------------------------- /backend/utils/generateAuthToken.js: -------------------------------------------------------------------------------- 1 | const jwt = require("jsonwebtoken"); 2 | 3 | const generateAuthToken = (user) => { 4 | const jwtSecretKey = process.env.JWT_SECRET_KEY; 5 | const token = jwt.sign( 6 | { _id: user._id, name: user.name, email: user.email }, 7 | jwtSecretKey 8 | ); 9 | 10 | return token; 11 | }; 12 | 13 | module.exports = generateAuthToken; 14 | -------------------------------------------------------------------------------- /frontend/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /backend/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env 17 | .env.local 18 | .env.development.local 19 | .env.test.local 20 | .env.production.local 21 | 22 | npm-debug.log* 23 | yarn-debug.log* 24 | yarn-error.log* 25 | -------------------------------------------------------------------------------- /backend/models/user.js: -------------------------------------------------------------------------------- 1 | const mongoose = require("mongoose"); 2 | 3 | require("dotenv").config(); 4 | 5 | const userSchema = new mongoose.Schema({ 6 | name: { type: String, required: true, minlength: 3, maxlength: 30 }, 7 | email: { 8 | type: String, 9 | required: true, 10 | minlength: 3, 11 | maxlength: 200, 12 | unique: true, 13 | }, 14 | password: { type: String, required: true, minlength: 3, maxlength: 1024 }, 15 | }); 16 | 17 | const User = mongoose.model("User", userSchema); 18 | 19 | exports.User = User; 20 | -------------------------------------------------------------------------------- /backend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "backend", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "bcrypt": "^5.0.1", 14 | "cors": "^2.8.5", 15 | "dotenv": "^16.0.0", 16 | "express": "^4.17.1", 17 | "joi": "^17.6.0", 18 | "jsonwebtoken": "^8.5.1", 19 | "mongoose": "^6.2.10", 20 | "nodemon": "^2.0.12" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /backend/middleware/auth.js: -------------------------------------------------------------------------------- 1 | const jwt = require("jsonwebtoken"); 2 | require("dotenv").config(); 3 | 4 | function auth(req, res, next) { 5 | const token = req.header("x-auth-token"); 6 | if (!token) return res.status(401).send("Access denied. Not authorized..."); 7 | try { 8 | const jwtSecretKey = process.env.TODO_APP_JWT_SECRET_KEY; 9 | const decoded = jwt.verify(token, jwtSecretKey); 10 | req.user = decoded; 11 | next(); 12 | } catch (ex) { 13 | res.status(400).send("Invalid auth token..."); 14 | } 15 | } 16 | 17 | module.exports = auth; 18 | -------------------------------------------------------------------------------- /frontend/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /frontend/src/slices/productsApi.js: -------------------------------------------------------------------------------- 1 | // Need to use the React-specific entry point to import createApi 2 | import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react"; 3 | 4 | // Define a service using a base URL and expected endpoints 5 | export const productsApi = createApi({ 6 | reducerPath: "productsApi", 7 | baseQuery: fetchBaseQuery({ baseUrl: "http://localhost:5000/" }), 8 | endpoints: (builder) => ({ 9 | getAllProducts: builder.query({ 10 | query: () => `products`, 11 | }), 12 | }), 13 | }); 14 | 15 | // Export hooks for usage in functional components, which are 16 | // auto-generated based on the defined endpoints 17 | export const { useGetAllProductsQuery } = productsApi; 18 | -------------------------------------------------------------------------------- /frontend/src/components/auth/StyledForm.js: -------------------------------------------------------------------------------- 1 | import styled from "styled-components"; 2 | 3 | export const StyledForm = styled.form` 4 | max-width: 350px; 5 | width: 100%; 6 | margin: 2rem auto; 7 | 8 | h2 { 9 | margin-bottom: 1rem; 10 | } 11 | 12 | button, 13 | input { 14 | height: 35px; 15 | width: 100%; 16 | padding: 7px; 17 | outline: none; 18 | border-radius: 5px; 19 | border: 1px solid rgb(220, 220, 220); 20 | margin-bottom: 1rem; 21 | 22 | &:focus { 23 | border: 1px solid rgb(0, 208, 255); 24 | } 25 | } 26 | 27 | button { 28 | cursor: pointer; 29 | 30 | &:focus { 31 | border: none; 32 | } 33 | } 34 | 35 | p { 36 | font-size: 14px; 37 | color: red; 38 | } 39 | `; 40 | -------------------------------------------------------------------------------- /backend/products.js: -------------------------------------------------------------------------------- 1 | const products = [ 2 | { 3 | id: 1, 4 | name: "iPhone 12 Pro", 5 | brand: "Apple", 6 | desc: "6.1-inch display", 7 | price: 999, 8 | image: 9 | "https://res.cloudinary.com/chaoocharles/image/upload/v1629289889/online-shop/iphone12pro_e09phn.jpg", 10 | }, 11 | { 12 | id: 2, 13 | name: "iPhone 12", 14 | brand: "Apple", 15 | desc: "5.4-inch mini display", 16 | price: 699, 17 | image: 18 | "https://res.cloudinary.com/chaoocharles/image/upload/v1629289889/online-shop/iphone12_efhrcp.jpg", 19 | }, 20 | { 21 | id: 3, 22 | name: "Galaxy S", 23 | brand: "Samsung", 24 | desc: "6.5-inch display", 25 | price: 399, 26 | image: 27 | "https://res.cloudinary.com/chaoocharles/image/upload/v1629289889/online-shop/galaxyS_dvjf5w.png", 28 | }, 29 | ]; 30 | 31 | module.exports = products; 32 | -------------------------------------------------------------------------------- /frontend/src/index.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import ReactDOM from "react-dom"; 3 | import App from "./App"; 4 | 5 | import { Provider } from "react-redux"; 6 | import { configureStore } from "@reduxjs/toolkit"; 7 | 8 | import productsReducer, { productsFetch } from "./slices/productsSlice"; 9 | import cartReducer, { getTotals } from "./slices/cartSlice"; 10 | import authReducer from "./slices/authSlice"; 11 | import { productsApi } from "./slices/productsApi"; 12 | 13 | const store = configureStore({ 14 | reducer: { 15 | products: productsReducer, 16 | cart: cartReducer, 17 | auth: authReducer, 18 | [productsApi.reducerPath]: productsApi.reducer, 19 | }, 20 | middleware: (getDefaultMiddleware) => 21 | getDefaultMiddleware().concat(productsApi.middleware), 22 | }); 23 | 24 | store.dispatch(productsFetch()); 25 | store.dispatch(getTotals()); 26 | 27 | ReactDOM.render( 28 | 29 | 30 | 31 | 32 | , 33 | document.getElementById("root") 34 | ); 35 | -------------------------------------------------------------------------------- /backend/routes/login.js: -------------------------------------------------------------------------------- 1 | const bcrypt = require("bcrypt"); 2 | const { User } = require("../models/user"); 3 | const Joi = require("joi"); 4 | const express = require("express"); 5 | const generateAuthToken = require("../utils/generateAuthToken"); 6 | const router = express.Router(); 7 | 8 | router.post("/", async (req, res) => { 9 | const schema = Joi.object({ 10 | email: Joi.string().min(3).max(200).required().email(), 11 | password: Joi.string().min(6).max(200).required(), 12 | }); 13 | 14 | const { error } = schema.validate(req.body); 15 | 16 | if (error) return res.status(400).send(error.details[0].message); 17 | 18 | let user = await User.findOne({ email: req.body.email }); 19 | if (!user) return res.status(400).send("Invalid email or password..."); 20 | 21 | const validPassword = await bcrypt.compare(req.body.password, user.password); 22 | if (!validPassword) 23 | return res.status(400).send("Invalid email or password..."); 24 | 25 | const token = generateAuthToken(user); 26 | 27 | res.send(token); 28 | }); 29 | 30 | module.exports = router; 31 | -------------------------------------------------------------------------------- /backend/index.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const cors = require("cors"); 3 | const mongoose = require("mongoose"); 4 | const register = require("./routes/register"); 5 | const login = require("./routes/login"); 6 | 7 | const products = require("./products"); 8 | 9 | const app = express(); 10 | 11 | require("dotenv").config(); 12 | 13 | app.use(express.json()); 14 | app.use(cors()); 15 | 16 | app.use("/api/register", register); 17 | app.use("/api/login", login); 18 | 19 | app.get("/", (req, res) => { 20 | res.send("Welcome our to online shop API..."); 21 | }); 22 | 23 | app.get("/products", (req, res) => { 24 | res.send(products); 25 | }); 26 | 27 | const uri = process.env.DB_URI; 28 | const port = process.env.PORT || 5000; 29 | 30 | app.listen(port, () => { 31 | console.log(`Server running on port: ${port}...`); 32 | }); 33 | 34 | mongoose 35 | .connect(uri, { 36 | useNewUrlParser: true, 37 | useUnifiedTopology: true, 38 | }) 39 | .then(() => console.log("MongoDB connection established...")) 40 | .catch((error) => console.error("MongoDB connection failed:", error.message)); 41 | -------------------------------------------------------------------------------- /frontend/src/slices/productsSlice.js: -------------------------------------------------------------------------------- 1 | import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"; 2 | import axios from "axios"; 3 | 4 | const initialState = { 5 | items: [], 6 | status: null, 7 | }; 8 | 9 | export const productsFetch = createAsyncThunk( 10 | "products/productsFetch", 11 | async () => { 12 | try { 13 | const response = await axios.get( 14 | "https://chaoo-online-shop.herokuapp.com/products" 15 | ); 16 | return response.data; 17 | } catch (error) { 18 | console.log(error); 19 | } 20 | } 21 | ); 22 | 23 | const productsSlice = createSlice({ 24 | name: "products", 25 | initialState, 26 | reducers: {}, 27 | extraReducers: { 28 | [productsFetch.pending]: (state, action) => { 29 | state.status = "pending"; 30 | }, 31 | [productsFetch.fulfilled]: (state, action) => { 32 | state.items = action.payload; 33 | state.status = "success"; 34 | }, 35 | [productsFetch.rejected]: (state, action) => { 36 | state.status = "rejected"; 37 | }, 38 | }, 39 | }); 40 | 41 | export default productsSlice.reducer; 42 | -------------------------------------------------------------------------------- /backend/routes/register.js: -------------------------------------------------------------------------------- 1 | const bcrypt = require("bcrypt"); 2 | const { User } = require("../models/user"); 3 | const Joi = require("joi"); 4 | const express = require("express"); 5 | const generateAuthToken = require("../utils/generateAuthToken"); 6 | const router = express.Router(); 7 | 8 | router.post("/", async (req, res) => { 9 | const schema = Joi.object({ 10 | name: Joi.string().min(3).max(30).required(), 11 | email: Joi.string().min(3).max(200).required().email(), 12 | password: Joi.string().min(6).max(200).required(), 13 | }); 14 | 15 | const { error } = schema.validate(req.body); 16 | 17 | if (error) return res.status(400).send(error.details[0].message); 18 | 19 | let user = await User.findOne({ email: req.body.email }); 20 | if (user) return res.status(400).send("User already exists..."); 21 | 22 | console.log("here"); 23 | 24 | const { name, email, password } = req.body; 25 | 26 | user = new User({ name, email, password }); 27 | 28 | const salt = await bcrypt.genSalt(10); 29 | user.password = await bcrypt.hash(user.password, salt); 30 | 31 | await user.save(); 32 | 33 | const token = generateAuthToken(user); 34 | 35 | res.send(token); 36 | }); 37 | 38 | module.exports = router; 39 | -------------------------------------------------------------------------------- /frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "frontend", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@reduxjs/toolkit": "^1.6.1", 7 | "@testing-library/jest-dom": "^5.14.1", 8 | "@testing-library/react": "^11.2.7", 9 | "@testing-library/user-event": "^12.8.3", 10 | "axios": "^0.21.1", 11 | "jwt-decode": "^3.1.2", 12 | "react": "^17.0.2", 13 | "react-dom": "^17.0.2", 14 | "react-redux": "^7.2.4", 15 | "react-router-dom": "^6.3.0", 16 | "react-scripts": "4.0.3", 17 | "react-toastify": "^7.0.4", 18 | "styled-components": "^5.3.5", 19 | "web-vitals": "^1.1.2" 20 | }, 21 | "scripts": { 22 | "start": "react-scripts start", 23 | "build": "react-scripts build", 24 | "test": "react-scripts test", 25 | "eject": "react-scripts eject" 26 | }, 27 | "eslintConfig": { 28 | "extends": [ 29 | "react-app", 30 | "react-app/jest" 31 | ] 32 | }, 33 | "browserslist": { 34 | "production": [ 35 | ">0.2%", 36 | "not dead", 37 | "not op_mini all" 38 | ], 39 | "development": [ 40 | "last 1 chrome version", 41 | "last 1 firefox version", 42 | "last 1 safari version" 43 | ] 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /frontend/src/App.js: -------------------------------------------------------------------------------- 1 | import "./App.css"; 2 | import { BrowserRouter, Routes, Route } from "react-router-dom"; 3 | import { ToastContainer } from "react-toastify"; 4 | 5 | import Home from "./components/Home"; 6 | import NavBar from "./components/NavBar"; 7 | import NotFound from "./components/NotFound"; 8 | import Cart from "./components/Cart"; 9 | 10 | import "react-toastify/dist/ReactToastify.css"; 11 | import Register from "./components/auth/Register"; 12 | import Login from "./components/auth/Login"; 13 | import { useEffect } from "react"; 14 | import { useDispatch } from "react-redux"; 15 | import { loadUser } from "./slices/authSlice"; 16 | 17 | function App() { 18 | const dispatch = useDispatch(); 19 | 20 | useEffect(() => { 21 | dispatch(loadUser(null)); 22 | }, [dispatch]); 23 | 24 | return ( 25 |
26 | 27 | 28 | 29 |
30 | 31 | } /> 32 | } /> 33 | } /> 34 | } /> 35 | } /> 36 | 37 | 38 |
39 |
40 |
41 | ); 42 | } 43 | 44 | export default App; 45 | -------------------------------------------------------------------------------- /frontend/src/components/auth/Login.jsx: -------------------------------------------------------------------------------- 1 | import { useEffect, useState } from "react"; 2 | import { useDispatch, useSelector } from "react-redux"; 3 | import { loginUser } from "../../slices/authSlice"; 4 | import { useNavigate } from "react-router-dom"; 5 | import { StyledForm } from "./StyledForm"; 6 | 7 | const Login = () => { 8 | const navigate = useNavigate(); 9 | const dispatch = useDispatch(); 10 | const auth = useSelector((state) => state.auth); 11 | 12 | const [user, setUser] = useState({ 13 | email: "", 14 | password: "", 15 | }); 16 | 17 | useEffect(() => { 18 | if (auth._id) { 19 | navigate("/cart"); 20 | } 21 | }, [auth._id, navigate]); 22 | 23 | const handleSubmit = (e) => { 24 | e.preventDefault(); 25 | 26 | console.log(user); 27 | dispatch(loginUser(user)); 28 | }; 29 | 30 | return ( 31 | <> 32 | 33 |

Login

34 | setUser({ ...user, email: e.target.value })} 38 | /> 39 | setUser({ ...user, password: e.target.value })} 43 | /> 44 | 47 | {auth.loginStatus === "rejected" ?

{auth.loginError}

: null} 48 |
49 | 50 | ); 51 | }; 52 | 53 | export default Login; 54 | -------------------------------------------------------------------------------- /frontend/src/components/Home.jsx: -------------------------------------------------------------------------------- 1 | import { useDispatch, useSelector } from "react-redux"; 2 | import { useNavigate } from "react-router"; 3 | import { addToCart } from "../slices/cartSlice"; 4 | import { useGetAllProductsQuery } from "../slices/productsApi"; 5 | 6 | const Home = () => { 7 | const { items: products, status } = useSelector((state) => state.products); 8 | const dispatch = useDispatch(); 9 | const navigate = useNavigate(); 10 | 11 | const { data, error, isLoading } = useGetAllProductsQuery(); 12 | 13 | const handleAddToCart = (product) => { 14 | dispatch(addToCart(product)); 15 | navigate("/cart"); 16 | }; 17 | 18 | return ( 19 |
20 | {status === "success" ? ( 21 | <> 22 |

New Arrivals

23 |
24 | {data && 25 | data?.map((product) => ( 26 |
27 |

{product.name}

28 | {product.name} 29 |
30 | {product.desc} 31 | ${product.price} 32 |
33 | 36 |
37 | ))} 38 |
39 | 40 | ) : status === "pending" ? ( 41 |

Loading...

42 | ) : ( 43 |

Unexpected error occured...

44 | )} 45 |
46 | ); 47 | }; 48 | 49 | export default Home; 50 | -------------------------------------------------------------------------------- /frontend/src/components/auth/Register.jsx: -------------------------------------------------------------------------------- 1 | import { useState, useEffect } from "react"; 2 | import { useNavigate } from "react-router-dom"; 3 | import { useDispatch, useSelector } from "react-redux"; 4 | import { registerUser } from "../../slices/authSlice"; 5 | import { StyledForm } from "./StyledForm"; 6 | 7 | const Register = () => { 8 | const dispatch = useDispatch(); 9 | const navigate = useNavigate(); 10 | const auth = useSelector((state) => state.auth); 11 | 12 | const [user, setUser] = useState({ 13 | name: "", 14 | email: "", 15 | password: "", 16 | }); 17 | 18 | useEffect(() => { 19 | if (auth._id) { 20 | navigate("/cart"); 21 | } 22 | }, [auth._id, navigate]); 23 | 24 | const handleSubmit = (e) => { 25 | e.preventDefault(); 26 | 27 | console.log(user); 28 | dispatch(registerUser(user)); 29 | }; 30 | 31 | return ( 32 | <> 33 | 34 |

Register

35 | setUser({ ...user, name: e.target.value })} 39 | /> 40 | setUser({ ...user, email: e.target.value })} 44 | /> 45 | setUser({ ...user, password: e.target.value })} 49 | /> 50 | 53 | {auth.registerStatus === "rejected" ? ( 54 |

{auth.registerError}

55 | ) : null} 56 |
57 | 58 | ); 59 | }; 60 | 61 | export default Register; 62 | -------------------------------------------------------------------------------- /frontend/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | OnlineShop 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /frontend/src/components/NavBar.jsx: -------------------------------------------------------------------------------- 1 | import { Link } from "react-router-dom"; 2 | import { useSelector, useDispatch } from "react-redux"; 3 | import styled from "styled-components"; 4 | import { logoutUser } from "../slices/authSlice"; 5 | import { toast } from "react-toastify"; 6 | 7 | const NavBar = () => { 8 | const dispatch = useDispatch(); 9 | const { cartTotalQuantity } = useSelector((state) => state.cart); 10 | const auth = useSelector((state) => state.auth); 11 | 12 | return ( 13 | 50 | ); 51 | }; 52 | 53 | export default NavBar; 54 | 55 | const AuthLinks = styled.div` 56 | a { 57 | &:last-child { 58 | margin-left: 2rem; 59 | } 60 | } 61 | `; 62 | 63 | const Logout = styled.div` 64 | color: white; 65 | cursor: pointer; 66 | `; 67 | -------------------------------------------------------------------------------- /frontend/README.md: -------------------------------------------------------------------------------- 1 | # Getting Started with Create React App 2 | 3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 4 | 5 | ## Available Scripts 6 | 7 | In the project directory, you can run: 8 | 9 | ### `npm start` 10 | 11 | Runs the app in the development mode.\ 12 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 13 | 14 | The page will reload if you make edits.\ 15 | You will also see any lint errors in the console. 16 | 17 | ### `npm test` 18 | 19 | Launches the test runner in the interactive watch mode.\ 20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 21 | 22 | ### `npm run build` 23 | 24 | Builds the app for production to the `build` folder.\ 25 | It correctly bundles React in production mode and optimizes the build for the best performance. 26 | 27 | The build is minified and the filenames include the hashes.\ 28 | Your app is ready to be deployed! 29 | 30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 31 | 32 | ### `npm run eject` 33 | 34 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 35 | 36 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 37 | 38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 39 | 40 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 41 | 42 | ## Learn More 43 | 44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 45 | 46 | To learn React, check out the [React documentation](https://reactjs.org/). 47 | 48 | ### Code Splitting 49 | 50 | This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) 51 | 52 | ### Analyzing the Bundle Size 53 | 54 | This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) 55 | 56 | ### Making a Progressive Web App 57 | 58 | This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) 59 | 60 | ### Advanced Configuration 61 | 62 | This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) 63 | 64 | ### Deployment 65 | 66 | This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) 67 | 68 | ### `npm run build` fails to minify 69 | 70 | This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) 71 | -------------------------------------------------------------------------------- /frontend/src/slices/cartSlice.js: -------------------------------------------------------------------------------- 1 | import { createSlice } from "@reduxjs/toolkit"; 2 | import { toast } from "react-toastify"; 3 | 4 | const initialState = { 5 | cartItems: localStorage.getItem("cartItems") 6 | ? JSON.parse(localStorage.getItem("cartItems")) 7 | : [], 8 | cartTotalQuantity: 0, 9 | cartTotalAmount: 0, 10 | }; 11 | 12 | const cartSlice = createSlice({ 13 | name: "cart", 14 | initialState, 15 | reducers: { 16 | addToCart(state, action) { 17 | const existingIndex = state.cartItems.findIndex( 18 | (item) => item.id === action.payload.id 19 | ); 20 | 21 | if (existingIndex >= 0) { 22 | state.cartItems[existingIndex] = { 23 | ...state.cartItems[existingIndex], 24 | cartQuantity: state.cartItems[existingIndex].cartQuantity + 1, 25 | }; 26 | toast.info("Increased product quantity", { 27 | position: "bottom-left", 28 | }); 29 | } else { 30 | let tempProductItem = { ...action.payload, cartQuantity: 1 }; 31 | state.cartItems.push(tempProductItem); 32 | toast.success("Product added to cart", { 33 | position: "bottom-left", 34 | }); 35 | } 36 | localStorage.setItem("cartItems", JSON.stringify(state.cartItems)); 37 | }, 38 | decreaseCart(state, action) { 39 | const itemIndex = state.cartItems.findIndex( 40 | (item) => item.id === action.payload.id 41 | ); 42 | 43 | if (state.cartItems[itemIndex].cartQuantity > 1) { 44 | state.cartItems[itemIndex].cartQuantity -= 1; 45 | 46 | toast.info("Decreased product quantity", { 47 | position: "bottom-left", 48 | }); 49 | } else if (state.cartItems[itemIndex].cartQuantity === 1) { 50 | const nextCartItems = state.cartItems.filter( 51 | (item) => item.id !== action.payload.id 52 | ); 53 | 54 | state.cartItems = nextCartItems; 55 | 56 | toast.error("Product removed from cart", { 57 | position: "bottom-left", 58 | }); 59 | } 60 | 61 | localStorage.setItem("cartItems", JSON.stringify(state.cartItems)); 62 | }, 63 | removeFromCart(state, action) { 64 | state.cartItems.map((cartItem) => { 65 | if (cartItem.id === action.payload.id) { 66 | const nextCartItems = state.cartItems.filter( 67 | (item) => item.id !== cartItem.id 68 | ); 69 | 70 | state.cartItems = nextCartItems; 71 | 72 | toast.error("Product removed from cart", { 73 | position: "bottom-left", 74 | }); 75 | } 76 | localStorage.setItem("cartItems", JSON.stringify(state.cartItems)); 77 | return state; 78 | }); 79 | }, 80 | getTotals(state, action) { 81 | let { total, quantity } = state.cartItems.reduce( 82 | (cartTotal, cartItem) => { 83 | const { price, cartQuantity } = cartItem; 84 | const itemTotal = price * cartQuantity; 85 | 86 | cartTotal.total += itemTotal; 87 | cartTotal.quantity += cartQuantity; 88 | 89 | return cartTotal; 90 | }, 91 | { 92 | total: 0, 93 | quantity: 0, 94 | } 95 | ); 96 | total = parseFloat(total.toFixed(2)); 97 | state.cartTotalQuantity = quantity; 98 | state.cartTotalAmount = total; 99 | }, 100 | clearCart(state, action) { 101 | state.cartItems = []; 102 | localStorage.setItem("cartItems", JSON.stringify(state.cartItems)); 103 | toast.error("Cart cleared", { position: "bottom-left" }); 104 | }, 105 | }, 106 | }); 107 | 108 | export const { addToCart, decreaseCart, removeFromCart, getTotals, clearCart } = 109 | cartSlice.actions; 110 | 111 | export default cartSlice.reducer; 112 | -------------------------------------------------------------------------------- /frontend/src/slices/authSlice.js: -------------------------------------------------------------------------------- 1 | import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"; 2 | import jwtDecode from "jwt-decode"; 3 | import axios from "axios"; 4 | import { url, setHeaders } from "./api"; 5 | 6 | const initialState = { 7 | token: localStorage.getItem("token"), 8 | name: "", 9 | email: "", 10 | _id: "", 11 | registerStatus: "", 12 | registerError: "", 13 | loginStatus: "", 14 | loginError: "", 15 | userLoaded: false, 16 | }; 17 | 18 | export const registerUser = createAsyncThunk( 19 | "auth/registerUser", 20 | async (values, { rejectWithValue }) => { 21 | try { 22 | const token = await axios.post(`${url}/register`, { 23 | name: values.name, 24 | email: values.email, 25 | password: values.password, 26 | }); 27 | 28 | localStorage.setItem("token", token.data); 29 | 30 | return token.data; 31 | } catch (error) { 32 | console.log(error.response.data); 33 | return rejectWithValue(error.response.data); 34 | } 35 | } 36 | ); 37 | 38 | export const loginUser = createAsyncThunk( 39 | "auth/loginUser", 40 | async (values, { rejectWithValue }) => { 41 | try { 42 | const token = await axios.post(`${url}/login`, { 43 | email: values.email, 44 | password: values.password, 45 | }); 46 | 47 | localStorage.setItem("token", token.data); 48 | return token.data; 49 | } catch (error) { 50 | console.log(error.response); 51 | return rejectWithValue(error.response.data); 52 | } 53 | } 54 | ); 55 | 56 | export const getUser = createAsyncThunk( 57 | "auth/getUser", 58 | async (id, { rejectWithValue }) => { 59 | try { 60 | const token = await axios.get(`${url}/user/${id}`, setHeaders()); 61 | 62 | localStorage.setItem("token", token.data); 63 | 64 | return token.data; 65 | } catch (error) { 66 | console.log(error.response); 67 | return rejectWithValue(error.response.data); 68 | } 69 | } 70 | ); 71 | 72 | const authSlice = createSlice({ 73 | name: "auth", 74 | initialState, 75 | reducers: { 76 | loadUser(state, action) { 77 | const token = state.token; 78 | 79 | if (token) { 80 | const user = jwtDecode(token); 81 | return { 82 | ...state, 83 | token, 84 | name: user.name, 85 | email: user.email, 86 | _id: user._id, 87 | userLoaded: true, 88 | }; 89 | } else return { ...state, userLoaded: true }; 90 | }, 91 | logoutUser(state, action) { 92 | localStorage.removeItem("token"); 93 | 94 | return { 95 | ...state, 96 | token: "", 97 | name: "", 98 | email: "", 99 | _id: "", 100 | registerStatus: "", 101 | registerError: "", 102 | loginStatus: "", 103 | loginError: "", 104 | }; 105 | }, 106 | }, 107 | extraReducers: (builder) => { 108 | builder.addCase(registerUser.pending, (state, action) => { 109 | return { ...state, registerStatus: "pending" }; 110 | }); 111 | builder.addCase(registerUser.fulfilled, (state, action) => { 112 | if (action.payload) { 113 | const user = jwtDecode(action.payload); 114 | return { 115 | ...state, 116 | token: action.payload, 117 | name: user.name, 118 | email: user.email, 119 | _id: user._id, 120 | registerStatus: "success", 121 | }; 122 | } else return state; 123 | }); 124 | builder.addCase(registerUser.rejected, (state, action) => { 125 | return { 126 | ...state, 127 | registerStatus: "rejected", 128 | registerError: action.payload, 129 | }; 130 | }); 131 | builder.addCase(loginUser.pending, (state, action) => { 132 | return { ...state, loginStatus: "pending" }; 133 | }); 134 | builder.addCase(loginUser.fulfilled, (state, action) => { 135 | if (action.payload) { 136 | const user = jwtDecode(action.payload); 137 | return { 138 | ...state, 139 | token: action.payload, 140 | name: user.name, 141 | email: user.email, 142 | _id: user._id, 143 | loginStatus: "success", 144 | }; 145 | } else return state; 146 | }); 147 | builder.addCase(loginUser.rejected, (state, action) => { 148 | return { 149 | ...state, 150 | loginStatus: "rejected", 151 | loginError: action.payload, 152 | }; 153 | }); 154 | builder.addCase(getUser.pending, (state, action) => { 155 | return { 156 | ...state, 157 | getUserStatus: "pending", 158 | }; 159 | }); 160 | builder.addCase(getUser.fulfilled, (state, action) => { 161 | if (action.payload) { 162 | const user = jwtDecode(action.payload); 163 | return { 164 | ...state, 165 | token: action.payload, 166 | name: user.name, 167 | email: user.email, 168 | _id: user._id, 169 | getUserStatus: "success", 170 | }; 171 | } else return state; 172 | }); 173 | builder.addCase(getUser.rejected, (state, action) => { 174 | return { 175 | ...state, 176 | getUserStatus: "rejected", 177 | getUserError: action.payload, 178 | }; 179 | }); 180 | }, 181 | }); 182 | 183 | export const { loadUser, logoutUser } = authSlice.actions; 184 | 185 | export default authSlice.reducer; 186 | -------------------------------------------------------------------------------- /frontend/src/components/Cart.jsx: -------------------------------------------------------------------------------- 1 | import { useEffect } from "react"; 2 | import { useNavigate } from "react-router-dom"; 3 | import { useDispatch, useSelector } from "react-redux"; 4 | import { 5 | addToCart, 6 | clearCart, 7 | decreaseCart, 8 | getTotals, 9 | removeFromCart, 10 | } from "../slices/cartSlice"; 11 | 12 | import { Link } from "react-router-dom"; 13 | 14 | const Cart = () => { 15 | const cart = useSelector((state) => state.cart); 16 | const auth = useSelector((state) => state.auth); 17 | 18 | const dispatch = useDispatch(); 19 | const navigate = useNavigate(); 20 | 21 | useEffect(() => { 22 | dispatch(getTotals()); 23 | }, [cart, dispatch]); 24 | 25 | const handleAddToCart = (product) => { 26 | dispatch(addToCart(product)); 27 | }; 28 | const handleDecreaseCart = (product) => { 29 | dispatch(decreaseCart(product)); 30 | }; 31 | const handleRemoveFromCart = (product) => { 32 | dispatch(removeFromCart(product)); 33 | }; 34 | const handleClearCart = () => { 35 | dispatch(clearCart()); 36 | }; 37 | return ( 38 |
39 |

Shopping Cart

40 | {cart.cartItems.length === 0 ? ( 41 |
42 |

Your cart is currently empty

43 |
44 | 45 | 53 | 57 | 58 | Start Shopping 59 | 60 |
61 |
62 | ) : ( 63 |
64 |
65 |

Product

66 |

Price

67 |

Quantity

68 |

Total

69 |
70 |
71 | {cart.cartItems && 72 | cart.cartItems.map((cartItem) => ( 73 |
74 |
75 | {cartItem.name} 76 |
77 |

{cartItem.name}

78 |

{cartItem.desc}

79 | 82 |
83 |
84 |
${cartItem.price}
85 |
86 | 89 |
{cartItem.cartQuantity}
90 | 91 |
92 |
93 | ${cartItem.price * cartItem.cartQuantity} 94 |
95 |
96 | ))} 97 |
98 |
99 | 102 |
103 |
104 | Subtotal 105 | ${cart.cartTotalAmount} 106 |
107 |

Taxes and shipping calculated at checkout

108 | {auth._id ? ( 109 | 110 | ) : ( 111 | 117 | )} 118 | 119 |
120 | 121 | 129 | 133 | 134 | Continue Shopping 135 | 136 |
137 |
138 |
139 |
140 | )} 141 |
142 | ); 143 | }; 144 | 145 | export default Cart; 146 | -------------------------------------------------------------------------------- /frontend/src/App.css: -------------------------------------------------------------------------------- 1 | @import url("https://fonts.googleapis.com/css2?family=Nunito:wght@200;400;700&display=swap"); 2 | 3 | * { 4 | padding: 0; 5 | margin: 0; 6 | box-sizing: border-box; 7 | font-family: "Nunito", sans-serif; 8 | } 9 | 10 | /* Not Found */ 11 | .not-found { 12 | display: flex; 13 | flex-direction: column; 14 | align-items: center; 15 | justify-content: center; 16 | color: rgb(68, 68, 68); 17 | min-height: 80vh; 18 | } 19 | .not-found h2 { 20 | font-size: 55px; 21 | } 22 | .not-found p { 23 | font-size: 20px; 24 | } 25 | 26 | /* NavBar */ 27 | 28 | .nav-bar { 29 | height: 70px; 30 | background: black; 31 | display: flex; 32 | justify-content: space-between; 33 | align-items: center; 34 | padding: 0 4rem; 35 | } 36 | .nav-bar a { 37 | text-decoration: none; 38 | color: white; 39 | } 40 | .nav-bar h2 { 41 | font-size: 40px; 42 | } 43 | .nav-bag { 44 | display: flex; 45 | align-items: center; 46 | } 47 | .bag-quantity { 48 | display: flex; 49 | align-items: center; 50 | justify-content: center; 51 | height: 25px; 52 | width: 25px; 53 | border-radius: 50%; 54 | background: yellow; 55 | font-size: 14px; 56 | font-weight: 700; 57 | color: black; 58 | margin-left: 5px; 59 | } 60 | 61 | /* Home */ 62 | 63 | .home-container { 64 | padding: 2rem 4rem; 65 | } 66 | .home-container h2 { 67 | font-size: 40px; 68 | font-weight: 400; 69 | text-align: center; 70 | } 71 | .products { 72 | display: flex; 73 | justify-content: space-between; 74 | flex-wrap: wrap; 75 | margin-top: 2rem; 76 | } 77 | .product { 78 | display: flex; 79 | flex-direction: column; 80 | justify-content: space-between; 81 | margin: 1rem auto; 82 | padding: 1rem; 83 | border-radius: 15px; 84 | width: 250px; 85 | max-width: 100%; 86 | height: 400px; 87 | box-shadow: -5px -5px 10px rgba(255, 255, 255, 0.5), 88 | 2px 2px 5px rgba(94, 104, 121, 0.3); 89 | } 90 | .product h3 { 91 | font-size: 25px; 92 | font-weight: 400; 93 | } 94 | .product img { 95 | width: 80%; 96 | margin-top: 1rem; 97 | margin-left: auto; 98 | margin-right: auto; 99 | } 100 | .product .details { 101 | display: flex; 102 | justify-content: space-between; 103 | align-items: center; 104 | } 105 | .product .details .price { 106 | font-size: 20px; 107 | font-weight: 700; 108 | } 109 | .product button { 110 | width: 100%; 111 | height: 40px; 112 | border-radius: 5px; 113 | margin-top: 2rem; 114 | font-weight: 400; 115 | letter-spacing: 1.15px; 116 | background-color: #4b70e2; 117 | color: #f9f9f9; 118 | border: none; 119 | outline: none; 120 | cursor: pointer; 121 | } 122 | 123 | /* Cart */ 124 | .cart-container { 125 | padding: 2rem 4rem; 126 | } 127 | .cart-container h2 { 128 | font-weight: 400; 129 | font-size: 30px; 130 | text-align: center; 131 | } 132 | .cart-container .titles { 133 | margin: 2rem 0 1rem 0; 134 | } 135 | .cart-container .titles h3 { 136 | font-size: 14px; 137 | font-weight: 400; 138 | text-transform: uppercase; 139 | } 140 | .cart-item, 141 | .cart-container .titles { 142 | display: grid; 143 | align-items: center; 144 | grid-template-columns: 3fr 1fr 1fr 1fr; 145 | column-gap: 0.5rem; 146 | } 147 | .cart-item { 148 | border-top: 1px solid rgb(187, 187, 187); 149 | padding: 1rem 0; 150 | } 151 | .cart-container .titles .product-title { 152 | padding-left: 0.5rem; 153 | } 154 | .cart-container .titles .total { 155 | padding-right: 0.5rem; 156 | justify-self: right; 157 | } 158 | .cart-item .cart-product { 159 | display: flex; 160 | } 161 | .cart-item .cart-product img { 162 | width: 100px; 163 | max-width: 100%; 164 | margin-right: 1rem; 165 | } 166 | .cart-item .cart-product h3 { 167 | font-weight: 400; 168 | } 169 | .cart-item .cart-product button { 170 | border: none; 171 | outline: none; 172 | margin-top: 0.7rem; 173 | cursor: pointer; 174 | background: none; 175 | color: gray; 176 | } 177 | .cart-item .cart-product button:hover { 178 | color: black; 179 | } 180 | 181 | .cart-item .cart-product-quantity { 182 | display: flex; 183 | align-items: flex-start; 184 | justify-content: center; 185 | width: 130px; 186 | max-width: 100%; 187 | border: 0.5px solid rgb(177, 177, 177); 188 | border-radius: 5px; 189 | } 190 | .cart-item .cart-product-quantity button { 191 | border: none; 192 | outline: none; 193 | background: none; 194 | padding: 0.7rem 1.5rem; 195 | cursor: pointer; 196 | } 197 | .cart-item .cart-product-quantity .count { 198 | padding: 0.7rem 0; 199 | } 200 | .cart-item .cart-product-total-price { 201 | padding-right: 0.5rem; 202 | justify-self: right; 203 | font-weight: 700; 204 | } 205 | 206 | /* cart summary */ 207 | .cart-summary { 208 | display: flex; 209 | justify-content: space-between; 210 | align-items: flex-start; 211 | border-top: 1px solid rgb(187, 187, 187); 212 | padding-top: 2rem; 213 | } 214 | .cart-summary .clear-btn { 215 | width: 130px; 216 | height: 40px; 217 | border-radius: 5px; 218 | font-weight: 400; 219 | letter-spacing: 1.15px; 220 | border: 0.5px solid rgb(177, 177, 177); 221 | color: gray; 222 | background: none; 223 | outline: none; 224 | cursor: pointer; 225 | } 226 | .cart-checkout { 227 | width: 270px; 228 | max-width: 100%; 229 | } 230 | .cart-checkout .subtotal { 231 | display: flex; 232 | justify-content: space-between; 233 | font-size: 20px; 234 | } 235 | .cart-checkout .amount { 236 | font-weight: 700; 237 | } 238 | .cart-checkout p { 239 | font-size: 14px; 240 | font-weight: 200; 241 | margin: 0.5rem 0; 242 | } 243 | .cart-checkout button { 244 | width: 100%; 245 | height: 40px; 246 | border-radius: 5px; 247 | font-weight: 400; 248 | letter-spacing: 1.15px; 249 | background-color: #4b70e2; 250 | color: #f9f9f9; 251 | border: none; 252 | outline: none; 253 | cursor: pointer; 254 | } 255 | 256 | .cart-checkout .cart-login { 257 | background-color: yellow; 258 | color: black; 259 | } 260 | 261 | .continue-shopping, 262 | .start-shopping { 263 | margin-top: 1rem; 264 | } 265 | .continue-shopping a, 266 | .start-shopping a { 267 | color: gray; 268 | text-decoration: none; 269 | display: flex; 270 | align-items: center; 271 | } 272 | .continue-shopping a span, 273 | .start-shopping a span { 274 | margin-left: 0.5rem; 275 | } 276 | .cart-empty { 277 | font-size: 20px; 278 | margin-top: 2rem; 279 | color: rgb(84, 84, 84); 280 | display: flex; 281 | flex-direction: column; 282 | align-items: center; 283 | } 284 | 285 | /* Responsive */ 286 | 287 | @media (max-width: 665px) { 288 | /* NavBar */ 289 | .nav-bar { 290 | padding: 0 1rem; 291 | } 292 | .nav-bar h2 { 293 | font-size: 30px; 294 | } 295 | 296 | /* Cart */ 297 | .cart-container { 298 | padding: 2rem; 299 | } 300 | .cart-container .titles { 301 | display: none; 302 | } 303 | .cart-item, 304 | .cart-container .titles { 305 | grid-template-columns: 1fr; 306 | row-gap: 1rem; 307 | } 308 | .cart-item .cart-product-total-price { 309 | justify-self: left; 310 | } 311 | .cart-summary { 312 | flex-direction: column; 313 | } 314 | .cart-summary .clear-btn { 315 | margin-bottom: 2rem; 316 | } 317 | } 318 | --------------------------------------------------------------------------------