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

Error while signing on using Discord if no avatar #1649 #1650

Merged
merged 4 commits into from
Jul 2, 2024

Conversation

venkatesh2k3
Copy link
Contributor

Description

Changes Made:
Enhanced handling of the avatar field in SignOnControllerDiscord.java to ensure robust behavior when the avatar is missing or not a string.

Details:

I added validation to check for the avatar field in the JSON response, implemented logic to handle empty or non-string avatar fields, and introduced a default avatar URL fallback mechanism.

Impact:

This update ensures the application handles sign-on scenarios without Discord avatars gracefully and consistently, providing a stable user experience.

Testing:

Tested locally to verify functionality across different scenarios (avatar present, empty avatar).

Note:

The default avatar URL (https://e7.pngegg.com/pngimages/84/165/png-clipart-united-states-avatar-organization-information-user-avatar-service-computer-wallpaper-thumbnail.png) used in this implementation can be replaced with an actual URL pointing to a suitable default image for the application.

@venkatesh2k3 venkatesh2k3 requested a review from a team as a code owner June 30, 2024 09:17
Copy link
Contributor

coderabbitai bot commented Jun 30, 2024

Walkthrough

The changes focus predominantly on the SignOnControllerDiscord class, particularly in refining how the handleCallback method processes the avatar field from the JSON response. It now correctly handles cases where the avatar field is null, empty, or not provided, ensuring the image URL is set appropriately. Additionally, in the sign-on.jsp file, the Google sign-on section is replaced with a new service sign-on section.

Changes

File Path Change Summary
src/main/java/.../SignOnControllerDiscord.java The handleCallback method now handles the avatar field more robustly, checking if it is null, empty, or not provided, and adjusts the image URL accordingly.
src/main/webapp/WEB-INF/jsp/sign-on.jsp Removed section related to Google sign-on and added a new section for signing on with another service.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Browser
    participant Discord
    participant SignOnController

    User->>Browser: Accesses Sign-On Page
    Browser->>Discord: Initiates OAuth Login
    Discord-->>Browser: Redirects with Callback (OAuth Code)
    Browser->>SignOnController: Sends Callback with OAuth Code
    SignOnController->>Discord: Gets User Info with OAuth Code
    Discord-->>SignOnController: Returns User Info (JSON)
    SignOnController->>SignOnController: Processes Avatar Field
    Note right of SignOnController: Checks if `avatar` is null or empty
    SignOnController-->>Browser: Returns Sign-On Response
    Browser->>User: Displays Sign-On Result
Loading

Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2e676b4 and 4e4d750.

Files selected for processing (1)
  • src/main/java/ai/elimu/web/SignOnControllerDiscord.java (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/main/java/ai/elimu/web/SignOnControllerDiscord.java
Additional context used
Learnings (1)
Common learnings
Learnt from: jo-elimu
PR: elimu-ai/webapp#1650
File: src/main/java/ai/elimu/web/SignOnControllerDiscord.java:137-137
Timestamp: 2024-07-02T09:44:13.475Z
Learning: Generate unit tests for new logic handling the avatar field in `SignOnControllerDiscord.java` to cover scenarios where the avatar field is present and valid, absent, and explicitly set to `null`.
Learnt from: jo-elimu
PR: elimu-ai/webapp#1650
File: src/main/java/ai/elimu/web/SignOnControllerDiscord.java:137-137
Timestamp: 2024-07-02T09:38:36.021Z
Learning: Generate unit tests for new logic handling the avatar field in `SignOnControllerDiscord.java` to cover scenarios where the avatar field is present and valid, and where it is absent.

Tip

Early access features: enabled

We are currently testing the following features in early access:

  • OpenAI gpt-4o model for code reviews and chat: OpenAI claims that this model is better at understanding and generating code than the previous models. We seek your feedback over the next few weeks before making it generally available.

Note:

  • You can enable or disable early access features from the CodeRabbit UI or by updating the CodeRabbit configuration file.
  • Please join our Discord Community to provide feedback and report issues.
  • OSS projects are currently opted into early access features by default.

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 Configration 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

Outside diff range and nitpick comments (1)
src/main/java/ai/elimu/web/SignOnControllerDiscord.java (1)

Line range hint 58-58: Remove hardcoded API key.

The API key should not be hardcoded in the source code. Use environment variables or a secure configuration management system to store and retrieve the API key.

// Example of using environment variables
String clientSecret = System.getenv("DISCORD_API_SECRET");
if (clientSecret == null) {
    throw new IllegalStateException("DISCORD_API_SECRET environment variable not set");
}

src/main/java/ai/elimu/web/SignOnControllerDiscord.java Outdated Show resolved Hide resolved
coderabbitai[bot]
coderabbitai bot previously approved these changes Jun 30, 2024
Copy link

codecov bot commented Jun 30, 2024

Codecov Report

Attention: Patch coverage is 0% with 2 lines in your changes missing coverage. Please review.

Project coverage is 13.78%. Comparing base (4862d8d) to head (4e4d750).

Files Patch % Lines
...ain/java/ai/elimu/web/SignOnControllerDiscord.java 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff            @@
##               main    #1650   +/-   ##
=========================================
  Coverage     13.78%   13.78%           
  Complexity      454      454           
=========================================
  Files           257      257           
  Lines          8503     8503           
  Branches        881      881           
=========================================
  Hits           1172     1172           
  Misses         7279     7279           
  Partials         52       52           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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

src/main/java/ai/elimu/web/SignOnControllerDiscord.java Outdated Show resolved Hide resolved
coderabbitai[bot]
coderabbitai bot previously approved these changes Jun 30, 2024
Copy link
Member

@jo-elimu jo-elimu left a comment

Choose a reason for hiding this comment

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

See if you can solve it with less code.

src/main/java/ai/elimu/web/SignOnControllerDiscord.java Outdated Show resolved Hide resolved
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

Outside diff range and nitpick comments (1)
src/main/java/ai/elimu/web/SignOnControllerDiscord.java (1)

Line range hint 58-58: Externalize client secrets to configuration files or environment variables.

Hardcoding client secrets is a security risk. Consider moving them to configuration files or environment variables.

- String clientSecret = "Lf0O65Zk0Qv9cXyC7igPgljIjSJJBZbv";
+ String clientSecret = ConfigHelper.getProperty("discord.api.secret.dev");

src/main/java/ai/elimu/web/SignOnControllerDiscord.java Outdated Show resolved Hide resolved
coderabbitai[bot]
coderabbitai bot previously approved these changes Jun 30, 2024
@venkatesh2k3 venkatesh2k3 requested a review from jo-elimu June 30, 2024 09:52
@venkatesh2k3 venkatesh2k3 requested a review from jo-elimu June 30, 2024 10:04
Copy link
Member

@jo-elimu jo-elimu left a comment

Choose a reason for hiding this comment

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

@venkatesh2k3 It should be possible to fix this bug with one or two lines of code, to keep the amount of code to a minimum.

Do you think it would work to replace jsonObject.has("avatar") with something like jsonObject.has("avatar") && !StringUtils.isBlank(jsonObject.get("avatar"))?

I haven't seen a sample of what the JSON response looks like when the bug occurs, but maybe this additional check would work?

Or maybe jsonObject.has("avatar") && (jsonObject.get("avatar") instanceof String)?

@venkatesh2k3
Copy link
Contributor Author

venkatesh2k3 commented Jun 30, 2024

@venkatesh2k3 It should be possible to fix this bug with one or two lines of code, to keep the amount of code to a minimum.

Do you think it would work to replace jsonObject.has("avatar") with something like jsonObject.has("avatar") && !StringUtils.isBlank(jsonObject.get("avatar"))?

I don't know what the JSON response looks like when the bug occurs, but maybe this additional check would work?

Or maybe jsonObject.has("avatar") && (jsonObject.get("avatar") instanceof String)?

Yeah it will optimize the code @jo-elimu

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

Outside diff range and nitpick comments (1)
src/main/java/ai/elimu/web/SignOnControllerDiscord.java (1)

Line range hint 58-58: Remove hardcoded API keys.

Detected a Generic API Key, potentially exposing access to various services and sensitive operations. Store sensitive data in environment variables or a secure vault.

- String clientSecret = "Lf0O65Zk0Qv9cXyC7igPgljIjSJJBZbv";
+ String clientSecret = ConfigHelper.getProperty("discord.api.secret");
Tools
GitHub Check: codecov/patch

[warning] 137-141: src/main/java/ai/elimu/web/SignOnControllerDiscord.java#L137-L141
Added lines #L137 - L141 were not covered by tests


[warning] 143-143: src/main/java/ai/elimu/web/SignOnControllerDiscord.java#L143
Added line #L143 was not covered by tests

src/main/java/ai/elimu/web/SignOnControllerDiscord.java Outdated Show resolved Hide resolved
jo-elimu
jo-elimu previously approved these changes Jun 30, 2024
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

Outside diff range and nitpick comments (1)
src/main/java/ai/elimu/web/SignOnControllerDiscord.java (1)

Line range hint 58-58: Remove or secure the exposed API key.

A generic API key is detected, which could potentially expose access to various services and sensitive operations. Ensure this key is secured.

- String clientSecret = "Lf0O65Zk0Qv9cXyC7igPgljIjSJJBZbv";
+ String clientSecret = ConfigHelper.getProperty("discord.api.secret");

src/main/java/ai/elimu/web/SignOnControllerDiscord.java Outdated Show resolved Hide resolved
@venkatesh2k3 venkatesh2k3 requested a review from jo-elimu June 30, 2024 12:03
coderabbitai[bot]
coderabbitai bot previously approved these changes Jun 30, 2024
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: 2

Outside diff range and nitpick comments (1)
src/main/java/ai/elimu/web/SignOnControllerDiscord.java (1)

Line range hint 58-58: Avoid hardcoding API keys.

Detected a Generic API Key, potentially exposing access to various services and sensitive operations. Store the API key securely using environment variables or a secrets management service.

- String clientSecret = "Lf0O65Zk0Qv9cXyC7igPgljIjSJJBZbv";
+ String clientSecret = System.getenv("DISCORD_API_SECRET");

src/main/java/ai/elimu/web/SignOnControllerDiscord.java Outdated Show resolved Hide resolved
Copy link
Member

@jo-elimu jo-elimu left a comment

Choose a reason for hiding this comment

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

Still no indentation. Maybe a tabs vs spaces problem? I think the default in this project is using 4 spaces instead of tabs.

image

coderabbitai[bot]
coderabbitai bot previously approved these changes Jul 1, 2024
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: 3

Comment on lines 137 to 142
if (!jsonObject.isNull("avatar")) {
String uriAvatar = "https://cdn.discordapp.com/avatars/" + jsonObject.getLong("id") + "/" + jsonObject.getString("avatar") + ".png";
logger.info(uriAvatar);
logger.info("Avatar URL: " + uriAvatar);
contributor.setImageUrl(uriAvatar);
}

Copy link
Contributor

Choose a reason for hiding this comment

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

Enhance validation for the avatar field and extract the default avatar URL into a constant.

The current implementation only checks if the avatar field is not null. It should also check if the field is a non-empty string to ensure robustness. Additionally, extract the default avatar URL into a constant to avoid duplication and improve maintainability.

private static final String DEFAULT_AVATAR_URL = "https://e7.pngegg.com/pngimages/84/165/png-clipart-united-states-avatar-organization-information-user-avatar-service-computer-wallpaper-thumbnail.png";

// Usage in the method
if (jsonObject.has("avatar") && jsonObject.get("avatar") instanceof String && !StringUtils.isBlank(jsonObject.getString("avatar"))) {
    String avatar = jsonObject.getString("avatar");
    String uriAvatar = "https://cdn.discordapp.com/avatars/" + jsonObject.getLong("id") + "/" + avatar + ".png";
    logger.info("Avatar URL: " + uriAvatar);
    contributor.setImageUrl(uriAvatar);
} else {
    logger.info("Avatar field is missing, not a string, or is blank.");
    contributor.setImageUrl(DEFAULT_AVATAR_URL);
}
Tools
GitHub Check: codecov/patch

[warning] 139-139: src/main/java/ai/elimu/web/SignOnControllerDiscord.java#L139
Added line #L139 was not covered by tests

Comment on lines 143 to 154

if (!jsonObject.isNull("avatar")) {
String uriAvatar = "https://cdn.discordapp.com/avatars/" + jsonObject.getLong("id") + "/" + jsonObject.getString("avatar") + ".png";
logger.info("Avatar URL: " + uriAvatar);
contributor.setImageUrl(uriAvatar);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove redundant code.

The logic to handle the avatar field is duplicated and should be removed.

-            if (!jsonObject.isNull("avatar")) {
-            	String uriAvatar = "https://cdn.discordapp.com/avatars/" + jsonObject.getLong("id") + "/" + jsonObject.getString("avatar") + ".png";
-            	logger.info("Avatar URL: " + uriAvatar);
-            	contributor.setImageUrl(uriAvatar);
-            }
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
if (!jsonObject.isNull("avatar")) {
String uriAvatar = "https://cdn.discordapp.com/avatars/" + jsonObject.getLong("id") + "/" + jsonObject.getString("avatar") + ".png";
logger.info("Avatar URL: " + uriAvatar);
contributor.setImageUrl(uriAvatar);
}
Tools
GitHub Check: codecov/patch

[warning] 145-147: src/main/java/ai/elimu/web/SignOnControllerDiscord.java#L145-L147
Added lines #L145 - L147 were not covered by tests

@venkatesh2k3 venkatesh2k3 force-pushed the main branch 2 times, most recently from 45befbe to 674a67b Compare July 2, 2024 09:08
coderabbitai[bot]
coderabbitai bot previously requested changes Jul 2, 2024
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: 2

Copy link
Member

@jo-elimu jo-elimu left a comment

Choose a reason for hiding this comment

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

@venkatesh2k3 venkatesh2k3 requested a review from jo-elimu July 2, 2024 10:02
Copy link
Member

@jo-elimu jo-elimu left a comment

Choose a reason for hiding this comment

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

Ready to merge 👍🏽

@venkatesh2k3 venkatesh2k3 merged commit 0e3ec41 into elimu-ai:main Jul 2, 2024
7 of 8 checks passed
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.

2 participants