Skip to content
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

feat: Added a Page to be shown in case of no authorization/not found #113

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

imrehankhan
Copy link

@imrehankhan imrehankhan commented Jan 10, 2025

Solved isssue #56

Changes made
1. Error Page Component:
• Created a reusable ErrorPage component that displays a user-friendly error message.
• Added a “Go to the Dashboard” button to redirect users to the UpdatesPage.
• Added PropTypes validation for the message prop.
• Enhanced accessibility by adding role="alert" and aria-live="polite" attributes.
• Moved inline styles to use Material-UI's styling solution using @emotion/styled.
2. Routing Logic:
• Updated App.js to handle routing based on the isAuthenticated state:
• Authenticated users are shown an error page (ErrorPage) for undefined routes.
• Unauthenticated users are also redirected to the same error page for restricted or invalid routes.

How to Test
1. Log in to the application, by setting "isAuthenticated" value to "true" in AuthContext.js file, located in src/Context/AuthContext.js:
• Navigate to an undefined route, e.g., /random-page.
• Verify that the error page is displayed and the “Go to the Dashboard” button redirects to /updatesPage.
• Navigate to a defined route, e.g., /dashboard
• Verify that the error page is not displayed.
3. Without logging in (when isAuthenticated value is set to false):
• Navigate to any restricted or invalid route, e.g., /dashboard.
• Confirm that the error page is displayed.

Components Added
• ErrorPage.js: Located under the components/ErrorPage

Screenshot 2025-01-10 at 6 49 02 PM
Screen.Recording.2025-01-10.at.7.15.46.PM.mov

Copy link

coderabbitai bot commented Jan 10, 2025

Walkthrough

The pull request modifies the BlueWave HRM application by updating dependencies in package.json and implementing routing functionality using react-router-dom. The App component is restructured to support routing, including a new PrivateRoute for authenticated access to the dashboard and an ErrorPage for handling navigation errors. Additionally, a new authentication context is created to manage user authentication state.

Changes

File Change Summary
package.json Updated @emotion/react and @emotion/styled to ^11.14.0, updated @mui/material to ^5.16.14, added react-router-dom@^6.22.1
src/App.js Implemented routing with Router, Routes, and Route components
Added AuthProvider for authentication context
Introduced PrivateRoute for protected routes and ErrorPage for error handling
src/components/ErrorPage/ErrorPage.js Created new ErrorPage component with customizable error messages and styling
src/components/PrivateRoute.js Created new PrivateRoute component to manage access based on authentication status
src/context/AuthContext.js Created new AuthContext and AuthProvider for managing authentication state

Sequence Diagram

sequenceDiagram
    participant User
    participant Router
    participant App
    participant UpdatesPage
    participant ErrorPage

    User->>Router: Navigate to route
    Router->>App: Check authentication
    alt User is authenticated
        App->>UpdatesPage: Render dashboard
    else User is not authenticated
        App->>ErrorPage: Redirect to error page
        ErrorPage-->>User: Display error message
    end
Loading

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5cce127 and d5d5df5.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • package.json (2 hunks)
  • src/App.js (1 hunks)
  • src/components/ErrorPage/ErrorPage.js (1 hunks)

src/App.js Outdated Show resolved Hide resolved
src/App.js Outdated Show resolved Hide resolved
src/App.js Outdated Show resolved Hide resolved
src/components/ErrorPage/ErrorPage.js Outdated Show resolved Hide resolved
src/components/ErrorPage/ErrorPage.js Outdated Show resolved Hide resolved
package.json Outdated Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

♻️ Duplicate comments (1)
src/App.js (1)

13-13: ⚠️ Potential issue

Inconsistent routing behaviour between root and dashboard

The root path still allows access without authentication while dashboard requires it. This could lead to security issues.

-<Route path="/" element={<UpdatesPage />} />
+<Route 
+    path="/" 
+    element={
+        <PrivateRoute>
+            <UpdatesPage />
+        </PrivateRoute>
+    } 
+/>
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d5d5df5 and aa32010.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (5)
  • package.json (3 hunks)
  • src/App.js (1 hunks)
  • src/components/ErrorPage/ErrorPage.js (1 hunks)
  • src/components/PrivateRoute.js (1 hunks)
  • src/context/AuthContext.js (1 hunks)
🔇 Additional comments (3)
src/components/ErrorPage/ErrorPage.js (1)

1-51: 🧹 Nitpick (assertive)

Add test coverage for ErrorPage component

The component lacks test coverage. Consider adding tests for different scenarios.

Would you like me to generate test cases for the ErrorPage component? This should include tests for:

  • Default error message
  • Custom message prop
  • Different error codes
  • Button navigation
package.json (2)

6-7: LGTM! Package versions are compatible.

The updates to @emotion/* and @mui/material packages maintain compatibility while providing new features for styling components.

Also applies to: 10-10


20-20: Verify react-router-dom compatibility with existing code.

The version is correct (6.22.1). However, since this is a major architectural change:

  1. Ensure all route definitions follow v6 syntax
  2. Verify that any existing navigation logic is updated to use v6 hooks (useNavigate instead of useHistory)

Let's verify the routing implementation:

✅ Verification successful

React Router v6 Implementation Verified

The codebase is fully compatible with react-router-dom v6:

  • Route definitions use correct v6 syntax with Routes and element props
  • Navigation implemented using v6 useNavigate hook
  • No legacy v5 patterns detected in routing logic
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for routing-related code to ensure v6 compatibility
echo "Checking route definitions..."
rg -l "Route|Routes|Router|useNavigate|useHistory" --type js

echo "Checking for potential v5 patterns..."
rg -l "Redirect|Switch|withRouter" --type js

Length of output: 587


Script:

#!/bin/bash
# Check route definitions and navigation patterns
echo "=== Route Definitions ==="
rg "Route|Routes|BrowserRouter|HashRouter" -A 2 src/App.js src/components/PrivateRoute.js

echo -e "\n=== Navigation Hooks ==="
rg "use(Navigate|History)" -A 1 --type js

echo -e "\n=== UpdatesList Router Imports ==="
rg "^import.*from ['\"]react-router" src/components/UpdatesPage/UpdatesList.jsx

Length of output: 1916

Comment on lines +5 to +13
export const AuthProvider = ({ children }) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);

return (
<AuthContext.Provider value={{ isAuthenticated, setIsAuthenticated }}>
{children}
</AuthContext.Provider>
);
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Enhance authentication context with loading and error states

The current implementation lacks loading and error states which are crucial for handling authentication flow properly.

 export const AuthProvider = ({ children }) => {
-    const [isAuthenticated, setIsAuthenticated] = useState(false);
+    const [authState, setAuthState] = useState({
+        isAuthenticated: false,
+        isLoading: true,
+        error: null
+    });
+
+    const setIsAuthenticated = (value) => {
+        setAuthState(prev => ({
+            ...prev,
+            isAuthenticated: value,
+            isLoading: false
+        }));
+        localStorage.setItem('isAuthenticated', value);
+    };

     return (
-        <AuthContext.Provider value={{ isAuthenticated, setIsAuthenticated }}>
+        <AuthContext.Provider value={{ ...authState, setIsAuthenticated }}>
             {children}
         </AuthContext.Provider>
     );
 };
📝 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.

Suggested change
export const AuthProvider = ({ children }) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
return (
<AuthContext.Provider value={{ isAuthenticated, setIsAuthenticated }}>
{children}
</AuthContext.Provider>
);
};
export const AuthProvider = ({ children }) => {
const [authState, setAuthState] = useState({
isAuthenticated: false,
isLoading: true,
error: null
});
const setIsAuthenticated = (value) => {
setAuthState(prev => ({
...prev,
isAuthenticated: value,
isLoading: false
}));
localStorage.setItem('isAuthenticated', value);
};
return (
<AuthContext.Provider value={{ ...authState, setIsAuthenticated }}>
{children}
</AuthContext.Provider>
);
};

export const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add persistence for authentication state

The authentication state will be reset on page reload since it's using a simple useState. Consider using localStorage or sessionStorage to persist the authentication state.

-const [isAuthenticated, setIsAuthenticated] = useState(false);
+const [isAuthenticated, setIsAuthenticated] = useState(() => {
+  return localStorage.getItem('isAuthenticated') === 'true';
+});
📝 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.

Suggested change
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [isAuthenticated, setIsAuthenticated] = useState(() => {
return localStorage.getItem('isAuthenticated') === 'true';
});

Comment on lines +6 to +10
const PrivateRoute = () => {
const { isAuthenticated } = useContext(AuthContext);

return isAuthenticated ? <UpdatesPage /> : <Navigate to="/error-unauthenticated" />;
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance PrivateRoute component reusability

The current implementation hard-codes the UpdatesPage component, making it non-reusable for other protected routes.

-const PrivateRoute = () => {
+const PrivateRoute = ({ children }) => {
     const { isAuthenticated } = useContext(AuthContext);
 
-    return isAuthenticated ? <UpdatesPage /> : <Navigate to="/error-unauthenticated" />;
+    return isAuthenticated ? children : <Navigate to="/error-unauthenticated" />;
 };
📝 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.

Suggested change
const PrivateRoute = () => {
const { isAuthenticated } = useContext(AuthContext);
return isAuthenticated ? <UpdatesPage /> : <Navigate to="/error-unauthenticated" />;
};
const PrivateRoute = ({ children }) => {
const { isAuthenticated } = useContext(AuthContext);
return isAuthenticated ? children : <Navigate to="/error-unauthenticated" />;
};

import UpdatesPage from './UpdatesPage/UpdatesPage';

const PrivateRoute = () => {
const { isAuthenticated } = useContext(AuthContext);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Handle loading state in authentication check

The component should handle the loading state from AuthContext to prevent flashing content.

-    const { isAuthenticated } = useContext(AuthContext);
+    const { isAuthenticated, isLoading } = useContext(AuthContext);
+
+    if (isLoading) {
+        return <div>Loading...</div>; // Consider using a proper loading component
+    }
📝 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.

Suggested change
const { isAuthenticated } = useContext(AuthContext);
const { isAuthenticated, isLoading } = useContext(AuthContext);
if (isLoading) {
return <div>Loading...</div>; // Consider using a proper loading component
}

Comment on lines +12 to +17
<Routes>
<Route path="/" element={<UpdatesPage />} />
<Route path="/dashboard" element={<PrivateRoute />} />
<Route path="/error-unauthenticated" element={<ErrorPage />} />
<Route path="*" element={<ErrorPage />} />
</Routes>
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Organize routes for better maintainability

Consider grouping related routes and using route constants for better maintainability.

+const ROUTES = {
+    ROOT: '/',
+    DASHBOARD: '/dashboard',
+    ERROR: '/error-unauthenticated',
+};

 <Routes>
-    <Route path="/" element={<UpdatesPage />} />
-    <Route path="/dashboard" element={<PrivateRoute />} />
-    <Route path="/error-unauthenticated" element={<ErrorPage />} />
-    <Route path="*" element={<ErrorPage />} />
+    {/* Protected Routes */}
+    <Route 
+        path={ROUTES.ROOT} 
+        element={
+            <PrivateRoute>
+                <UpdatesPage />
+            </PrivateRoute>
+        } 
+    />
+    <Route 
+        path={ROUTES.DASHBOARD} 
+        element={
+            <PrivateRoute>
+                <UpdatesPage />
+            </PrivateRoute>
+        } 
+    />
+    
+    {/* Error Routes */}
+    <Route path={ROUTES.ERROR} element={<ErrorPage />} />
+    <Route path="*" element={<ErrorPage />} />
 </Routes>

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +37 to +45
const ErrorPage = ({ message }) => {
return (
<Container role="alert" aria-live="polite">
<Heading>We cannot find this page</Heading>
<Text>{message || 'Either the URL doesn’t exist, or you don’t have access to it.'}</Text>
<Button to="/">Go to the main dashboard</Button>
</Container>
);
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Add error code prop for different error scenarios

The component could be more flexible by accepting an error code prop to display different messages based on the error type.

-const ErrorPage = ({ message }) => {
+const ErrorPage = ({ message, errorCode }) => {
+  const getDefaultMessage = (code) => {
+    switch(code) {
+      case 401:
+        return 'You need to be authenticated to access this page.';
+      case 404:
+        return 'The page you are looking for does not exist.';
+      default:
+        return 'Either the URL doesn't exist, or you don't have access to it.';
+    }
+  };
+
   return (
     <Container role="alert" aria-live="polite">
       <Heading>We cannot find this page</Heading>
-      <Text>{message || 'Either the URL doesn't exist, or you don't have access to it.'}</Text>
+      <Text>{message || getDefaultMessage(errorCode)}</Text>
       <Button to="/">Go to the main dashboard</Button>
     </Container>
   );
 };
📝 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.

Suggested change
const ErrorPage = ({ message }) => {
return (
<Container role="alert" aria-live="polite">
<Heading>We cannot find this page</Heading>
<Text>{message || 'Either the URL doesn’t exist, or you don’t have access to it.'}</Text>
<Button to="/">Go to the main dashboard</Button>
</Container>
);
};
const ErrorPage = ({ message, errorCode }) => {
const getDefaultMessage = (code) => {
switch(code) {
case 401:
return 'You need to be authenticated to access this page.';
case 404:
return 'The page you are looking for does not exist.';
default:
return 'Either the URL doesn't exist, or you don't have access to it.';
}
};
return (
<Container role="alert" aria-live="polite">
<Heading>We cannot find this page</Heading>
<Text>{message || getDefaultMessage(errorCode)}</Text>
<Button to="/">Go to the main dashboard</Button>
</Container>
);
};

Comment on lines +28 to +35
const Button = styled(Link)`
display: inline-block;
padding: 10px 20px;
background-color: #6c63ff;
color: #fff;
text-decoration: none;
border-radius: 5px;
`;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Add hover state to Button component

The button lacks visual feedback on hover, which is important for user interaction.

 const Button = styled(Link)`
   display: inline-block;
   padding: 10px 20px;
   background-color: #6c63ff;
   color: #fff;
   text-decoration: none;
   border-radius: 5px;
+  transition: background-color 0.2s ease;
+
+  &:hover {
+    background-color: #5a52cc;
+  }
 `;
📝 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.

Suggested change
const Button = styled(Link)`
display: inline-block;
padding: 10px 20px;
background-color: #6c63ff;
color: #fff;
text-decoration: none;
border-radius: 5px;
`;
const Button = styled(Link)`
display: inline-block;
padding: 10px 20px;
background-color: #6c63ff;
color: #fff;
text-decoration: none;
border-radius: 5px;
transition: background-color 0.2s ease;
&:hover {
background-color: #5a52cc;
}
`;

@gorkem-bwl
Copy link
Contributor

@imrehankhan can you please also add a screenshot of the page?

@GabrielChan1 assigned the review for you.

@imrehankhan
Copy link
Author

imrehankhan commented Jan 10, 2025

@imrehankhan can you please also add a screenshot of the page?

@GabrielChan1 assigned the review for you.

@imrehankhan can you please also add a screenshot of the page?

@GabrielChan1 assigned the review for you.

Screenshot 2025-01-10 at 6 49 02 PM @gorkem-bwl uploaded screenshot of error page
Screen.Recording.2025-01-10.at.7.15.46.PM.mov

@gorkem-bwl also uploaded screen recording of the feature

@gorkem-bwl
Copy link
Contributor

Thanks @imrehankhan - both the video and the screen look good.

@imrehankhan
Copy link
Author

Thanks @imrehankhan - both the video and the screen look good.

You're welcome @gorkem-bwl

@imrehankhan
Copy link
Author

@gorkem-bwl can you please merge this pr?

@gorkem-bwl
Copy link
Contributor

@gorkem-bwl can you please merge this pr?

For this one we'll need @GabrielChan1's input.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants