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

Logout API Integration #57

Merged
merged 2 commits into from
Dec 3, 2024
Merged

Logout API Integration #57

merged 2 commits into from
Dec 3, 2024

Conversation

vidyaaKhandekar
Copy link
Contributor

@vidyaaKhandekar vidyaaKhandekar commented Dec 3, 2024

Logout API Integration

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced logout functionality with improved error handling and user notifications.
    • User authentication flow now includes saving access and refresh tokens to local storage upon successful login.
  • Bug Fixes

    • Fixed logout process to ensure tokens are cleared from local storage after logout.
  • Documentation

    • Improved user feedback during authentication and logout processes through toast notifications.

Copy link
Contributor

coderabbitai bot commented Dec 3, 2024

Warning

Rate limit exceeded

@vidyaaKhandekar has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 13 minutes and 31 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between fc30ec7 and 13e5913.

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes involve modifications to several components and services related to user authentication and logout functionality. The Navbar and Home components have been updated to use the useToast hook for user notifications and to implement asynchronous logout processes. The SignIn component has introduced state management for storing authentication tokens. The logoutUser service function has been restructured to manage tokens directly from local storage, enhancing the logout flow and error handling.

Changes

File Path Change Summary
src/components/common/layout/Navbar.tsx Added useToast hook, modified handleLogout to use logoutUser service asynchronously with error handling.
src/screens/Home.tsx Updated handleConsent to be asynchronous, integrated useToast, and improved error handling during logout.
src/screens/auth/SignIn.tsx Introduced state variable token for storing authentication token, updated handleLogin to save tokens to local storage.
src/services/auth/auth.tsx Modified logoutUser to retrieve tokens from local storage, removed parameters, and added logging in loginUser.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Navbar
    participant AuthService
    participant Home

    User->>Navbar: Click Logout
    Navbar->>AuthService: Call logoutUser()
    AuthService->>localStorage: Remove tokens
    AuthService-->>Navbar: Return success
    Navbar->>User: Show success toast
    Navbar->>Home: Redirect to home page
    Home->>User: Refresh page
Loading

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

@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

🧹 Outside diff range and nitpick comments (6)
src/components/common/layout/Navbar.tsx (1)

35-50: Add loading state during logout

The logout process should indicate to users that an action is in progress, preventing multiple clicks and improving user experience.

  const Navbar: React.FC<{ isMenu?: boolean }> = ({ isMenu = true }) => {
    const [success] = useState<string>("");
+   const [isLoggingOut, setIsLoggingOut] = useState(false);
    const navigate = useNavigate();
    const { t } = useTranslation();
    const toast = useToast();

    const handleLogout = async () => {
+     if (isLoggingOut) return;
+     setIsLoggingOut(true);
      try {
        const response = await logoutUser();
        // ... rest of the code
      } catch (error) {
        // ... error handling
      } finally {
+       setIsLoggingOut(false);
      }
    };
src/screens/auth/SignIn.tsx (1)

Line range hint 35-51: Consider removing redundant token state

The token state appears unnecessary since tokens are already stored in localStorage. Consider removing it unless needed for specific UI rendering.

-  const [token, setToken] = useState();

   const handleLogin = async () => {
     try {
       setLoading(true);
       const response = await loginUser({ username, password });
       if (response) {
         toast({
           title: t("SIGNIN_LOGGEDIN_SUCCESSFULLY"),
           status: "success",
           duration: 3000,
           isClosable: true,
         });
-        setToken(response);
         localStorage.setItem("authToken", response.data.access_token);
         localStorage.setItem("refreshToken", response.data.refresh_token);
         navigate(0);
       }
🧰 Tools
🪛 eslint

[error] 54-54: 'error' is defined but never used.

(@typescript-eslint/no-unused-vars)

src/screens/Home.tsx (1)

53-54: Improve error logging

Consider using a proper error logging service instead of console.log for better error tracking in production.

     } catch (error) {
-      console.log(error);
+      // TODO: Implement proper error logging service
+      console.error('Logout failed:', error);
       toast({
src/services/auth/auth.tsx (3)

24-25: Remove debugging console.log statement

Production code should not contain console.log statements. Consider using proper logging mechanisms if logging is required.

-    console.log("response.data", response.data);

54-55: Consider centralizing token management

Token management (storage and removal) is scattered across the codebase. Consider creating a dedicated token management utility to handle these operations consistently.

Example utility:

// utils/tokenManager.ts
export const TokenManager = {
  clearTokens: () => {
    localStorage.removeItem("authToken");
    localStorage.removeItem("refreshToken");
  },
  getTokens: () => ({
    accessToken: localStorage.getItem("authToken"),
    refreshToken: localStorage.getItem("refreshToken")
  })
};

Line range hint 38-67: Enhance security with proper error handling and token validation

While the logout implementation is generally secure, consider these security enhancements:

  1. Validate token format before making the API call
  2. Clear tokens even if the API call fails
  3. Add proper error typing for better error handling

Example implementation:

export const logoutUser = async () => {
  try {
    const tokens = TokenManager.getTokens();
    if (!tokens.accessToken || !tokens.refreshToken) {
      throw new Error("Missing authentication tokens");
    }

    await axios.post(
      `${apiBaseUrl}/auth/logout`,
      {
        access_token: tokens.accessToken,
        refresh_token: tokens.refreshToken,
      },
      {
        headers: {
          "Content-Type": "application/json",
        },
      }
    );

    return true;
  } catch (error) {
    // Clear tokens even if API call fails
    console.error("Logout failed:", error);
  } finally {
    TokenManager.clearTokens();
  }
};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 473e6a7 and fc30ec7.

📒 Files selected for processing (4)
  • src/components/common/layout/Navbar.tsx (1 hunks)
  • src/screens/Home.tsx (3 hunks)
  • src/screens/auth/SignIn.tsx (3 hunks)
  • src/services/auth/auth.tsx (4 hunks)
🧰 Additional context used
🪛 eslint
src/services/auth/auth.tsx

[error] 2-2: 'useNavigate' is defined but never used.

(@typescript-eslint/no-unused-vars)

Comment on lines 31 to 34
const handleLogout = async () => {
localStorage.removeItem("authToken");
navigate("/");
navigate(0);
// localStorage.removeItem("authToken");

// keycloak.logout({ redirectUri: window.location.origin });
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Consider clearing local tokens regardless of API response

For security reasons, it's recommended to clear local tokens even if the API call fails. This ensures the user's session is terminated locally even in case of network issues.

  const handleLogout = async () => {
+   const clearLocalTokens = () => {
+     localStorage.removeItem("authToken");
+     localStorage.removeItem("refreshToken");
+   };
    try {
      const response = await logoutUser();
      if (response) {
+       clearLocalTokens();
        navigate("/");
        navigate(0);
      }
    } catch (error) {
+     clearLocalTokens();
      console.log(error);
      toast({

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

@@ -63,6 +66,7 @@ const SignIn: React.FC = () => {
const handleBack = () => {
navigate("/");
};
console.log("response", token);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove sensitive data logging

Console logging of authentication tokens poses a security risk as it exposes sensitive information in browser logs.

-  console.log("response", token);

@@ -1,10 +1,11 @@
import React, { useContext, useEffect, useState } from "react";
import { Box, VStack } from "@chakra-ui/react";
import { Box, useToast, VStack } from "@chakra-ui/react";
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Based on the results, I can now generate the final response:

Logout implementation is consistent but needs cleanup

The logout implementation using logoutUser service is consistent across components, but there's a commented-out token removal in Navbar that should be cleaned up:

  • src/components/common/layout/Navbar.tsx: Remove commented code for localStorage.removeItem("authToken")
  • Main logout logic in src/services/auth/auth.tsx correctly removes both tokens
  • Both Home.tsx and Navbar.tsx components handle logout consistently with proper navigation
🔗 Analysis chain

Verify consistent logout implementation

Ensure that the logout implementation is consistent across all components using the logoutUser service.

Also applies to: 8-8

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all usages of logoutUser and localStorage token removal
echo "Checking logoutUser usage:"
rg "logoutUser" -A 5

echo "\nChecking localStorage token removal:"
rg "localStorage\.removeItem\(.*Token" -A 2

Length of output: 2632

Comment on lines +44 to +61
const handleConsent = async () => {
setConsentSaved(!consentSaved);
keycloak.logout();
localStorage.removeItem("authToken");
try {
const response = await logoutUser();
if (response) {
navigate("/");
navigate(0);
}
} catch (error) {
console.log(error);
toast({
title: "Logout failed",
status: "error",
duration: 3000,
isClosable: true,
description: "Try Again",
});
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Separate consent and logout logic

The handleConsent function now handles logout functionality, which violates the Single Responsibility Principle. Consider separating these concerns.

-  const handleConsent = async () => {
+  const handleConsentClose = () => {
     setConsentSaved(!consentSaved);
+  };
+
+  const handleLogout = async () => {
     try {
       const response = await logoutUser();
       if (response) {
+       localStorage.removeItem("authToken");
+       localStorage.removeItem("refreshToken");
         navigate("/");
         navigate(0);
       }
     } catch (error) {
       console.log(error);
       toast({
         title: "Logout failed",
         status: "error",
         duration: 3000,
         isClosable: true,
         description: "Try Again",
       });
     }
   };

Then update the dialogue component:

   {consentSaved && (
     <CommonDialogue
       isOpen={consentSaved}
-      onClose={handleConsent}
+      onClose={handleConsentClose}
       termsAndConditions={termsAndConditions}
       handleDialog={saveConsent}
     />
   )}

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

Comment on lines +38 to +40
export const logoutUser = async () => {
const accessToken = localStorage.getItem("authToken");
const refreshToken = localStorage.getItem("refreshToken");
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add null checks and type safety for localStorage tokens

The tokens retrieved from localStorage should be checked for null values and properly typed.

-  const accessToken = localStorage.getItem("authToken");
-  const refreshToken = localStorage.getItem("refreshToken");
+  const accessToken = localStorage.getItem("authToken");
+  const refreshToken = localStorage.getItem("refreshToken");
+  
+  if (!accessToken || !refreshToken) {
+    return Promise.reject(new Error("Missing authentication tokens"));
+  }
📝 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 logoutUser = async () => {
const accessToken = localStorage.getItem("authToken");
const refreshToken = localStorage.getItem("refreshToken");
export const logoutUser = async () => {
const accessToken = localStorage.getItem("authToken");
const refreshToken = localStorage.getItem("refreshToken");
if (!accessToken || !refreshToken) {
return Promise.reject(new Error("Missing authentication tokens"));
}

@@ -1,5 +1,5 @@
import axios from "axios";
import { removeToken } from "./asyncStorage";
import { useNavigate } from "react-router-dom";
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove unused import and maintain service layer architecture

The useNavigate hook import is unused and should be removed. Additionally, React hooks should not be used in service files as they are meant for React components only.

-import { useNavigate } from "react-router-dom";
🧰 Tools
🪛 eslint

[error] 2-2: 'useNavigate' is defined but never used.

(@typescript-eslint/no-unused-vars)

Copy link

sonarcloud bot commented Dec 3, 2024

@manojLondhe manojLondhe merged commit 35c8bfc into tekdi:main Dec 3, 2024
3 checks passed
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