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: No notification shown when invalid OTP is entered #9667

Merged
merged 4 commits into from
Jan 3, 2025

Conversation

abhimanyurajeesh
Copy link
Contributor

@abhimanyurajeesh abhimanyurajeesh commented Jan 2, 2025

Proposed Changes

  • Fixes No notification shown when invalid OTP is entered #9656
  • Change 1: Introduced a default error message "invalid_otp": "Invalid OTP, Please check the OPT and try Again" to en.json
  • Change 2: Added conditional checks to determine if the error object follows the expected structure (error.cause.errors).

Summary

  • These changes aim to make the error handling more reliable and user-friendly by ensuring that any issues during the OTP process are communicated clearly to the user, reducing confusion and improving the overall user experience during authentication.

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Screenshot

image

Summary by CodeRabbit

  • New Features

    • Added localized error message for invalid OTP verification.
  • Bug Fixes

    • Improved OTP error handling in login process.
    • Enhanced user feedback for authentication errors.

@abhimanyurajeesh abhimanyurajeesh requested a review from a team as a code owner January 2, 2025 15:27
Copy link
Contributor

coderabbitai bot commented Jan 2, 2025

Walkthrough

The pull request addresses the issue of displaying an error message when an invalid OTP is entered during the login process. A new localization string for the "invalid_otp" error has been added to the English JSON file. Simultaneously, the Login component's error handling logic has been updated to more effectively capture and display OTP validation errors, ensuring users receive clear feedback when their OTP is incorrect.

Changes

File Change Summary
public/locale/en.json Added new localization key "invalid_otp" with error message for invalid OTP
src/components/Auth/Login.tsx Enhanced OTP error handling logic to capture and display validation errors

Assessment against linked issues

Objective Addressed Explanation
Show notification for invalid OTP [#9656]

Possibly related PRs

  • OTP schedule timezone fix #9676: This PR addresses OTP functionalities and includes changes related to error handling for OTP, which is directly connected to the new localization entry for "invalid_otp" in the main PR.

Suggested labels

good to merge

Suggested reviewers

  • rithviknishad
  • Jacobjeevan

Poem

🐰 OTP errors, once so sly
Now caught with a rabbit's keen eye
A message clear, no more disguise
Invalid codes meet their demise
Authentication's triumph nigh! 🔐


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 86c681e and 9d91cfb.

📒 Files selected for processing (1)
  • public/locale/en.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • public/locale/en.json

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 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.

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

netlify bot commented Jan 2, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 9d91cfb
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/67779077e72e3e0008c5ec27
😎 Deploy Preview https://deploy-preview-9667--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

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

🧹 Nitpick comments (4)
src/components/Auth/Login.tsx (3)

171-171: Leverage in-code comments to clarify the new OTP error handling flow.
Adding a short comment can help other devs quickly understand the purpose of this error callback when dealing with invalid OTP scenarios, especially since it addresses #9656.


176-179: Consider using optional chaining for safer property checks.
Instead of:

if (
  error.cause &&
  Array.isArray(error.cause.errors) &&
  error.cause.errors.length > 0
) { 
  ...
}

You could simplify conditional checks:

- if (
-   error.cause &&
-   Array.isArray(error.cause.errors) &&
-   error.cause.errors.length > 0
- ) {
+ if (Array.isArray(error.cause?.errors) && error.cause.errors.length > 0) {
    ...
  }

180-183: Encapsulate OTP error extraction into a helper function.
This block neatly extracts the “otp” error from error.cause.errors. For cleaner code and potential reuse, consider moving it into a small utility function that returns the final errorMessage.

🧰 Tools
🪛 Biome (1.9.4)

[error] 181-181: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

public/locale/en.json (1)

1016-1016: Check for spelling consistency in error message.
There is a small typo: "Please check the OPT and try Again" should likely use "OTP".

- "invalid_otp": "Invalid OTP, Please check the OPT and try Again"
+ "invalid_otp": "Invalid OTP, Please check the OTP and try again."
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b58db6a and 6215ebe.

📒 Files selected for processing (2)
  • public/locale/en.json (1 hunks)
  • src/components/Auth/Login.tsx (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/components/Auth/Login.tsx

[error] 181-181: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (1)
src/components/Auth/Login.tsx (1)

184-187: Order of fallback checks is clear, but confirm fail-safe coverage.
Currently, if errorMessage is not set from the array of errors, you default to error.message. Make sure this fallback is always defined or your user interface handles the scenario if error.message is unexpected or missing.

@abhimanyurajeesh
Copy link
Contributor Author

@rithviknishad please let me know if it works or I made any mistakes. Thank You!

Copy link
Member

@rithviknishad rithviknishad left a comment

Choose a reason for hiding this comment

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

setOtpValidationError(firstError.otp);
} else {
setOtpValidationError(t("invalid_otp"));
Notification.Error({ msg: t("invalid_otp") });
Copy link
Member

Choose a reason for hiding this comment

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

the otp error notification is likely not being dispatched due to it's useQuery being passed with silent=true.

This is ideally auto handled by our global error handler defined here:

https://github.com/ohcnetwork/care_fe/blob/develop/src/Utils/request/errorHandler.ts

As for the set otp error for the field error, LGTM.

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

🧹 Nitpick comments (3)
src/components/Auth/Login.tsx (3)

170-187: Improve error handling robustness

The error handling implementation could be more robust with optional chaining and simplified logic.

Consider this improved implementation:

    onError: (error: HTTPError) => {
-      let errorMessage = t("invalid_otp");
-      if (
-        error.cause &&
-        Array.isArray(error.cause.errors) &&
-        error.cause.errors.length > 0
-      ) {
-        const otpError = error.cause.errors.find((e) => e.otp);
-        if (otpError && otpError.otp) {
-          errorMessage = otpError.otp;
-        }
-      } else if (error.message) {
-        errorMessage = error.message;
-      }
+      const errorMessage = error.cause?.errors?.find(e => e.otp)?.otp 
+        ?? error.message 
+        ?? t("invalid_otp");
       setOtpValidationError(errorMessage);
       Notification.Error({ msg: errorMessage });
    },
🧰 Tools
🪛 Biome (1.9.4)

[error] 180-180: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


171-172: Enhance code documentation and type safety

The error handling comment could be more descriptive, and the error structure could benefit from proper type definitions.

Consider adding:

  1. A more descriptive comment explaining the error structure:
-    //Invalid OTP error handling
+    // Handle OTP validation errors
+    // error.cause.errors structure: Array<{ otp?: string, [key: string]: any }>
  1. A type definition for the error structure:
interface OtpValidationError {
  otp?: string;
  [key: string]: any;
}

interface OtpErrorResponse extends HTTPError {
  cause?: {
    errors?: OtpValidationError[];
  };
}

170-187: Consider additional security measures

While the implementation handles basic error cases, consider these security improvements:

  1. Sanitize error messages to prevent potential information leakage. Consider using predefined error messages instead of directly displaying server errors.
  2. Implement client-side rate limiting for OTP verification attempts.

Example implementation for rate limiting:

const MAX_OTP_ATTEMPTS = 3;
const [otpAttempts, setOtpAttempts] = useState(0);

// In onError callback
if (otpAttempts >= MAX_OTP_ATTEMPTS) {
  setOtpValidationError(t("max_attempts_reached"));
  // Reset after delay
  setTimeout(() => setOtpAttempts(0), 30000);
  return;
}
setOtpAttempts(prev => prev + 1);
🧰 Tools
🪛 Biome (1.9.4)

[error] 180-180: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6215ebe and 86c681e.

📒 Files selected for processing (1)
  • src/components/Auth/Login.tsx (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/components/Auth/Login.tsx

[error] 180-180: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (1)
src/components/Auth/Login.tsx (1)

170-187: Review the use of silent flag in mutation

Based on the previous review comment, the silent: true flag in the mutation configuration might prevent the global error handler from showing notifications. Consider if this is intentional, as you're manually handling the notifications here.

Let's check the mutation configuration:

✅ Verification successful

Let me check the request utility implementation to understand how the silent flag affects error handling.


Let me check the global error handler implementation to understand how the silent flag affects notifications.


Let me check the HTTPError implementation to understand how the silent flag is set.


Based on the code analysis, I can now provide the final response:

The silent flag usage is correct and intentional

The implementation is working as expected because:

  1. The silent: true flag in the mutation is correctly passed to the HTTPError constructor
  2. The global error handler (handleHttpError) checks for error.silent and skips showing notifications for silent errors
  3. The component manually handles notifications using Notification.Error({ msg: errorMessage }) for OTP validation errors

This pattern allows the component to have full control over error message formatting and display while preventing duplicate notifications from the global handler.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if there are other mutations using silent flag
rg "silent:\s*true" -A 2 -B 2

Length of output: 6164


Script:

#!/bin/bash
# Check the request utility implementation
ast-grep --pattern 'function request($$$) {
  $$$
}'

# Also check for any global error handling setup
rg "onError|errorHandler" -A 5 -B 5

Length of output: 52788


Script:

#!/bin/bash
# Check the error handler implementation
rg -g "errorHandler.ts" -A 10 "export.*handleHttpError"

Length of output: 685


Script:

#!/bin/bash
# Check the HTTPError class implementation
ast-grep --pattern 'class HTTPError extends Error {
  $$$
}'

Length of output: 1115

🧰 Tools
🪛 Biome (1.9.4)

[error] 180-180: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

@rithviknishad rithviknishad merged commit ee27ecd into ohcnetwork:develop Jan 3, 2025
17 checks passed
Copy link

github-actions bot commented Jan 3, 2025

@abhimanyurajeesh Your efforts have helped advance digital healthcare and TeleICU systems. 🚀 Thank you for taking the time out to make CARE better. We hope you continue to innovate and contribute; your impact is immense! 🙌

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.

No notification shown when invalid OTP is entered
3 participants