Skip to content

Created script just for calling the login/logout endpoint#213

Open
milanmajchrak wants to merge 1 commit intomainfrom
login-requests-script
Open

Created script just for calling the login/logout endpoint#213
milanmajchrak wants to merge 1 commit intomainfrom
login-requests-script

Conversation

@milanmajchrak
Copy link
Collaborator

@milanmajchrak milanmajchrak commented Jul 2, 2025

Phases MS MM MK JR JM Total
ETA 0 0 0 0 0 0
Developing 0 0 0 0 0 0
Review 0 0 0 0 0 0
Total - - - - - 0
ETA est. 0
ETA cust. - - - - - 0

Problem description

Related to this issue: https://github.com/dataquest-dev/dspace-customers/issues/156

Summary by CodeRabbit

  • New Features
    • Introduced a script to perform and log multiple authentication attempts using backend credentials.

@coderabbitai
Copy link

coderabbitai bot commented Jul 2, 2025

Walkthrough

A new script, login_requests.py, has been added under tools/policy_and_auth/. The script configures the environment, sets up logging, initializes a backend client with credentials from environment variables, and performs nine authentication attempts, logging each attempt. Some code for logging out is present but commented out.

Changes

File(s) Change Summary
tools/policy_and_auth/login_requests.py New script added to perform multiple authentication attempts using a backend client and logging.

Poem

A script hops in with a login spree,
Nine times it knocks, as busy as can be.
Credentials in paw, it logs each quest,
With commented-out logout, it takes a rest.
In the warren of code, new paths are spun—
Another day’s work, another run! 🐇

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Pylint (3.3.7)
tools/policy_and_auth/login_requests.py
✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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: 2

🧹 Nitpick comments (2)
tools/policy_and_auth/login_requests.py (2)

5-8: Consider making path resolution more robust.

The current path manipulation using relative paths (../../) can be brittle if the script is moved or executed from different working directories. Consider using more robust path resolution or packaging the dependencies properly.

-_this_dir = os.path.dirname(os.path.abspath(__file__))
-path_to_dspace_lib = os.path.join(_this_dir, "../../libs/dspace-rest-python")
-sys.path.insert(0, path_to_dspace_lib)
-sys.path.insert(0, os.path.join(_this_dir, "../../src"))
+_this_dir = os.path.dirname(os.path.abspath(__file__))
+_root_dir = os.path.join(_this_dir, "../..")
+path_to_dspace_lib = os.path.join(_root_dir, "libs/dspace-rest-python")
+path_to_src = os.path.join(_root_dir, "src")
+
+if os.path.exists(path_to_dspace_lib):
+    sys.path.insert(0, path_to_dspace_lib)
+if os.path.exists(path_to_src):
+    sys.path.insert(0, path_to_src)

26-29: Complete the logout implementation or remove the commented code.

The commented logout functionality suggests incomplete implementation. Either implement it properly or remove the dead code to keep the script clean.

If logout testing is needed, implement it properly:

-        # Call logout every 5th request
-        # if i % 5 == 0:
-        #     dspace_be.client.logout()
-        #     print("Logged out")
+        # Call logout every 5th request for testing session management
+        logout_interval = int(os.environ.get("LOGOUT_INTERVAL", "0"))
+        if logout_interval > 0 and i % logout_interval == 0:
+            try:
+                dspace_be.client.logout()
+                _logger.info(f"Logged out after {i} attempts")
+            except Exception as e:
+                _logger.error(f"Logout failed: {e}")

Or remove it entirely if not needed:

-        # Call logout every 5th request
-        # if i % 5 == 0:
-        #     dspace_be.client.logout()
-        #     print("Logged out")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 72af738 and 02b87e4.

📒 Files selected for processing (1)
  • tools/policy_and_auth/login_requests.py (1 hunks)

Comment on lines +15 to +16
env = update_settings(settings.env, project_settings.settings)
init_logging(_logger, env["log_file"])
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add validation for required environment variables.

The script assumes required credentials exist in the environment but doesn't validate them. This could lead to unclear error messages if configuration is missing.

 env = update_settings(settings.env, project_settings.settings)
 init_logging(_logger, env["log_file"])

+# Validate required environment variables
+required_keys = ["backend.endpoint", "backend.user", "backend.password"]
+missing_keys = []
+for key in required_keys:
+    keys = key.split('.')
+    value = env
+    try:
+        for k in keys:
+            value = value[k]
+        if not value:
+            missing_keys.append(key)
+    except (KeyError, TypeError):
+        missing_keys.append(key)
+
+if missing_keys:
+    _logger.error(f"Missing required environment variables: {missing_keys}")
+    sys.exit(1)

Also applies to: 21-21

🤖 Prompt for AI Agents
In tools/policy_and_auth/login_requests.py at lines 15-16 and line 21, the code
uses environment variables without validating their presence, which can cause
unclear errors. Add explicit checks after loading the environment to verify that
all required environment variables are set. If any are missing, raise a clear
exception or log an error indicating which variables are absent before
proceeding with the rest of the script.

Comment on lines +21 to +24
dspace_be = dspace.rest(env["backend"]["endpoint"], env["backend"]["user"], env["backend"]["password"], True)
for i in range(1, 10):
_logger.info(f"Authenticating {i}")
dspace_be.client.authenticate()
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling and make the loop count configurable.

The authentication loop lacks error handling and uses a hard-coded count. This could cause the script to fail silently or make it difficult to customize for different testing scenarios.

-    dspace_be = dspace.rest(env["backend"]["endpoint"], env["backend"]["user"], env["backend"]["password"], True)
-    for i in range(1, 10):
-        _logger.info(f"Authenticating {i}")
-        dspace_be.client.authenticate()
+    try:
+        dspace_be = dspace.rest(env["backend"]["endpoint"], env["backend"]["user"], env["backend"]["password"], True)
+        
+        # Make loop count configurable via environment variable
+        loop_count = int(os.environ.get("AUTH_LOOP_COUNT", "9"))
+        
+        for i in range(1, loop_count + 1):
+            _logger.info(f"Authenticating attempt {i}/{loop_count}")
+            try:
+                dspace_be.client.authenticate()
+                _logger.info(f"Authentication attempt {i} successful")
+            except Exception as e:
+                _logger.error(f"Authentication attempt {i} failed: {e}")
+                
+    except Exception as e:
+        _logger.error(f"Failed to initialize DSpace backend: {e}")
+        sys.exit(1)
📝 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
dspace_be = dspace.rest(env["backend"]["endpoint"], env["backend"]["user"], env["backend"]["password"], True)
for i in range(1, 10):
_logger.info(f"Authenticating {i}")
dspace_be.client.authenticate()
try:
dspace_be = dspace.rest(
env["backend"]["endpoint"],
env["backend"]["user"],
env["backend"]["password"],
True
)
# Make loop count configurable via environment variable
loop_count = int(os.environ.get("AUTH_LOOP_COUNT", "9"))
for i in range(1, loop_count + 1):
_logger.info(f"Authenticating attempt {i}/{loop_count}")
try:
dspace_be.client.authenticate()
_logger.info(f"Authentication attempt {i} successful")
except Exception as e:
_logger.error(f"Authentication attempt {i} failed: {e}")
except Exception as e:
_logger.error(f"Failed to initialize DSpace backend: {e}")
sys.exit(1)
🤖 Prompt for AI Agents
In tools/policy_and_auth/login_requests.py around lines 21 to 24, the
authentication loop uses a hard-coded count of 9 and lacks error handling.
Modify the code to make the loop count configurable via a parameter or
environment variable, and wrap the authentication call in a try-except block to
catch and log any exceptions during authentication attempts.

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.

1 participant