Skip to content

Added gitlab token #215

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

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

Conversation

Preeti9764
Copy link
Contributor

@Preeti9764 Preeti9764 commented Jul 27, 2025

Fixes #219

Summary of changes:
Added gitlab token in the setting for better support of gitlab and authenticated request made for gitlab for token users.

Summary by Sourcery

Add support for GitLab personal access tokens and enhance GitLab data fetching to use authenticated requests with GraphQL fallback.

New Features:

  • Add GitLab token input field and visibility toggle in extension settings
  • Persist GitLab token to Chrome local storage and load it on startup
  • Allow fetchGitLabData methods to accept and use a GitLab token for authenticated API calls

Enhancements:

  • Implement GraphQL-based fetch in GitLabHelper with automatic fallback to REST
  • Include Authorization headers in REST and MR/issue detail requests when token is provided
  • Extend cache keys to distinguish between public/authenticated and REST/GraphQL fetches
  • Update popup.js and main.js to handle gitlabToken input events and conditionally show GitLab settings based on platform

Summary by Sourcery

Add support for GitLab personal access tokens and integrate authenticated GitLab data fetching with GraphQL fallback.

New Features:

  • Add GitLab token input field and visibility toggle in extension settings
  • Persist GitLab token to Chrome storage and load it on startup
  • Allow fetchGitLabData methods to accept and use a GitLab token for authenticated API calls

Enhancements:

  • Implement GraphQL-based GitLab data fetching with automatic fallback to REST endpoints
  • Include Authorization headers in REST and GraphQL requests when tokens are provided
  • Extend cache keys to distinguish between public vs authenticated and REST vs GraphQL fetches
  • Update popup UI and main script to conditionally show GitHub or GitLab settings based on selected platform

Copy link
Contributor

sourcery-ai bot commented Jul 27, 2025

Reviewer's Guide

This PR adds support for GitLab personal access tokens in the extension settings, persists them to storage, and updates both the CLI and UI layers to make authenticated GitLab requests via GraphQL (with automatic REST fallback). It also adjusts caching logic to account for token usage and conditionally shows GitHub/GitLab configuration sections.

Sequence diagram for authenticated GitLab data fetching with token and fallback

sequenceDiagram
    actor User
    participant Popup
    participant ChromeStorage
    participant GitLabAPI
    User->>Popup: Selects GitLab and enters token
    Popup->>ChromeStorage: Save gitlabToken
    User->>Popup: Requests data fetch (e.g., generate report)
    Popup->>ChromeStorage: Retrieve gitlabToken
    Popup->>GitLabAPI: Fetch data using GraphQL with token
    alt GraphQL fails
      Popup->>GitLabAPI: Fallback to REST API with token
    end
    GitLabAPI-->>Popup: Return data
    Popup-->>User: Display report
Loading

Class diagram for platform-specific settings and UI logic

classDiagram
    class Popup {
      +updatePlatformUI(platform)
      +platformSelect
      +githubTokenSection
      +gitlabTokenSection
    }
    class PlatformSelect {
      +value
      +onChange()
    }
    Popup --> PlatformSelect : listens for changes
    Popup : +show/hide GitHub and GitLab token sections
    Popup : +update username label and org section
    PlatformSelect : +switches between GitHub and GitLab
Loading

Class diagram for cache key and data fetching enhancements

classDiagram
    class CacheManager {
      +repoCache
      +gitlabCache
      +cacheKey (includes token and fetch type)
      +timestamp
    }
    class GitLabHelper {
      +fetchData(token)
      +fetchGraphQL(token)
      +fetchREST(token)
    }
    CacheManager <.. GitLabHelper : uses for caching
    GitLabHelper : +uses Authorization header if token present
    CacheManager : +distinguishes cache by token and fetch type
Loading

File-Level Changes

Change Details Files
Introduce GitLab token input and toggle in settings UI
  • Add GitLab token field and visibility toggle to popup.html
  • Persist and load gitlabToken in popup.js and main.js
  • Toggle GitLab settings section based on selected platform
src/popup.html
src/scripts/popup.js
src/scripts/main.js
Load and handle gitlabToken in scraper logic
  • Include gitlabToken when fetching settings from Chrome storage
  • Pass gitlabToken into allIncluded() and GitLabHelper.fetchGitLabData calls
  • Update allIncluded to reinstantiate GitLabHelper before each run
src/scripts/scrumHelper.js
Enhance GitLabHelper to use authenticated GraphQL with REST fallback
  • Add GraphQL-based fetch with Authorization header when token is present
  • Automatic fallback to REST-based fetch if GraphQL fails or no token
  • Extend cache key to distinguish between public/authenticated and REST/GraphQL fetches
src/scripts/gitlabHelper.js
Adjust caching to consider token usage
  • Tie cache invalidation to token presence by including token flag in cache keys
  • Update save/load storage routines to store and restore token usage state
  • Invalidate cache when token or organization changes
src/scripts/scrumHelper.js
src/scripts/gitlabHelper.js
Conditionally show/hide GitHub/GitLab UI sections
  • Update updatePlatformUI to show GitHub or GitLab token sections
  • Bind platformSelect change handler to synchronize username keys
  • Add CSS classes to hide GitHub-only settings when on GitLab
src/popup.html
src/scripts/popup.js

Assessment against linked issues

Issue Objective Addressed Explanation
#219 Allow users to input and securely store a GitLab personal access token within the application.
#219 Update the GitLab integration logic to use the stored token for authenticated API requests to GitLab, enabling access to private repositories and authenticated features.
#219 Provide clear instructions and UI for users to add or update their GitLab token.

Possibly linked issues

  • Add Gitlab Token  #219: The PR adds GitLab token support, allowing authenticated API calls and GraphQL fallback, which directly resolves the issue of enabling authenticated interactions with GitLab.
  • Add Gitlab Token  #219: The PR adds GitLab token support and integrates GitLab API fetching for merge requests and issues, directly fulfilling the issue's request to add GitLab support to the Scrum Helper extension.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @Preeti9764 - I've reviewed your changes - here's some feedback:

Blocking issues:

  • User controlled data in methods like innerHTML, outerHTML or document.write is an anti-pattern that can lead to XSS vulnerabilities (link)
  • User controlled data in a scrumReport.innerHTML is an anti-pattern that can lead to XSS vulnerabilities (link)

General comments:

  • The GraphQL fetch method currently returns early to the REST fallback, leaving the subsequent caching and response-handling code unreachable—consider removing or refactoring that dead code to clean up the flow.
  • There's a lot of duplicated logic for building headers, handling tokens, and logging between the REST and GraphQL flows—extract common utilities or helper functions to DRY up the implementation.
  • You’ve added very verbose console logging throughout; consider gating these behind a debug flag or trimming down to essential messages to avoid cluttering the console in production.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The GraphQL fetch method currently returns early to the REST fallback, leaving the subsequent caching and response-handling code unreachable—consider removing or refactoring that dead code to clean up the flow.
- There's a lot of duplicated logic for building headers, handling tokens, and logging between the REST and GraphQL flows—extract common utilities or helper functions to DRY up the implementation.
- You’ve added very verbose console logging throughout; consider gating these behind a debug flag or trimming down to essential messages to avoid cluttering the console in production.

## Individual Comments

### Comment 1
<location> `src/scripts/gitlabHelper.js:158` </location>
<code_context>
+        return this.fetchGitLabDataREST(username, startDate, endDate, token);
+      }
+
+      // Process GraphQL response
+      const user = graphqlData.data?.user;
+      if (!user) {
</code_context>

<issue_to_address>
Unreachable code after return in GraphQL branch.

The lines after the return statement won't execute. Please remove or restructure them for clarity and maintainability.
</issue_to_address>

### Comment 2
<location> `src/scripts/scrumHelper.js:288` </location>
<code_context>
-                                    const mappedMRs = (data.mergeRequests || data.mrs || []).map(mr => mapGitLabItem(mr, data.projects, 'mr'));
+
+                                    // Ensure data is not null and has required properties
+                                    if (!data) {
+                                        throw new Error('GitLab data is null or undefined');
+                                    }
+
</code_context>

<issue_to_address>
Error thrown for null data may not be user-friendly.

Consider providing a more descriptive error message or handling null data more gracefully in the UI to improve user experience.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
                                    // Ensure data is not null and has required properties
+                                    if (!data) {
+                                        throw new Error('GitLab data is null or undefined');
+                                    }
=======
                                    // Ensure data is not null and has required properties
+                                    if (!data) {
+                                        // Show a user-friendly message in the UI
+                                        alert('Unable to load GitLab data. Please check your connection or authentication and try again.');
+                                        // Optionally, update a status element in the DOM if available
+                                        const statusElem = document.getElementById('gitlab-status');
+                                        if (statusElem) {
+                                            statusElem.textContent = 'Failed to load GitLab data. Please refresh or check your credentials.';
+                                        }
+                                        return; // Stop further processing
+                                    }
>>>>>>> REPLACE

</suggested_fix>

### Comment 3
<location> `src/scripts/scrumHelper.js:312` </location>
<code_context>
                                         if (scrumReport) {
-                                            scrumReport.innerHTML = `<div class=\"error-message\" style=\"color: #dc2626; font-weight: bold; padding: 10px;\">${err.message || 'An error occurred while fetching GitLab data.'}</div>`;
+                                            const errorMessage = err.message || 'An error occurred while fetching GitLab data.';
+                                            console.error('GitLab error details:', {
+                                                message: err.message,
+                                                stack: err.stack,
+                                                name: err.name
+                                            });
+                                            scrumReport.innerHTML = `<div class=\"error-message\" style=\"color: #dc2626; font-weight: bold; padding: 10px;\">${errorMessage}</div>`;
</code_context>

<issue_to_address>
Console error logging may expose sensitive information.

Restrict detailed error logs to development mode or sanitize output to avoid leaking sensitive data in production.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
                                            console.error('GitLab error details:', {
                                                message: err.message,
                                                stack: err.stack,
                                                name: err.name
                                            });
=======
                                            if (window.NODE_ENV === 'development') {
                                                console.error('GitLab error details:', {
                                                    message: err.message,
                                                    stack: err.stack,
                                                    name: err.name
                                                });
                                            } else {
                                                console.error('An error occurred while fetching GitLab data.');
                                            }
>>>>>>> REPLACE

</suggested_fix>

## Security Issues

### Issue 1
<location> `src/scripts/scrumHelper.js:317` </location>

<issue_to_address>
**security (javascript.browser.security.insecure-document-method):** User controlled data in methods like `innerHTML`, `outerHTML` or `document.write` is an anti-pattern that can lead to XSS vulnerabilities

*Source: opengrep*
</issue_to_address>

### Issue 2
<location> `src/scripts/scrumHelper.js:317` </location>

<issue_to_address>
**security (javascript.browser.security.insecure-innerhtml):** User controlled data in a `scrumReport.innerHTML` is an anti-pattern that can lead to XSS vulnerabilities

*Source: opengrep*
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

stack: err.stack,
name: err.name
});
scrumReport.innerHTML = `<div class=\"error-message\" style=\"color: #dc2626; font-weight: bold; padding: 10px;\">${errorMessage}</div>`;
Copy link
Contributor

Choose a reason for hiding this comment

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

security (javascript.browser.security.insecure-innerhtml): User controlled data in a scrumReport.innerHTML is an anti-pattern that can lead to XSS vulnerabilities

Source: opengrep

@Preeti9764 Preeti9764 self-assigned this Jul 29, 2025
@Preeti9764 Preeti9764 marked this pull request as draft July 30, 2025 07:19
@github-actions github-actions bot added javascript Pull requests that update javascript code core frontend extension labels Jul 31, 2025
@Preeti9764 Preeti9764 marked this pull request as ready for review July 31, 2025 20:28
@Preeti9764
Copy link
Contributor Author

@hpdang @vedansh-5 Please review the gitlab token support is working good .Thanks!

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @Preeti9764 - I've reviewed your changes - here's some feedback:

Blocking issues:

  • User controlled data in methods like innerHTML, outerHTML or document.write is an anti-pattern that can lead to XSS vulnerabilities (link)
  • User controlled data in a scrumReport.innerHTML is an anti-pattern that can lead to XSS vulnerabilities (link)

General comments:

  • The GitLabHelper class has grown very large and mixes GraphQL, REST, caching, and fallback logic—consider extracting each strategy into smaller modules or methods to simplify its responsibilities.
  • The new GitLab token UI in popup.js largely duplicates the GitHub token section—refactor into a reusable token‐input component or helper function to reduce repetition and ensure consistency.
  • There are many scattered console.log calls across the code; consider wrapping them in a debug flag or using a logging utility so you can toggle verbose output in production.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The GitLabHelper class has grown very large and mixes GraphQL, REST, caching, and fallback logic—consider extracting each strategy into smaller modules or methods to simplify its responsibilities.
- The new GitLab token UI in popup.js largely duplicates the GitHub token section—refactor into a reusable token‐input component or helper function to reduce repetition and ensure consistency.
- There are many scattered console.log calls across the code; consider wrapping them in a debug flag or using a logging utility so you can toggle verbose output in production.

## Security Issues

### Issue 1
<location> `src/scripts/scrumHelper.js:319` </location>

<issue_to_address>
**security (javascript.browser.security.insecure-document-method):** User controlled data in methods like `innerHTML`, `outerHTML` or `document.write` is an anti-pattern that can lead to XSS vulnerabilities

*Source: opengrep*
</issue_to_address>

### Issue 2
<location> `src/scripts/scrumHelper.js:319` </location>

<issue_to_address>
**security (javascript.browser.security.insecure-innerhtml):** User controlled data in a `scrumReport.innerHTML` is an anti-pattern that can lead to XSS vulnerabilities

*Source: opengrep*
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@hpdang
Copy link
Member

hpdang commented Aug 8, 2025

@Preeti9764 did you manage to check out the sourcery comments?

Preeti9764 and others added 4 commits August 9, 2025 11:47
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
@Preeti9764
Copy link
Contributor Author

@hpdang I have checked them , now this gitlab token functionality is working fine and ready for merge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
core extension frontend javascript Pull requests that update javascript code
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add Gitlab Token
2 participants