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

Update GithubOAuth.php #123

Closed
wants to merge 1 commit into from
Closed

Update GithubOAuth.php #123

wants to merge 1 commit into from

Conversation

Zoly
Copy link
Contributor

@Zoly Zoly commented Jul 20, 2024

Retrieve the user's email addresses regardless if the email address status is set public or not

Summary by CodeRabbit

  • New Features
    • Improved email retrieval from GitHub, allowing access to the user's primary or alternative email addresses even when not publicly visible.
    • Enhanced user information response now includes the retrieved email address, providing a more comprehensive user profile.

Retrieve the user's email addresses regardless if their status is set public or not
Copy link

coderabbitai bot commented Jul 20, 2024

Walkthrough

The changes to the GithubOAuth class enhance the retrieval of user email addresses from the GitHub API. The updated fetchUserInfoWithToken method now attempts to fetch additional email addresses if the primary email is not available. This ensures that applications can access user emails in more scenarios, significantly improving data handling and user experience.

Changes

File Change Summary
src/Libraries/GithubOAuth.php Improved fetchUserInfoWithToken method to retrieve user email addresses more robustly by adding a second API call if the primary email is not public or missing. The method now returns a modified user info object that includes the retrieved email.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant GithubOAuth
    participant GitHubAPI

    Client->>GithubOAuth: Request user info with token
    GithubOAuth->>GitHubAPI: GET /user
    GitHubAPI-->>GithubOAuth: Return user info (email may be missing)
    alt Email is missing
        GithubOAuth->>GitHubAPI: GET /user/emails
        GitHubAPI-->>GithubOAuth: Return list of emails
        GithubOAuth->>GithubOAuth: Extract primary email or first email
    end
    GithubOAuth-->>Client: Return enriched user info with email
Loading

Poem

🐇 In the meadow where emails bloom,
The GitHub rabbit clears the gloom.
With a hop and a skip, new paths we find,
Fetching emails for all, both gentle and kind.
Now no query shall leave us in dark,
A treasure of emails, we've made our mark! 🌼✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

Outside diff range, codebase verification and nitpick comments (2)
src/Libraries/GithubOAuth.php (2)

95-95: Improve the readability of the comment.

The comment can be made more concise and clear.

- * Note: When making a call to /user, the API will only return the email address the user's explicitly set publicly visible
- * (or null if the user has not specified a public email address in their profile).
+ * Note: The /user API returns only the publicly visible email address or null if none is set.

97-98: Improve the readability of the comment.

The comment can be made more concise and clear.

- * The email address is mandatory we have no other choice but to dig deeper.
+ * Since the email address is mandatory, we need to dig deeper if it's not available.
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 970262b and 881a360.

Files selected for processing (1)
  • src/Libraries/GithubOAuth.php (1 hunks)

Comment on lines +88 to +89

$userInfo = json_decode($response->getBody());
Copy link

Choose a reason for hiding this comment

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

Check for API request success before processing the response.

The response from the GitHub API should be checked for success before attempting to decode the body. This ensures that the code handles errors gracefully.

+ if ($response->getStatusCode() !== 200) {
+     throw new Exception('Failed to fetch user info from GitHub API');
+ }
  $userInfo = json_decode($response->getBody());
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
$userInfo = json_decode($response->getBody());
if ($response->getStatusCode() !== 200) {
throw new Exception('Failed to fetch user info from GitHub API');
}
$userInfo = json_decode($response->getBody());

* so, we'll choose the one marked as primary
* or at least get the first one just to be covered
*/
$userInfo->email = $emailAddresses[0]->email;
Copy link

Choose a reason for hiding this comment

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

Check for empty email addresses array.

Before accessing the first element of the $emailAddresses array, ensure it is not empty to avoid potential errors.

+ if (empty($emailAddresses)) {
+     throw new Exception('No email addresses found for the user');
+ }
  $userInfo->email = $emailAddresses[0]->email;
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
$userInfo->email = $emailAddresses[0]->email;
if (empty($emailAddresses)) {
throw new Exception('No email addresses found for the user');
}
$userInfo->email = $emailAddresses[0]->email;

break;
}
}
}
Copy link

Choose a reason for hiding this comment

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

Handle potential exceptions more gracefully.

Using exit for exception handling is not recommended. Instead, consider logging the error and throwing an exception.

- exit($e->getMessage());
+ log_message('error', $e->getMessage());
+ throw new Exception('Error fetching user info with token');

Committable suggestion was skipped due to low confidence.

Comment on lines +103 to +110
$response = $this->client->request('GET', self::$API_USER_INFO_URL.'/emails', [
'headers' => [
'User-Agent' => self::$APPLICATION_NAME . '/1.0',
'Accept' => 'application/vnd.github+json',
'Authorization' => 'Bearer ' . $this->getToken(),
],
'http_errors' => false,
]);
Copy link

Choose a reason for hiding this comment

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

Check for API request success before processing the response.

The response from the GitHub API should be checked for success before attempting to decode the body. This ensures that the code handles errors gracefully.

+ if ($response->getStatusCode() !== 200) {
+     throw new Exception('Failed to fetch user emails from GitHub API');
+ }
  $emailAddresses = json_decode($response->getBody());
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
$response = $this->client->request('GET', self::$API_USER_INFO_URL.'/emails', [
'headers' => [
'User-Agent' => self::$APPLICATION_NAME . '/1.0',
'Accept' => 'application/vnd.github+json',
'Authorization' => 'Bearer ' . $this->getToken(),
],
'http_errors' => false,
]);
$response = $this->client->request('GET', self::$API_USER_INFO_URL.'/emails', [
'headers' => [
'User-Agent' => self::$APPLICATION_NAME . '/1.0',
'Accept' => 'application/vnd.github+json',
'Authorization' => 'Bearer ' . $this->getToken(),
],
'http_errors' => false,
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Failed to fetch user emails from GitHub API');
}
$emailAddresses = json_decode($response->getBody());

Comment on lines +121 to +126
foreach ( $emailAddresses as $emailAddress ) {
if ($emailAddress->primary) {
$userInfo->email = $emailAddress->email;
break;
}
}
Copy link

Choose a reason for hiding this comment

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

Optimize email address selection logic.

The logic for selecting the primary email address can be optimized by using array_filter and array_shift.

- foreach ( $emailAddresses as $emailAddress ) {
-     if ($emailAddress->primary) {
-         $userInfo->email = $emailAddress->email;
-         break;
-     }
- }
+ $primaryEmail = array_filter($emailAddresses, fn($email) => $email->primary);
+ $userInfo->email = !empty($primaryEmail) ? array_shift($primaryEmail)->email : $emailAddresses[0]->email;
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
foreach ( $emailAddresses as $emailAddress ) {
if ($emailAddress->primary) {
$userInfo->email = $emailAddress->email;
break;
}
}
$primaryEmail = array_filter($emailAddresses, fn($email) => $email->primary);
$userInfo->email = !empty($primaryEmail) ? array_shift($primaryEmail)->email : $emailAddresses[0]->email;

@Zoly Zoly marked this pull request as draft July 20, 2024 06:17
@Zoly Zoly closed this Jul 20, 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.

1 participant