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

fixed unnecessary log in option after getting logged in (#205) #219

Conversation

Amnyadav
Copy link
Contributor

@Amnyadav Amnyadav commented Oct 11, 2024

fixed unnecessary log in option after getting logged in .

now you got the log out option there instead of log in.

i have used jwt token to get to know if user is log in or not based no that i select what option i have to show .

Screenshot 2024-10-11 121106

Summary by CodeRabbit

  • New Features

    • Enhanced login process with token storage in cookies for improved security and persistence.
    • Updated Navbar to utilize JWT tokens for user authentication, streamlining the login state management.
  • Bug Fixes

    • Improved error handling and loading state management during the login process.
  • Style

    • Minor adjustments to button text rendering in the Navbar for clearer user experience.

Copy link

vercel bot commented Oct 11, 2024

@Amnyadav is attempting to deploy a commit to the bunty's projects Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Oct 11, 2024

Walkthrough

The pull request introduces modifications to the Login and Navbar components to enhance user authentication. The Login component now stores the authentication token in cookies upon successful login, replacing the previous local storage method. The Navbar component retrieves this token from cookies to manage the user's logged-in state. The changes streamline the authentication process and update the logout handling to remove the token from cookies.

Changes

File Path Change Summary
frontend/src/components/Pages/Login.jsx Updated to store the authentication token in cookies after a successful login.
frontend/src/components/Shared/Navbar.jsx Modified to use a JWT token from cookies for user authentication; updated logout handling.
frontend/package.json Added the js-cookie dependency to manage cookie operations.

Possibly related PRs

  • global message implemented #94: The changes in the Navbar component regarding user authentication handling are related to the main PR's updates in the Login component, as both involve managing authentication tokens and state.
  • changes the font of navbar and added a hover effect. #103: The modifications in the Navbar component, particularly around user authentication, connect with the main PR's changes in the Login component, which also deals with user login functionality.
  • Kinde/remove #169: The removal of Kinde authentication in the Navbar component relates to the main PR's updates in the Login component, as both are focused on user authentication processes.
  • Signup/login/page #173: The addition of the Login component in this PR directly relates to the changes made in the main PR, which also involves updates to the Login component for handling authentication.
  • Reset Password For Play Cafe  #177: The introduction of the ResetPassword component and its connection to user authentication aligns with the main PR's focus on managing authentication tokens in the Login component.

Suggested labels

enhancement, level 1, gssoc-ext

Poem

In the burrow, where bunnies play,
A token's stored, come what may.
With each login, a leap of cheer,
The Navbar knows when friends are near.
Hop along, let the good times roll,
For every login, we reach our goal! 🐇✨


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:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • 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 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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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
Contributor

Thank you for submitting your pull request! 🙌 We'll review it as soon as possible. In the meantime, please ensure that your changes align with our CONTRIBUTING.md. If there are any specific instructions or feedback regarding your PR, we'll provide them here. Thanks again for your contribution! 😊

Copy link
Contributor

@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: 2

🧹 Outside diff range and nitpick comments (7)
frontend/src/components/Pages/Login.jsx (2)

37-38: Consider simplifying token storage

The token storage implementation is correct, but it can be simplified:

Consider applying this change:

-const token=result.token;
-localStorage.setItem("token",JSON.stringify(token));
+localStorage.setItem("token", result.token);

This change eliminates the need for JSON stringification, as the token is likely already a string. It also improves readability and reduces the risk of parsing errors when retrieving the token later.


Line range hint 1-105: Enhance security, error handling, and user experience

While the overall implementation is solid, consider the following improvements:

  1. Security Enhancement:
    Instead of storing the entire token in localStorage, consider storing only a session identifier and keeping the token in memory. This approach reduces the risk of XSS attacks.

    // After successful login
    const sessionId = generateSessionId(); // Implement this function
    localStorage.setItem("sessionId", sessionId);
    sessionStorage.setItem("token", result.token);
  2. Improved Error Handling:
    Provide more specific error messages based on the API response. This will help users understand and resolve issues more easily.

    if (!response.ok) {
      const errorMessage = result.message || 'Login failed';
      if (response.status === 401) {
        throw new Error('Invalid email or password. Please try again.');
      } else if (response.status === 429) {
        throw new Error('Too many login attempts. Please try again later.');
      } else {
        throw new Error(errorMessage);
      }
    }
  3. Password Visibility Toggle:
    Add a button to toggle password visibility, improving user experience.

    const [showPassword, setShowPassword] = useState(false);
    
    // In the JSX, replace the password input with:
    <div className="relative w-full">
      <input
        className="input w-full h-10 rounded-md border-2 border-black bg-beige shadow-[4px_4px_0px_0px_black] text-[15px] font-semibold text-[#323232] p-2.5 focus:outline-none focus:border-[#2d8cf0] placeholder-[#666] placeholder-opacity-80"
        name="password"
        placeholder="Password"
        type={showPassword ? "text" : "password"}
        onChange={(e) => handleChange(e)}
      />
      <button
        type="button"
        className="absolute inset-y-0 right-0 pr-3 flex items-center"
        onClick={() => setShowPassword(!showPassword)}
      >
        {showPassword ? "Hide" : "Show"}
      </button>
    </div>

These changes will significantly improve the security, user experience, and error handling of your login component.

frontend/src/components/Shared/Navbar.jsx (5)

Line range hint 5-5: Remove unused isloggedIn state variable

The state variable isloggedIn is no longer used in the component. Removing it will clean up the code.

Apply this diff to remove the unused state variable:

-const [isloggedIn, setisloggedIn] = useState(false);

40-40: Remove commented-out code related to isloggedIn

The commented-out line setting isloggedIn to false is no longer needed and can be removed to clean up the code.

Apply this diff to remove the unused code:

-// setisloggedIn(false); // Set isLoggedIn to false on confirmation

41-41: Improve comment for clarity and grammar

Consider rephrasing the comment for better clarity and proper grammar.

Apply this diff to update the comment:

-//managing log in , logout using jwt tokens 
+// Managing login and logout using JWT tokens

44-45: Add missing semicolons for consistency

Lines 44 and 45 are missing semicolons at the end of the statements. Adding them ensures consistency and prevents potential issues.

Apply this diff to add the missing semicolons:

 setIsModalOpen(false); // Close the modal
-setIsMenuOpen(false) // after getting logged out close the menu if it is open
+setIsMenuOpen(false); // After logging out, close the menu if it is open
-navigate("/login")//navigate to login after get logged out
+navigate("/login"); // Navigate to login after logging out

Line range hint 104-109: Refactor duplicated code for login/logout buttons into a reusable component

The logic for rendering the login/logout buttons in both the desktop menu (lines 104-109) and the mobile menu (lines 183-189) is duplicated. Consider creating a reusable component or function to reduce duplication and improve maintainability.

Example: Create an AuthButton component

First, create a new component within your Navbar.jsx file or separate it into its own file:

const AuthButton = ({ baseTextColorClass, hoverTextColorClass }) => {
  const navigate = useNavigate();
  const handleLogoutClick = () => {
    setIsModalOpen(true);
  };

  return token ? (
    <button
      className={`${baseTextColorClass} ${hoverTextColorClass} px-4 py-1 rounded-md border-2 border-black bg-beige shadow-[4px_4px_0px_0px_black] font-semibold text-[#323232]`}
      type="button"
      onClick={handleLogoutClick}
    >
      LOGOUT
    </button>
  ) : (
    <button
      className={`${baseTextColorClass} ${hoverTextColorClass} px-4 py-1 rounded-md border-2 border-black bg-beige shadow-[4px_4px_0px_0px_black] font-semibold text-[#323232]`}
      type="button"
      onClick={() => navigate('/login')}
    >
      LOGIN
    </button>
  );
};

Then, replace the duplicated code in the desktop menu (line 104) and mobile menu (line 183) with the new AuthButton component:

Desktop Menu:

{/* Existing code */}
<div className="hidden md:flex font-semibold Poppins text-lg">
-  {token ? (
-    <button /* ... */>
-      LOGOUT
-    </button>
-  ) : (
-    <button /* ... */>
-      LOGIN
-    </button>
-  )}
+  <AuthButton baseTextColorClass={baseTextColorClass} hoverTextColorClass={hoverTextColorClass} />
</div>

Mobile Menu:

{/* Existing code */}
{isMenuOpen && (
  <div /* ... */>
    <div className="px-4 pt-4 pb-4 space-y-2">
      {/* Menu items */}
-     {token ? (
-       <button /* ... */>
-         Log Out
-       </button>
-     ) : (
-       <button /* ... */>
-         Log In
-       </button>
-     )}
+     <AuthButton baseTextColorClass={mobileMenuBaseTextColorClass} hoverTextColorClass="hover:bg-amber-300 hover:text-black" />
    </div>
  </div>
)}

This refactoring reduces code duplication and makes the authentication button easier to manage.

Also applies to: 183-189

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 045630a and b40129b.

📒 Files selected for processing (2)
  • frontend/src/components/Pages/Login.jsx (1 hunks)
  • frontend/src/components/Shared/Navbar.jsx (4 hunks)
🧰 Additional context used

frontend/src/components/Shared/Navbar.jsx Outdated Show resolved Hide resolved
@RamakrushnaBiswal
Copy link
Owner

@Amnyadav resolve code rabit suggestions

Copy link
Contributor

@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: 0

🧹 Outside diff range and nitpick comments (2)
frontend/package.json (1)

25-25: LGTM! Consider adding a comment for clarity.

The addition of the js-cookie package (version ^3.0.5) is appropriate for handling JWT tokens as mentioned in the PR objectives. This change aligns well with the goal of improving user authentication.

Consider adding a brief comment in the package.json file to explain the purpose of this new dependency. For example:

 {
   ...
   "dependencies": {
     ...
+    // Used for handling JWT tokens for authentication
     "js-cookie": "^3.0.5",
     ...
   },
   ...
 }

This can help other developers understand why this package was added without needing to refer to the PR description.

frontend/src/components/Pages/Login.jsx (1)

37-40: Approved: Token storage moved to cookies, but minor formatting issue.

The change to store the authentication token in cookies instead of local storage is a good security improvement. The cookie is correctly set with an expiration time and the secure flag.

However, there's a minor formatting issue:

Consider adjusting the indentation to match the rest of the function:

-      Cookies.set('authToken',result.token,{
-        expire:'1h',
-        secure:true
-      });
+      Cookies.set('authToken', result.token, {
+        expire: '1h',
+        secure: true
+      });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b40129b and 2fca884.

📒 Files selected for processing (3)
  • frontend/package.json (1 hunks)
  • frontend/src/components/Pages/Login.jsx (2 hunks)
  • frontend/src/components/Shared/Navbar.jsx (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/src/components/Shared/Navbar.jsx
🧰 Additional context used
🔇 Additional comments (2)
frontend/src/components/Pages/Login.jsx (2)

5-5: LGTM: Cookie library import added correctly.

The import statement for the Cookies library is correctly placed and follows proper naming conventions.


Line range hint 1-108: Verify consistency of authentication flow across the application.

The change to use cookies for token storage is a good improvement. However, to ensure a consistent authentication flow:

  1. Verify that the logout functionality in other components (e.g., Navbar) has been updated to remove the cookie instead of clearing local storage.
  2. Check if any other components that previously accessed the token from local storage have been updated to read from cookies.

This will help maintain a consistent and secure authentication system throughout the application.

To assist in this verification, you can run the following script:

This script will help identify any remaining localStorage usage for authentication, verify cookie usage in other components, and locate logout functionality that may need updating.

Copy link

vercel bot commented Oct 11, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
play-cafe ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 11, 2024 11:04am
play-cafe-backen ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 11, 2024 11:04am

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working enhancement New feature or request gssoc-ext gssoc-extd program hacktoberfest accepted hacktoberfest-accepted repo level2 for 25 points
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants