0% found this document useful (0 votes)
45 views9 pages

Authentication & Authorization 3

Authentication & authorization 3 in react

Uploaded by

Marada Prudhvi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views9 pages

Authentication & Authorization 3

Authentication & authorization 3 in react

Uploaded by

Marada Prudhvi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 9

Router Switch

Switch can have any React Component inside it

Route
User defined Component
Redirect
2. Wrapper Component
Redirection Logic can be reused by separating out into a React Component called
Wrapper Component.
Each route will be wrapped with it.

2.1 Protected Route


ProtectedRoute is the Wrapper Component which returns Home Route Component.

File: src/components/ProtectedRoute/index.js

import { Route, Redirect } from "react-router-dom";


import Cookies from "js-cookie";

const ProtectedRoute = (props) => {


const token = Cookies.get("jwt_token");
if (token === undefined) {
return <Redirect to="/login" />;
}
return <Route {...props} />;
};

export default ProtectedRoute;


___________________________________________________________________________________
_______________________________

3. E-Commerce Application

File: src/App.js

import { BrowserRouter, Route, Switch, Redirect } from "react-router-dom";

import LoginForm from "./components/LoginForm";


import Home from "./components/Home";
import Products from "./components/Products";
import Cart from "./components/Cart";
import NotFound from "./components/NotFound";
import ProtectedRoute from "./components/ProtectedRoute";

import "./App.css";

const App = () => (


<BrowserRouter>
<Switch>
<Route exact path="/login" component={LoginForm} />
<ProtectedRoute exact path="/" component={Home} />
<ProtectedRoute exact path="/products" component={Products} />
<ProtectedRoute exact path="/cart" component={Cart} />
<Route path="/not-found" component={NotFound} />
<Redirect to="not-found" />
</Switch>
</BrowserRouter>
);
export default App;

###################################################################################
#################
File: src/components/AllProductsSection/index.js

import { Component } from "react";


import Cookies from "js-cookie";

import ProductCard from "../ProductCard";


import "./index.css";

class AllProductsSection extends Component {


state = {
productsList: [],
};

componentDidMount() {
this.getProducts();
}

getProducts = async () => {


const apiUrl = "https://apis.ccbp.in/products";
const jwtToken = Cookies.get("jwt_token");
const options = {
headers: {
Authorization: `Bearer ${jwtToken}`,
},
method: "GET",
};
const response = await fetch(apiUrl, options);
if (response.ok === true) {
const fetchedData = await response.json();
const updatedData = fetchedData.products.map((product) => ({
title: product.title,
brand: product.brand,
price: product.price,
id: product.id,
imageUrl: product.image_url,
rating: product.rating,
}));
this.setState({
productsList: updatedData,
});
}
};

renderProductsList = () => {
const { productsList } = this.state;
return (
<div>
<h1 className="products-list-heading">All Products</h1>
<ul className="products-list">
{productsList.map((product) => (
<ProductCard productData={product} key={product.id} />
))}
</ul>
</div>
);
};

render() {
return <>{this.renderProductsList()}</>;
}
}

export default AllProductsSection;


###################################################################################
##################
File: src/components/Cart/index.js

import Header from "../Header";


import "./index.css";

const Cart = () => (


<>
<Header />
<div className="cart-container">
<img
src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-cart-img.png"
alt="cart"
className="cart-img"
/>
</div>
</>
);

export default Cart;


###################################################################################
###################

File: src/components/Header/index.js

import { Link, withRouter } from "react-router-dom";

import Cookie from "js-cookie";

import "./index.css";

const Header = (props) => {


const onClickLogout = () => {
Cookie.remove("jwt_token");
const { history } = props;
history.replace("/login");
};
return (
<nav className="nav-header">
<div className="nav-content">
<img
className="website-logo"
src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-logo-img.png"
alt="website logo"
/>
<ul className="nav-menu">
<Link to="/" className="nav-link">
<li>Home</li>
</Link>
<Link to="/products" className="nav-link">
<li>Products</li>
</Link>
<Link to="/cart" className="nav-link">
<li>Cart</li>
</Link>
</ul>
<button
type="button"
className="logout-desktop-btn"
onClick={onClickLogout}
>
Logout
</button>
<button
type="button"
className="logout-mobile-btn"
onClick={onClickLogout}
>
<img
src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-log-out-
img.png"
alt="logout icon"
className="logout-icon"
/>
</button>
</div>
</nav>
);
};
export default withRouter(Header);
###################################################################################
###################

File: src/components/Home/index.js

import Header from "../Header";


import "./index.css";

const Home = () => (


<>
<Header />
<div className="home-container">
<div className="home-content">
<h1 className="home-heading">Clothes That Get YOU Noticed</h1>
<img
src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-home-img.png"
alt="dresses to be noticed"
className="home-mobile-img"
/>
<p className="home-description">
Fashion is part of the daily air and it does not quite help that it
changes all the time. Clothes have always been a marker of the era and
we are in a revolution. Your fashion makes you been seen and heard
that way you are. So, celebrate the seasons new and exciting fashion
in your own way.
</p>
<button type="button" className="shop-now-button">
Shop Now
</button>
</div>
<img
src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-home-img.png"
alt="dresses to be noticed"
className="home-desktop-img"
/>
</div>
</>
);

export default Home;


###################################################################################
#################

File: src/components/LoginForm/index.js

import { Component } from "react";


import Cookies from "js-cookie";
import { Redirect } from "react-router-dom";

import "./index.css";

class LoginForm extends Component {


state = {
username: "",
password: "",
showSubmitError: false,
errorMsg: "",
};

onChangeUsername = (event) => {


this.setState({ username: event.target.value });
};

onChangePassword = (event) => {


this.setState({ password: event.target.value });
};

onSubmitSuccess = (jwtTkoken) => {


const { history } = this.props;

Cookies.set("jwt_token", jwtTkoken, {
expires: 30,
path: "/",
});
history.replace("/");
};

onSubmitFailure = (errorMsg) => {


console.log(errorMsg);
this.setState({ showSubmitError: true, errorMsg });
};

submitForm = async (event) => {


event.preventDefault();
const { username, password } = this.state;
const userDetails = { username, password };
const url = "https://apis.ccbp.in/login";
const options = {
method: "POST",
body: JSON.stringify(userDetails),
};
const response = await fetch(url, options);
const data = await response.json();
if (response.ok === true) {
this.onSubmitSuccess(data.jwt_token);
} else {
this.onSubmitFailure(data.error_msg);
}
};

renderPasswordField = () => {
const { password } = this.state;
return (
<>
<label className="input-label" htmlFor="password">
PASSWORD
</label>
<input
type="password"
id="password"
className="password-input-filed"
value={password}
onChange={this.onChangePassword}
/>
</>
);
};

renderUsernameField = () => {
const { username } = this.state;
return (
<>
<label className="input-label" htmlFor="username">
USERNAME
</label>
<input
type="text"
id="username"
className="username-input-filed"
value={username}
onChange={this.onChangeUsername}
/>
</>
);
};

render() {
const { showSubmitError, errorMsg } = this.state;
const jwtToken = Cookies.get("jwt_token");
if (jwtToken !== undefined) {
return <Redirect to="/" />;
}
return (
<div className="login-form-container">
<img
src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-logo-img.png"
className="login-website-logo-mobile-image"
alt="website logo"
/>
<img
src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-login-img.png"
className="login-image"
alt="website login"
/>
<form className="form-container" onSubmit={this.submitForm}>
<img
src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-logo-img.png"
className="login-website-logo-desktop-image"
alt="website logo"
/>
<div className="input-container">{this.renderUsernameField()}</div>
<div className="input-container">{this.renderPasswordField()}</div>
<button type="submit" className="login-button">
Login
</button>
{showSubmitError && <p className="error-message">*{errorMsg}</p>}
</form>
</div>
);
}
}

export default LoginForm;


###################################################################################
######################

File: src/components/NotFound/index.js

import "./index.css";

const NotFound = () => (


<div className="not-found-container">
<img
src="https://assets.ccbp.in/frontend/react-js/not-found-blog-img.png"
alt="not-found"
className="not-found-img"
/>
</div>
);

export default NotFound;


###################################################################################
########################

File: src/components/ProductCard/index.js
import "./index.css";

const ProductCard = (props) => {


const { productData } = props;
const { title, brand, imageUrl, rating, price } = productData;

return (
<li className="product-item">
<img src={imageUrl} alt="product" className="thumbnail" />
<h1 className="title">{title}</h1>
<p className="brand">by {brand}</p>
<div className="product-details">
<p className="price">Rs {price}/-</p>
<div className="rating-container">
<p className="rating">{rating}</p>
<img
src="https://assets.ccbp.in/frontend/react-js/star-img.png"
alt="star"
className="star"
/>
</div>
</div>
</li>
);
};
export default ProductCard;
###################################################################################
##########################

File: src/components/Products/index.js

import AllProductsSection from "../AllProductsSection";

import Header from "../Header";

import "./index.css";

const Products = () => (


<>
<Header />
<div className="product-sections">
<AllProductsSection />
</div>
</>
);

export default Products;


###################################################################################
########################

File: src/components/ProtectedRoute/index.js

import { Route, Redirect } from "react-router-dom";


import Cookies from "js-cookie";
const ProtectedRoute = (props) => {
const token = Cookies.get("jwt_token");
if (token === undefined) {
return <Redirect to="/login" />;
}
return <Route {...props} />;
};

export default ProtectedRoute;


###################################################################################
######################

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy