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

file type restricted to jpg jpeg and png fix #1448

Merged
merged 2 commits into from
Sep 30, 2024

Conversation

mithunhegde-egov
Copy link

@mithunhegde-egov mithunhegde-egov commented Sep 30, 2024

file type restricted to jpg jpeg and png fix

Summary by CodeRabbit

  • New Features
    • Enhanced file upload functionality in the Config and Logo Uploader components to accept only specific image formats (.jpg, .png, .jpeg).
  • Bug Fixes
    • Improved user experience by restricting file uploads to valid image types, reducing potential errors during the upload process.

@mithunhegde-egov mithunhegde-egov requested a review from a team as a code owner September 30, 2024 11:57
Copy link
Contributor

coderabbitai bot commented Sep 30, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes involve updates to two components, ConfigUploaderComponent.js and LogoUploaderComponent.js, within the micro-ui application. Both components now include an accept attribute in their Uploader components to restrict file uploads to specific image formats, namely .jpg, .png, and .jpeg. The overall functionality, including file handling and notifications, remains unchanged.

Changes

File Path Change Summary
micro-ui/web/micro-ui-internals/packages/modules/sandbox/src/pages/employee/tenantMgmt/ConfigUploaderComponent.js
micro-ui/web/micro-ui-internals/packages/modules/sandbox/src/pages/employee/tenantMgmt/LogoUploaderComponent.js
Added an accept attribute to the Uploader component to restrict file uploads to image formats .jpg, .png, and .jpeg.

Possibly related PRs

  • Tenant config upload #1416: The LogoUploaderComponent.js and ConfigUploaderComponent.js both involve modifications to the Uploader component to restrict accepted file types, indicating a direct relationship in functionality related to file uploads.

Suggested reviewers

  • nabeelmd-eGov
  • jagankumar-egov

Poem

In the land of code where uploads play,
A rabbit hops with joy today.
With images fine, we now can choose,
No more wrong files, just good news!
Hooray for formats, clear and bright,
Our uploads now feel just right! 🐇✨


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: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 5afff69 and 6fd5b22.

📒 Files selected for processing (2)
  • micro-ui/web/micro-ui-internals/packages/modules/sandbox/src/pages/employee/tenantMgmt/ConfigUploaderComponent.js (1 hunks)
  • micro-ui/web/micro-ui-internals/packages/modules/sandbox/src/pages/employee/tenantMgmt/LogoUploaderComponent.js (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
micro-ui/web/micro-ui-internals/packages/modules/sandbox/src/pages/employee/tenantMgmt/ConfigUploaderComponent.js (1)

Pattern **/*.js: check

micro-ui/web/micro-ui-internals/packages/modules/sandbox/src/pages/employee/tenantMgmt/LogoUploaderComponent.js (1)

Pattern **/*.js: check

🔇 Additional comments (3)
micro-ui/web/micro-ui-internals/packages/modules/sandbox/src/pages/employee/tenantMgmt/LogoUploaderComponent.js (1)

55-55: 🧹 Nitpick (assertive)

🛠️ Refactor suggestion

Refine file type restriction to match PR objective

The addition of the accept attribute is a good step towards restricting file uploads to specific image formats. However, there are a few points to consider:

  1. The current value "image/*, .jpg, .png, .jpeg" allows all image types, which is broader than the PR objective of restricting to JPG, JPEG, and PNG only.
  2. The order of mime types and file extensions can be optimized for clarity.

Consider refining the accept attribute as follows:

-accept="image/*, .jpg, .png, .jpeg"
+accept="image/jpeg, image/png, .jpg, .jpeg, .png"

This change will:

  • Strictly limit uploads to JPG, JPEG, and PNG formats.
  • Improve clarity by listing mime types first, followed by file extensions.

While client-side restrictions are helpful, it's crucial to implement server-side validation as well. This ensures that only the desired file types are processed, even if the client-side restrictions are bypassed.

To ensure this change doesn't conflict with any existing file upload logic, please run the following script:

This script will help identify any other places in the codebase where file types or extensions are being checked, ensuring consistency with this new restriction.

micro-ui/web/micro-ui-internals/packages/modules/sandbox/src/pages/employee/tenantMgmt/ConfigUploaderComponent.js (2)

Line range hint 1-82: Consider refactoring file upload logic into a custom hook

The component currently handles file upload logic, state management for the upload process, and UI rendering. To improve separation of concerns and make the component more maintainable, consider moving the file upload logic into a custom hook.

Here's a high-level suggestion for refactoring:

  1. Create a new file, e.g., useFileUpload.js:
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';

export const useFileUpload = (onSelect) => {
  const [file, setFile] = useState(null);
  const [fileStoreId, setFileStoreId] = useState(null);
  const [showToast, setShowToast] = useState(null);
  const [toastMessage, setToastMessage] = useState('');
  const [isError, setIsError] = useState(false);
  const { t } = useTranslation();
  const tenantId = Digit.ULBService.getCurrentTenantId();

  const handleUploadFile = async () => {
    // ... existing upload logic ...
  };

  useEffect(() => {
    if (file) {
      handleUploadFile();
    }
  }, [file]);

  useEffect(() => {
    if (fileStoreId) {
      onSelect('ConfigUploaderComponent', { fileStoreId, type: 'your_type_here' });
    }
  }, [fileStoreId, onSelect]);

  const selectFile = (files) => setFile(files?.[0]);

  return {
    selectFile,
    showToast,
    toastMessage,
    isError,
    setShowToast,
  };
};
  1. Update the ConfigUploaderComponent to use the new hook:
import { useFileUpload } from './useFileUpload';

const ConfigUploaderComponent = ({ onSelect, ...props }) => {
  const { selectFile, showToast, toastMessage, isError, setShowToast } = useFileUpload(onSelect);

  return (
    <>
      <LabelFieldPair className={'uploader-label-field'}>
        <CardLabel>{`${t('BANNER_UPLOAD')}`}</CardLabel>
        <Uploader
          uploadedFiles={[]}
          variant="uploadFile"
          onUpload={(files) => selectFile(files)}
          accept=".jpg, .jpeg, .png"
        />
      </LabelFieldPair>
      {showToast && (
        <Toast
          error={isError}
          label={toastMessage}
          onClose={() => setShowToast(false)}
        />
      )}
    </>
  );
};

This refactoring would:

  1. Separate concerns, making the component focused on rendering.
  2. Make the file upload logic reusable across components.
  3. Improve testability of both the UI component and the upload logic.

To ensure this refactoring doesn't introduce issues, we should verify the usage of ConfigUploaderComponent:

#!/bin/bash
# Description: Check for usage of ConfigUploaderComponent

# Test: Search for imports and usage of ConfigUploaderComponent
rg --type js 'import.*ConfigUploaderComponent|<ConfigUploaderComponent'

59-59: 🛠️ Refactor suggestion

Refine file type restrictions for better specificity

The addition of the accept attribute is a good step towards meeting the PR objective of restricting file uploads to JPG, JPEG, and PNG formats. However, the current implementation might be too permissive.

Consider modifying the accept attribute to be more specific:

-accept="image/*, .jpg, .png, .jpeg"
+accept=".jpg, .jpeg, .png"

This change will:

  1. Strictly limit uploads to the specified file extensions.
  2. Prevent potential uploads of other image formats (e.g., GIF, WebP) that the current image/* might allow.
  3. Align more closely with the stated PR objective.

To ensure this change doesn't conflict with other parts of the codebase, let's verify the usage:

✅ Verification successful

File Type Restrictions Verified

The proposed modification to the accept attribute has been verified. There are no other Uploader components with accept attributes that might be affected by this change.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other Uploader components that might be affected by this change

# Test: Search for other Uploader components with accept attributes
rg --type js 'Uploader.*accept'

Length of output: 235

@jagankumar-egov jagankumar-egov merged commit facc6d9 into develop Sep 30, 2024
2 checks passed
@jagankumar-egov jagankumar-egov deleted the SN-276-upload-filetype branch September 30, 2024 12:03
This was referenced Oct 1, 2024
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.

3 participants