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

Bug Fix: Fixed field should not allow only whitespace values issue #2318

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

Conversation

Vinod-Mane3021
Copy link

@Vinod-Mane3021 Vinod-Mane3021 commented Oct 11, 2024

What does this PR do?

Added validation to check the Default Prefix is empty or contain whitespaces using .trim() method.

Fixes #2297

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • Chore (refactoring code, technical debt, workflow improvements)
  • Enhancement (small improvements)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How should this be tested?

  • Navigate to Dashbaord -> APIs -> Select anyone API -> API Settings
  • Enter only whitespace (e.g., several spaces) in the "Default Prefix" field.
  • Attempt to save the changes.
  • Check if the error message is showing in bottom right corner or not

Checklist

Required

  • Filled out the "How to test" section in this PR
  • Read Contributing Guide
  • Self-reviewed my own code
  • Commented on my code in hard-to-understand areas
  • Ran pnpm build
  • Ran pnpm fmt
  • Checked for warnings, there are none
  • Removed all console.logs
  • Merged the latest changes from main onto my branch with git pull origin main
  • My changes don't cause any responsiveness issues

Appreciated

  • If a UI change was made: Added a screen recording or screenshots to this PR
  • Updated the Unkey Docs if changes were necessary

Summary by CodeRabbit

  • New Features

    • Enhanced input validation for the default prefix field to prevent submission of empty or whitespace-only values, with error messaging for users.
  • Bug Fixes

    • Maintained existing validation checks to ensure robust handling of default prefix submissions.

Copy link

changeset-bot bot commented Oct 11, 2024

⚠️ No Changeset found

Latest commit: 7ad275d

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

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)
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 13, 2024 6:53pm

Copy link

vercel bot commented Oct 11, 2024

@vinod-techstax is attempting to deploy a commit to the Unkey Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Oct 11, 2024

Warning

Rate limit exceeded

@chronark has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 18 minutes and 36 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

Files that changed from the base of the PR and between 6e45634 and 7ad275d.

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes introduced in this pull request enhance the validation process for the DefaultPrefix component within the API settings. A new validation check has been added to the onSubmit function to ensure that the defaultPrefix value is not empty or composed solely of whitespace. If this condition is violated, an error toast is displayed, preventing the submission of invalid values.

Changes

File Path Change Summary
apps/dashboard/app/(app)/apis/[apiId]/settings/default-prefix.tsx Added validation check in onSubmit for defaultPrefix to prevent submission of empty or whitespace-only values. Trigger error toast on violation.

Assessment against linked issues

Objective Addressed Explanation
The Default Prefix field should not allow only whitespace values. (#2297)

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.

@CLAassistant
Copy link

CLAassistant commented Oct 11, 2024

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
0 out of 2 committers have signed the CLA.

❌ Vinod-Mane3021
❌ vinod-techstax
You have signed the CLA already but the status is still pending? Let us recheck it.

Copy link
Contributor

github-actions bot commented Oct 11, 2024

Hey there and thank you for opening this pull request! 👋🏼

We require pull request titles to follow the Conventional Commits specification and it looks like your proposed title needs to be adjusted.
Here is an example:

<type>[optional scope]: <description>
fix: I fixed something for Unkey

Details:

No release type found in pull request title "Bug Fix: Fixed field should not allow only whitespace values issue". Add a prefix to indicate what kind of release this pull request corresponds to. For reference, see https://www.conventionalcommits.org/

Available types:
 - feat: A new feature
 - fix: A bug fix
 - docs: Documentation only changes
 - style: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
 - refactor: A code change that neither fixes a bug nor adds a feature
 - perf: A code change that improves performance
 - test: Adding missing tests or correcting existing tests
 - build: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)
 - ci: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)
 - chore: Other changes that don't modify src or test files
 - revert: Reverts a previous commit

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)
apps/dashboard/app/(app)/apis/[apiId]/settings/default-prefix.tsx (2)

56-58: Approved: Good addition of whitespace validation

The new validation check effectively addresses the issue of allowing only whitespace values in the default prefix. The use of trim() is appropriate, and the error message is clear.

For consistency with other error messages in this function, consider using the toast.error() method instead of returning the result. This would allow the function to continue checking other conditions if needed in the future.

Here's a suggested minor refactor for consistency:

-    if (values.defaultPrefix.trim() === '') {
-      return toast.error("Default prefix cannot be empty or contain only spaces.");
-    }
+    if (values.defaultPrefix.trim() === '') {
+      toast.error("Default prefix cannot be empty or contain only spaces.");
+      return;
+    }

Line range hint 56-65: Consider refactoring validation logic for better maintainability

While the current implementation works correctly, the multiple validation checks in the onSubmit function could be refactored for better maintainability. Consider extracting these checks into a separate validation function or using Zod's custom refinements.

Here's a suggested refactor using Zod's refinements:

const formSchema = z.object({
  keyAuthId: z.string(),
  workspaceId: z.string(),
  defaultPrefix: z.string()
    .refine(value => value.trim() !== '', {
      message: "Default prefix cannot be empty or contain only spaces."
    })
    .refine(value => value.length <= 8, {
      message: "Default prefix is too long, maximum length is 8 characters."
    })
});

// In the component:
const form = useForm<z.infer<typeof formSchema>>({
  resolver: zodResolver(formSchema),
  // ... other options
});

async function onSubmit(values: z.infer<typeof formSchema>) {
  if (values.defaultPrefix === keyAuth.defaultPrefix) {
    toast.error("Please provide a different prefix than the already existing one as default");
    return;
  }
  await setDefaultPrefix.mutateAsync(values);
}

This approach moves most of the validation logic into the schema definition, making it easier to maintain and modify in the future. It also ensures that these validations are applied consistently, both in the form and during submission.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0608fee and 6e45634.

📒 Files selected for processing (1)
  • apps/dashboard/app/(app)/apis/[apiId]/settings/default-prefix.tsx (1 hunks)
🧰 Additional context used
🔇 Additional comments (1)
apps/dashboard/app/(app)/apis/[apiId]/settings/default-prefix.tsx (1)

Line range hint 1-105: Overall, well-implemented component with good validation

The DefaultPrefix component is well-structured and implements proper form handling, validation, and error management. The recent changes to prevent whitespace-only inputs effectively address the reported issue.

Key strengths:

  1. Use of React Hook Form with Zod for robust form management and validation.
  2. Clear separation of concerns between UI components and logic.
  3. Proper error handling and user feedback through toast notifications.
  4. Appropriate use of TRPC for API interactions.

The added validation for whitespace-only inputs enhances the overall robustness of the form. With the suggested minor improvements (consistent error handling and potential refactoring of validation logic), this component will be even more maintainable and aligned with best practices.

@DetrojaRadhey
Copy link

/assign

Copy link

oss-gg bot commented Oct 11, 2024

Assigned to @DetrojaRadhey! Please open a draft PR linking this issue within 48h ⚠️ If we can't detect a PR from you linking this issue in 48h, you'll be unassigned automatically 🕹️ Excited to have you ship this 🚀

@chronark
Copy link
Collaborator

prefixes must not include any whitespace at all

@chronark chronark assigned chronark and unassigned DetrojaRadhey Oct 11, 2024
@Vinod-Mane3021
Copy link
Author

Vinod-Mane3021 commented Oct 11, 2024

I have applied validation for only
Prefix = ""
Prefix = " "

Do you mean validation for below also
Prefix = "a "
Prefix = " a"

@chronark
Copy link
Collaborator

yes,the validation must ensure there is no whitespace in the input field

@harshsbhat
Copy link
Contributor

@Vinod-Mane3021 I am not the maintainer of this repo. But like I commented on the issue. This issue also exists for the

https://app.unkey.com/apis/[api_123]/keys/[ks_123]/new

Currently your code only solves it for the default prefix.

cc: @chronark

@chronark
Copy link
Collaborator

@Vinod-Mane3021 I am not the maintainer of this repo. But like I commented on the issue. This issue also exists for the

https://app.unkey.com/apis/[api_123]/keys/[ks_123]/new

Currently your code only solves it for the default prefix.

cc: @chronark

in addition to that, we must also validate it on the serverside in the trpc handler.

Copy link
Collaborator

@chronark chronark left a comment

Choose a reason for hiding this comment

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

see comments above

@Vinod-Mane3021
Copy link
Author

ill make all changes

@Vinod-Mane3021
Copy link
Author

Vinod-Mane3021 commented Oct 13, 2024

I have added validation for both

  1. Default prefix API Settings
  2. prefix in create api key

in both client and server side

can you review the changes @chronark

@chronark
Copy link
Collaborator

Looks good, please sign the CLA and fix the title

@chronark chronark added the Requires CLA Waiting for a contributor to sign the CLA label Oct 28, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Something isn't working 🕹️ 150 points 🕹️ oss.gg Requires CLA Waiting for a contributor to sign the CLA
Projects
None yet
Development

Successfully merging this pull request may close these issues.

API Setting : "Default Prefix" Field Should Not Allow Only Whitespace Values
6 participants