-
Notifications
You must be signed in to change notification settings - Fork 402
Added authentication requirement for cart and wishlist functionality #2631
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Added authentication requirement for cart and wishlist functionality #2631
Conversation
Someone is attempting to deploy a commit to the Vivek Prajapati's projects Team on Vercel. A member of the Team first needs to authorize it. |
WalkthroughAdds authentication gating to product interactions. ProductGrid and ProductCard now check AuthContext.isLoggedIn before Buy Now, Add to Cart, and Wishlist actions, showing toasts/alerts and navigating to /auth if unauthenticated. AuthContext gains isLoggedIn, user data, and logout. README typo corrected. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant U as User
participant UI as Product UI (Grid/Card)
participant AC as AuthContext
participant R as Router
participant T as Toast/Alert
participant S as Action Handler (Cart/Wishlist/Checkout)
rect rgb(245,248,255)
U->>UI: Click action (Buy/Add/Wishlist)
UI->>AC: Check isLoggedIn
alt Not logged in
AC-->>UI: isLoggedIn = false
UI->>T: Show "Please login..." message
UI->>R: navigate('/auth')
else Logged in
AC-->>UI: isLoggedIn = true
UI->>S: Perform action
S-->>UI: Result
UI->>T: Show success/failure
end
end
sequenceDiagram
autonumber
participant App as App
participant AC as AuthContext
participant Admin as Admin Login
participant User as User Login
Note over AC: Initial: isAdmin=false, isLoggedIn=false, user=null
Admin->>AC: loginAsAdmin()
AC-->>App: isAdmin=true, isLoggedIn=true, user=null
User->>AC: loginAsUser(userData)
AC-->>App: isAdmin=false, isLoggedIn=true, user=userData
App->>AC: logout()
AC-->>App: isAdmin=false, isLoggedIn=false, user=null
Estimated code review effortπ― 3 (Moderate) | β±οΈ ~20 minutes Poem
Tip π Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. β¨ Finishing Touches
π§ͺ Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. πͺ§ TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 5
Caution
Some comments are outside the diff and canβt be posted inline due to platform limitations.
β οΈ Outside diff range comments (1)
src/User/components/Popular_Categories/ProductGrid.jsx (1)
150-159
: βBuy Nowβ is disabled when item is already in cart β users canβt proceed to checkout.Let users buy even if the item is already in the cart. Gate login, add if missing, then navigate.
Apply:
- <button - onClick={() => { - onAddToCart(product); // First, add the product to the cart - handleBuyNow(); // Then, navigate to the payment page - }} - className="mt-1 bg-orange-600 text-white px-4 py-2 rounded text-sm w-full hover:bg-orange-700 transition-colors disabled:opacity-45 disabled:pointer-events-none" - disabled={cartItems.find((item) => item.id === product.id)}> - {cartItems.find((item) => item.id === product.id) - ? "β‘Buy Now" - : "β‘Buy Now"} - </button> + <button + onClick={() => { + if (!isLoggedIn) { + toast.error("Please login to buy products!"); + navigate("/auth"); + return; + } + if (!cartItems.find((item) => item.id === product.id)) { + onAddToCart(product); + } + navigate("/checkout"); + }} + className="mt-1 bg-orange-600 text-white px-4 py-2 rounded text-sm w-full hover:bg-orange-700 transition-colors"> + β‘Buy Now + </button>
π§Ή Nitpick comments (7)
src/context/AuthContext.jsx (2)
28-35
: Consider memoizing provider value.Prevents avoidable re-renders downstream.
Example:
- return ( - <AuthContext.Provider value={{ - isAdmin, - isLoggedIn, - user, - loginAsAdmin, - loginAsUser, - logout - }}> + const value = React.useMemo(() => ({ + isAdmin, isLoggedIn, user, loginAsAdmin, loginAsUser, logout + }), [isAdmin, isLoggedIn, user]); + return ( + <AuthContext.Provider value={value}> {children} </AuthContext.Provider> );
1-1
: Optional: provide a non-null default context shape.Helps DX when
useAuth
is accidentally used outside the provider.-const AuthContext = createContext(); +const AuthContext = createContext({ + isAdmin: false, + isLoggedIn: false, + user: null, + loginAsAdmin: () => {}, + loginAsUser: () => {}, + logout: () => {}, +});src/User/components/ProductCard/ProductCard.jsx (1)
3-5
: Unify notifications (toast vs alert).Other components use react-hot-toast; align here for consistency.
If you wire Redux in this card, also import and dispatch
manageCartItem
like in ProductGrid.src/User/components/Popular_Categories/ProductGrid.jsx (4)
8-10
: Remove unused import.
PaymentPage
is never used.-import PaymentPage from "../../pages/Payment/Payment"; import { useAuth } from "../../../context/AuthContext";
47-54
: Inline buy-now guard or remove this function.After refactoring the button onClick (see below), this helper becomes redundant.
Apply:
- const handleBuyNow = () => { - if (!isLoggedIn) { - toast.error("Please login to buy products!"); - navigate("/auth"); - return; - } - navigate(`/checkout`); - }; + // handleBuyNow inlined in the button onClick
69-72
: Consider moving wishlist login checks intoonAddToWishlist
.Reduces duplication at call sites.
23-29
: Avoid mutating product objects when derivingnewPrice
.Compute inline or create a shallow copy to keep data flow predictable.
Example:
const newPrice = getNewPrice(product.discountPercentage, product.price);
π Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
π‘ Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
π Files selected for processing (4)
README.md
(1 hunks)src/User/components/Popular_Categories/ProductGrid.jsx
(5 hunks)src/User/components/ProductCard/ProductCard.jsx
(2 hunks)src/context/AuthContext.jsx
(1 hunks)
π§° Additional context used
𧬠Code graph analysis (3)
src/User/components/Popular_Categories/ProductGrid.jsx (4)
src/context/AuthContext.jsx (3)
useAuth
(41-41)useAuth
(41-41)isLoggedIn
(7-7)src/User/components/Navbar/UserNavbar.jsx (2)
isLoggedIn
(22-22)navigate
(17-17)src/App.jsx (1)
App
(88-274)src/User/pages/UserAuth/UserAuth.jsx (1)
e
(44-95)
src/User/components/ProductCard/ProductCard.jsx (3)
src/User/components/Products/ProductDetails.jsx (1)
dispatch
(113-157)src/User/pages/Dashboard/dashboard-cart.jsx (2)
navigate
(164-271)div
(23-69)src/User/components/Buttons/AddToCart.jsx (1)
AddToCart
(3-9)
src/context/AuthContext.jsx (4)
src/User/pages/UserAuth/UserAuth.jsx (2)
e
(44-95)provider
(146-176)src/User/components/Navbar/AuthButton.jsx (1)
isLoggedIn
(6-25)src/User/components/Buttons/Logout.jsx (1)
Logout
(4-32)src/PrivateRoute.jsx (1)
isLoggedIn
(4-7)
π Additional comments (6)
README.md (1)
94-94
: Typo fix looks good.Grammatical correction improves clarity; no further changes needed.
src/User/components/Popular_Categories/ProductGrid.jsx (5)
39-39
: Auth source-of-truth mismatch risk.Youβre using
useAuth().isLoggedIn
here, while many components still readlocalStorage.isLoggedIn
. Until AuthContext persists/initializes from storage (see AuthContext comment), guards may behave inconsistently post-login.Would you prefer updating AuthContext (recommended) or temporarily falling back to
const isLoggedIn = authIsLoggedIn || localStorage.getItem("isLoggedIn")==="true"
?
58-66
: Cart guard LGTM, but ensure Redux add is the only side effect.Toast + dispatch order is fine. No changes required.
81-86
: Wishlist guard (remove path) LGTM.Properly blocks unauthenticated removal and redirects.
95-99
: Wishlist guard (add path) LGTM.Consistent messaging and flow.
1-166
: Server-side enforcement reminder.Client-side guards are necessary UX but not sufficient security. Ensure the API for cart/wishlist also rejects unauthenticated requests.
const [isLoggedIn, setIsLoggedIn] = useState(false); | ||
const [user, setUser] = useState(null); | ||
|
||
const loginAsAdmin = () => setIsAdmin(true); | ||
const loginAsUser = () => setIsAdmin(false); | ||
const loginAsAdmin = () => { | ||
setIsAdmin(true); | ||
setIsLoggedIn(true); | ||
}; | ||
|
||
const loginAsUser = (userData = null) => { | ||
setIsAdmin(false); | ||
setIsLoggedIn(true); | ||
setUser(userData); | ||
}; | ||
|
||
const logout = () => { | ||
setIsAdmin(false); | ||
setIsLoggedIn(false); | ||
setUser(null); | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
π‘ Verification agent
π§© Analysis chain
Verify end-to-end: Is loginAsUser
or loginAsAdmin
called anywhere?
Current login screens set localStorage directly and donβt invoke these helpers, leaving context stale during the session.
Run:
π Script executed:
#!/bin/bash
set -euo pipefail
echo "Calls to login helpers (outside context file):"
rg -nP 'loginAs(User|Admin)\s*\(' -g '!src/context/AuthContext.jsx' -C2 || true
echo
echo "Direct localStorage isLoggedIn usage:"
rg -nP "localStorage\\.getItem\\(['\"]isLoggedIn['\"]\\)" -n -C2
Length of output: 1975
π Script executed:
#!/usr/bin/env bash
set -euo pipefail
echo "Locations with localStorage.setItem:"
rg -nP 'localStorage\.setItem\(' -n -C2
Length of output: 6264
Login helpers are unused and context remains stale
The loginAsUser
and loginAsAdmin
functions in src/context/AuthContext.jsx
are never invokedβevery authentication flow writes directly to localStorage
instead (e.g. in UserAuth.jsx
, Admin.jsx
, Dashboard.jsx
, etc.). As a result, your contextβs isLoggedIn
, isAdmin
, and user
states never update during a session, leading to stale or inconsistent UI state.
Please address by:
- Refactoring your login flows (in
src/User/pages/UserAuth/UserAuth.jsx
,src/User/pages/AdditionalDetails.jsx
,src/User/pages/Admin-Verification/Admin.jsx
,src/User/pages/Dashboard/Dashboard.jsx
, etc.) to call the corresponding context helpers (loginAsUser
,loginAsAdmin
) instead of writing directly tolocalStorage
. - Ensuring those helpers also persist the session to
localStorage
(e.g. insideloginAsUser
, calllocalStorage.setItem("isLoggedIn", "true")
,localStorage.setItem("username", userData.username)
, etc.) so that both context and storage remain in sync. - Optionally removing redundant direct
localStorage.setItem
calls once all flows use the context API.
This change is necessary to guarantee that the React Context accurately reflects authentication state across your app.
π€ Prompt for AI Agents
In src/context/AuthContext.jsx around lines 7 to 25, the loginAsUser and
loginAsAdmin helpers are never called so context state stays stale; update these
helpers to both update context state (setIsAdmin, setIsLoggedIn, setUser) and
persist the same values to localStorage (e.g., set isLoggedIn, isAdmin, and user
fields such as username) so context and storage stay in sync, then refactor the
authentication flows (UserAuth.jsx, AdditionalDetails.jsx, Admin.jsx,
Dashboard.jsx, etc.) to call loginAsUser(userData) or loginAsAdmin() instead of
writing directly to localStorage (and remove redundant localStorage.setItem
calls in those files once they use the context API).
const [isLoggedIn, setIsLoggedIn] = useState(false); | ||
const [user, setUser] = useState(null); | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Auth state isnβt persisted or initialized from storage; will desync with existing login flow.
Login code elsewhere writes to localStorage, but AuthContext never reads it. After a successful login, isLoggedIn
in context remains false
, breaking the new guards.
Apply this diff to initialize from storage on mount:
-const AuthContext = createContext();
+const AuthContext = createContext();
@@
-export const AuthProvider = ({ children }) => {
+export const AuthProvider = ({ children }) => {
const [isAdmin, setIsAdmin] = useState(false);
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [user, setUser] = useState(null);
+ React.useEffect(() => {
+ try {
+ const storedLoggedIn = localStorage.getItem("isLoggedIn") === "true";
+ const storedUser = localStorage.getItem("user");
+ const storedAdminRole = localStorage.getItem("adminRole");
+ if (storedLoggedIn) {
+ setIsLoggedIn(true);
+ setUser(storedUser ? JSON.parse(storedUser) : null);
+ }
+ if (storedAdminRole != null) {
+ setIsAdmin(storedAdminRole === "1" || storedAdminRole === "true");
+ }
+ } catch {
+ /* no-op */
+ }
+ }, []);
Also update the import to include useEffect
:
-import React, { createContext, useState, useContext } from 'react';
+import React, { createContext, useState, useContext, useEffect } from 'react';
π€ Prompt for AI Agents
In src/context/AuthContext.jsx around lines 7 to 9, the AuthContext initial
state is not hydrated from localStorage so it stays false after an existing
login; import useEffect and on component mount read stored auth (e.g.
localStorage.getItem('auth') or specific keys like 'isLoggedIn'/'user'), parse
safely, then call setIsLoggedIn and setUser to initialize the context values;
also fall back to defaults if nothing is stored and ensure you handle JSON.parse
errors gracefully (try/catch) so the app doesn't crash.
const loginAsAdmin = () => { | ||
setIsAdmin(true); | ||
setIsLoggedIn(true); | ||
}; | ||
|
||
const loginAsUser = (userData = null) => { | ||
setIsAdmin(false); | ||
setIsLoggedIn(true); | ||
setUser(userData); | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
π οΈ Refactor suggestion
Login helpers donβt sync storage; context and consumers using localStorage will diverge.
Ensure loginAsAdmin
/loginAsUser
update localStorage so Navbar, PrivateRoute, etc., stay consistent.
Apply:
const loginAsAdmin = () => {
setIsAdmin(true);
setIsLoggedIn(true);
+ try {
+ localStorage.setItem("isLoggedIn", "true");
+ localStorage.setItem("adminRole", "1");
+ } catch {}
};
@@
const loginAsUser = (userData = null) => {
setIsAdmin(false);
setIsLoggedIn(true);
setUser(userData);
+ try {
+ localStorage.setItem("isLoggedIn", "true");
+ localStorage.setItem("user", JSON.stringify(userData));
+ localStorage.removeItem("adminRole");
+ } catch {}
};
π Committable suggestion
βΌοΈ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const loginAsAdmin = () => { | |
setIsAdmin(true); | |
setIsLoggedIn(true); | |
}; | |
const loginAsUser = (userData = null) => { | |
setIsAdmin(false); | |
setIsLoggedIn(true); | |
setUser(userData); | |
}; | |
const loginAsAdmin = () => { | |
setIsAdmin(true); | |
setIsLoggedIn(true); | |
try { | |
localStorage.setItem("isLoggedIn", "true"); | |
localStorage.setItem("adminRole", "1"); | |
} catch {} | |
}; | |
const loginAsUser = (userData = null) => { | |
setIsAdmin(false); | |
setIsLoggedIn(true); | |
setUser(userData); | |
try { | |
localStorage.setItem("isLoggedIn", "true"); | |
localStorage.setItem("user", JSON.stringify(userData)); | |
localStorage.removeItem("adminRole"); | |
} catch {} | |
}; |
const logout = () => { | ||
setIsAdmin(false); | ||
setIsLoggedIn(false); | ||
setUser(null); | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Logout doesnβt clear storage.
Components that read from localStorage will still think the user is logged in.
Apply:
const logout = () => {
setIsAdmin(false);
setIsLoggedIn(false);
setUser(null);
+ try {
+ localStorage.removeItem("isLoggedIn");
+ localStorage.removeItem("user");
+ localStorage.removeItem("adminRole");
+ } catch {}
};
π Committable suggestion
βΌοΈ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const logout = () => { | |
setIsAdmin(false); | |
setIsLoggedIn(false); | |
setUser(null); | |
}; | |
const logout = () => { | |
setIsAdmin(false); | |
setIsLoggedIn(false); | |
setUser(null); | |
try { | |
localStorage.removeItem("isLoggedIn"); | |
localStorage.removeItem("user"); | |
localStorage.removeItem("adminRole"); | |
} catch {} | |
}; |
π€ Prompt for AI Agents
In src/context/AuthContext.jsx around lines 21 to 25, the logout function only
updates React state but does not clear persisted auth data, so other components
reading localStorage will still think the user is logged in; update logout to
also remove or clear the auth-related keys from storage (removeItem for keys you
persist such as "isAdmin", "isLoggedIn", "user" and any auth token like "token"
or "authToken"), and if you support sessionStorage remove them there too; keep
the state resets as-is after clearing storage so UI and persisted state stay in
sync.
const handleAddToCart = () => { | ||
if (!isLoggedIn) { | ||
alert("Please login to add items to your cart!"); | ||
navigate("/auth"); | ||
return; | ||
} | ||
|
||
// Add to cart logic here | ||
alert(`${title} added to cart!`); | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
βAdd to Bagβ shows success without adding anything.
This misleads users and tests. Either wire Redux add-to-cart or remove the success message until implemented.
Minimal fix to avoid false positives and align UX with ProductGrid toasts:
-import { useAuth } from "../../../context/AuthContext";
+import { useAuth } from "../../../context/AuthContext";
+import toast from "react-hot-toast";
@@
- const handleAddToCart = () => {
- if (!isLoggedIn) {
- alert("Please login to add items to your cart!");
- navigate("/auth");
- return;
- }
-
- // Add to cart logic here
- alert(`${title} added to cart!`);
- };
+ const handleAddToCart = () => {
+ if (!isLoggedIn) {
+ toast.error("Please login to add items to your cart!");
+ navigate("/auth");
+ return;
+ }
+ // TODO: Wire up actual add-to-cart logic (e.g., dispatch manageCartItem).
+ };
π Committable suggestion
βΌοΈ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const handleAddToCart = () => { | |
if (!isLoggedIn) { | |
alert("Please login to add items to your cart!"); | |
navigate("/auth"); | |
return; | |
} | |
// Add to cart logic here | |
alert(`${title} added to cart!`); | |
}; | |
// at the top of the file, alongside your other imports | |
import { useAuth } from "../../../context/AuthContext"; | |
import toast from "react-hot-toast"; | |
// β¦ | |
const handleAddToCart = () => { | |
if (!isLoggedIn) { | |
toast.error("Please login to add items to your cart!"); | |
navigate("/auth"); | |
return; | |
} | |
// TODO: Wire up actual add-to-cart logic (e.g., dispatch manageCartItem). | |
}; |
π€ Prompt for AI Agents
In src/User/components/ProductCard/ProductCard.jsx around lines 10 to 19, the
handler currently shows a success alert without actually adding the product to
the cart; either wire the Redux add-to-cart action or remove the misleading
success message. Replace the placeholder success alert with a dispatch to the
existing Redux addToCart (or addCartItem) action passing the product
id/quantity/details and then show the same toast used by ProductGrid on
successful dispatch (or handle errors and show an error toast); if Redux wiring
is not ready, remove the success alert entirely (or replace it with a
non-committal "feature coming soon" toast) so the UI no longer reports success
when nothing was added.
Kindly mention your Issue number and at this time we don't want to authenticate user in these pages ... when they will be in their checkout page then there login will required only |
π Authentication Enhancement
Changes Made:
β Users must login before adding items to cart
β Users must login before adding items to wishlist
β Enhanced AuthContext with proper user state management
β Added proper error messages and redirects to login page
β Fixed navigation paths to correct auth route
Testing:
Fixes the security issue where users could add items without authentication.
Summary by CodeRabbit
New Features
Documentation