Skip to content

UFAL/File preview no required username and password in UI#960

Merged
milanmajchrak merged 6 commits intodtq-devfrom
ufal/file-preview-no-required-username-and-password-in-UI
May 13, 2025
Merged

UFAL/File preview no required username and password in UI#960
milanmajchrak merged 6 commits intodtq-devfrom
ufal/file-preview-no-required-username-and-password-in-UI

Conversation

@Paurikova2
Copy link
Collaborator

@Paurikova2 Paurikova2 commented May 8, 2025

Phases MP MM MB MR JM Total
ETA 0 0 0 0 0 0
Developing 5 0 0 0 0 0
Review 0 0 0 0 0 0
Total - - - - - 0
ETA est. 0
ETA cust. - - - - - 0

Problem Description

When the file-preview script is run from the UI as a process, user authentication should not be required. The current context user should be used instead. However, when the script is run from the command line, authentication should be required.

What I Did

  1. Removed the email and password options from the script configuration when running as a UI process.
  2. Made the email and password arguments required only if the current user is null.
  3. Used the current user if available; otherwise, authenticated the user using the provided email and password.
  4. Wrote an integration test.

Summary by CodeRabbit

  • Bug Fixes
    • Improved authentication error handling and user feedback for the file preview script.
  • Tests
    • Enhanced integration tests to verify script authentication outcomes and process execution for file preview.
    • Added new REST API test for file preview script process execution and output verification.
  • New Features
    • Added REST API test for file preview script process execution and output verification.
  • Refactor
    • Centralized and streamlined authentication logic for the file preview script.
  • Chores
    • Updated script parameter handling to exclude certain internal options from REST API exposure.

@coderabbitai
Copy link

coderabbitai bot commented May 8, 2025

"""

Walkthrough

The changes refactor and centralize authentication logic for the FilePreview script, renaming fields, consolidating email/password handling into a new method, and updating error handling. Tests are updated to assert exit codes rather than error messages. REST API code is modified to filter out sensitive options, and a new integration test for file-preview process execution is added.

Changes

File(s) Change Summary
dspace-api/src/main/java/org/dspace/scripts/filepreview/FilePreview.java Refactored authentication logic: added a getAuthenticatedEperson(Context) method, renamed authentication fields (emailepersonMail, passwordepersonPassword), centralized error handling, and updated control flow in setup() and internalRun().
dspace-api/src/test/java/org/dspace/scripts/filepreview/FilePreviewIT.java Updated tests to assert the integer return value from ScriptLauncher.handleScript for different authentication and processing scenarios, replacing previous message-based assertions.
dspace-server-webapp/src/main/java/org/dspace/app/rest/converter/ScriptConverter.java Modified REST parameter conversion to skip options "e" and "p" (short names) and "email" and "password" (long names) for the "file-preview" script, preventing them from being included in the REST API parameter list.
dspace-server-webapp/src/test/java/org/dspace/app/rest/ScriptRestRepositoryIT.java Added a new integration test postFilePreviewProcess to verify file-preview script execution via REST API, checking process creation, output log content, and cleanup.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ScriptLauncher
    participant FilePreview
    participant Context
    participant EPersonService

    User->>ScriptLauncher: Launch FilePreview script (with email/password or identifier)
    ScriptLauncher->>FilePreview: setup()
    FilePreview->>FilePreview: getAuthenticatedEperson(context)
    FilePreview->>EPersonService: Find EPerson by identifier or email
    EPersonService-->>FilePreview: EPerson or error
    alt Authentication fails
        FilePreview-->>ScriptLauncher: Throw AuthenticationException
    else Authentication succeeds
        FilePreview->>Context: Set current user
        FilePreview->>FilePreview: internalRun()
    end
    FilePreview-->>ScriptLauncher: Return exit code
    ScriptLauncher-->>User: Script result
Loading

Possibly related PRs

Suggested reviewers

  • milanmajchrak
  • vidiecan

Poem

In the meadow of code where the previews hop,
Authentication's now tidy, no reason to stop!
Fields renamed, logic neat,
REST and tests skip a beat.
With a thump of approval, this rabbit will cheer—
The FilePreview script is safer this year! 🐇✨
"""


📜 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 3b0fcd2 and 4f54bed.

📒 Files selected for processing (1)
  • dspace-api/src/main/java/org/dspace/scripts/filepreview/FilePreview.java (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • dspace-api/src/main/java/org/dspace/scripts/filepreview/FilePreview.java
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: dspace-dependencies / docker-build (linux/amd64, ubuntu-latest, true)
  • GitHub Check: Run Integration Tests
  • GitHub Check: Run Unit Tests
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

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

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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

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

🧹 Nitpick comments (4)
dspace-api/src/main/java/org/dspace/scripts/filepreview/FilePreview.java (3)

93-95: Redundant reads

epersonMail / epersonPassword were already captured above (or could be, see previous comment). Reading them twice is unnecessary and can be dropped once the early assignment is in place.


106-108: Minor style/nit: stray parenthesis & potential NPE

getEperson((context)) has a redundant parenthesis and – in the unlikely event getEperson() returned nullcontext.setCurrentUser(null) followed by getCurrentUser().getEmail() would raise an NPE. Consider a guard clause:

-            context.setCurrentUser(getEperson((context)));
-            handler.logInfo("Authentication by user: " + context.getCurrentUser().getEmail());
+            EPerson currentUser = getEperson(context);
+            context.setCurrentUser(currentUser);
+            handler.logInfo("Authentication by user: " + currentUser.getEmail());

187-205: Handle missing eperson & reuse AuthenticationService result

  1. ePersonService.find(context, getEpersonIdentifier()) may still return null; handle it explicitly to avoid an eventual NPE downstream.
  2. authenticateService.authenticate(...) sets the current user in Context already; the extra context.setCurrentUser() upstream may be redundant.
-        if (getEpersonIdentifier() != null) {
-            return ePersonService.find(context, getEpersonIdentifier());
+        if (getEpersonIdentifier() != null) {
+            EPerson idUser = ePersonService.find(context, getEpersonIdentifier());
+            if (idUser == null) {
+                throw new AuthenticationException("No EPerson found for id: " + getEpersonIdentifier());
+            }
+            return idUser;
         }
dspace-api/src/test/java/org/dspace/scripts/filepreview/FilePreviewIT.java (1)

91-93: Exit-code based assertion only checks half of the story

Relying solely on handleScript’s integer return code hides why the script failed.
Consider also asserting that testDSpaceRunnableHandler.getErrorMessages() contains a meaningful message (e.g. “No eperson options have been provided”) to make the test future-proof and self-documenting.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f79e704 and 2d3a1cf.

📒 Files selected for processing (4)
  • dspace-api/src/main/java/org/dspace/scripts/filepreview/FilePreview.java (6 hunks)
  • dspace-api/src/test/java/org/dspace/scripts/filepreview/FilePreviewIT.java (4 hunks)
  • dspace-server-webapp/src/main/java/org/dspace/app/rest/converter/ScriptConverter.java (2 hunks)
  • dspace-server-webapp/src/test/java/org/dspace/app/rest/ScriptRestRepositoryIT.java (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: dspace-dependencies / docker-build (linux/amd64, ubuntu-latest, true)
  • GitHub Check: Run Integration Tests
  • GitHub Check: Run Unit Tests

@Paurikova2 Paurikova2 requested a review from milanmajchrak May 8, 2025 09:53
@Paurikova2 Paurikova2 requested a review from milanmajchrak May 9, 2025 11:03
Copy link
Collaborator

@milanmajchrak milanmajchrak left a comment

Choose a reason for hiding this comment

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

@Paurikova2 Paurikova2 requested a review from milanmajchrak May 12, 2025 04:46
@milanmajchrak milanmajchrak requested a review from vidiecan May 12, 2025 09:43
@vidiecan vidiecan requested a review from Copilot May 12, 2025 14:36
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR removes the requirement for explicit authentication parameters (username and password) when the file-preview script is executed from the UI, relying instead on the current logged-in user. Key changes include:

  • Removal of email and password options from the UI process in the script configuration.
  • Refactoring of authentication logic in the file-preview script.
  • Updates to integration tests to validate both UI and command line behaviors.

Reviewed Changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
dspace-server-webapp/src/test/java/org/dspace/app/rest/ScriptRestRepositoryIT.java Added a new integration test for file-preview process execution from the UI.
dspace-server-webapp/src/main/java/org/dspace/app/rest/converter/ScriptConverter.java Excludes email and password options for the file-preview script to prevent accidental exposure in the REST API.
dspace-api/src/test/java/org/dspace/scripts/filepreview/FilePreviewIT.java Updated tests to assert correct return codes and log messages for authentication failures and successes.
dspace-api/src/main/java/org/dspace/scripts/filepreview/FilePreview.java Refactored authentication handling by using the current user if available and introducing a new helper method for authentication.
Comments suppressed due to low confidence (1)

dspace-server-webapp/src/main/java/org/dspace/app/rest/converter/ScriptConverter.java:40

  • [nitpick] Consider refactoring the exclusion of email and password options into a separate utility method or configuration to improve readability and ease future modifications.
if ("file-preview".equalsIgnoreCase(scriptConfiguration.getName()) && (Objects.equals(option.getOpt(), "e") || Objects.equals(option.getOpt(), "p") || Objects.equals(option.getLongOpt(), "email") || Objects.equals(option.getLongOpt(), "password"))) {

@milanmajchrak milanmajchrak merged commit 645cf98 into dtq-dev May 13, 2025
11 checks passed
milanmajchrak added a commit that referenced this pull request May 16, 2025
* Fixed browse - the results are not lowercase (#954)

* S3-CESNET direct downloads (#949)

* Return headers for HEAD request - the bitstream download endpoint (#956)

* The bitstream name is encoded in the URL. (#958)

* SWORDv2 issues: Cannot update bitstream of archived Item. The swordv2 url is not composed correctly. Fixed deleting the workspace item when used org.dspace.sword2.WorkflowManagerDefault (#957)

* The file preview process not required username and password in UI (#960)

* Added translation of distribution license for collection to Czech (#952)

* Added dead and deadSince to handle rest (#948)

* Display community and collection handle (#961)

* Embargo during submission not recorded in provenance (#950)

* Allow to access File Downloader for any authorized user (ufal#1199)

* allow.edit.metadata property should also work for submitters that are members of collection SUBMIT subgroup (ufal#1202)

* Prevent error 500 for non admin user uploading file to bundle (ufal#1205)

* Track downloads as pageviews (ufal#1209)

* Loading the bitstreams - performance issue (ufal#1211)
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.

UFAL/File preview - username and password should not be required in the UI process

4 participants