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

Log usage of legacy identities #5893

Merged
merged 1 commit into from
Oct 25, 2024
Merged

Log usage of legacy identities #5893

merged 1 commit into from
Oct 25, 2024

Conversation

jorg-vr
Copy link
Contributor

@jorg-vr jorg-vr commented Oct 25, 2024

This pull request adds logging of usage of legacy sign in methods. If they remain unused for at least 1 month, they will be removed by #5791

@jorg-vr jorg-vr added the chore Repository/build/dependency maintenance label Oct 25, 2024
@jorg-vr jorg-vr self-assigned this Oct 25, 2024
@jorg-vr jorg-vr requested a review from bmesuere as a code owner October 25, 2024 09:14
@bmesuere bmesuere changed the title Log usage of legacy providers Log usage of legacy identities Oct 25, 2024
Copy link

coderabbitai bot commented Oct 25, 2024

Walkthrough

The changes in this pull request involve modifications to user authentication logging, updates to event types in the Event model, and enhancements to localization files for error messages and model attributes in both English and Dutch. Specifically, the Auth::OmniauthCallbacksController now logs sign-in events for legacy identifiers, the Event model has a new enum value, and various error messages have been added or expanded in the localization files to improve clarity for users.

Changes

File Change Summary
app/controllers/auth/omniauth_callbacks_controller.rb Added logging for legacy identifier sign-ins in find_identity_by_uid method.
app/models/event.rb Updated event_type enum to include a new value other mapped to integer 4.
config/locales/models/en.yml Added and expanded error messages for activity, course_membership, api_token, activity_read_state, and gitable. Added other to event_types for the event model.
config/locales/models/nl.yml Added new error messages and statuses, including other in event_types, not_valid in statuses, and clarified status in course_membership.

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>, 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.

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

🧹 Outside diff range and nitpick comments (2)
app/models/event.rb (2)

Line range hint 14-21: Consider adding scopes to support legacy provider analysis.

To facilitate the identification of unused providers after one month, consider adding specific scopes for date-based queries and provider analysis.

Add these scopes to the model:

# Scope to find events within the last month
scope :within_last_month, -> { where('created_at >= ?', 1.month.ago) }

# Scope to find legacy provider usage events
scope :legacy_provider_usage, -> { where(event_type: :legacy_provider_usage) }

# Combined scope for analyzing provider usage
scope :unused_legacy_providers, -> { 
  legacy_provider_usage
    .where('created_at < ?', 1.month.ago)
    .group(:message)
    .having('MAX(created_at) < ?', 1.month.ago)
}

Line range hint 1-13: Consider enhancing the schema for better provider tracking.

The current schema might limit the ability to effectively track provider usage. The message field as string(255) stores the provider information, but this makes it harder to query and analyze specific providers.

Consider adding dedicated fields for provider tracking:

  1. Add a provider field to store the provider name
  2. Add a provider_metadata JSON field for additional tracking data
  3. Index the provider field for better query performance

Example migration:

class EnhanceEventsForProviderTracking < ActiveRecord::Migration[7.0]
  def change
    add_column :events, :provider, :string
    add_column :events, :provider_metadata, :jsonb, default: {}
    add_index :events, :provider
    add_index :events, :created_at  # For date-based queries
  end
end
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e0a056a and 811f718.

📒 Files selected for processing (4)
  • app/controllers/auth/omniauth_callbacks_controller.rb (2 hunks)
  • app/models/event.rb (1 hunks)
  • config/locales/models/en.yml (1 hunks)
  • config/locales/models/nl.yml (1 hunks)
🔇 Additional comments (2)
config/locales/models/nl.yml (1)

179-179: LGTM! Verify the event type usage.

The addition of "other: Overige" as a new event type aligns with the PR objective of logging legacy provider usage. The Dutch translation is appropriate.

Let's verify the usage of this new event type in the codebase:

✅ Verification successful

Let me check the actual content of these files to verify the proper integration of the event type.


Event type integration verified and properly used

The new event type :other is correctly integrated:

  • Defined in the Event model's enum with value 4
  • Used appropriately in the authentication controller to log legacy sign-in attempts for both Office365 and Smartschool providers
  • Has matching translations in both Dutch ("Overige") and English ("Other")
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the new event type is properly integrated
# Expected: Find related event type definition and its usage

# Check for event type definition in models
echo "Checking event type definition..."
rg -l "other" app/models/event.rb

# Check for usage in the authentication controller
echo "Checking usage in auth controller..."
rg -l "other" app/controllers/auth/omniauth_callbacks_controller.rb

# Verify English translation exists
echo "Checking English translation..."
rg "other:" config/locales/models/en.yml

Length of output: 472


Script:

#!/bin/bash
# Check the event type definition in the model
echo "=== Event model definition ==="
rg -A 5 -B 5 "other" app/models/event.rb

# Check how it's used in the controller
echo -e "\n=== Controller usage ==="
rg -A 5 -B 5 "other" app/controllers/auth/omniauth_callbacks_controller.rb

Length of output: 2921

app/controllers/auth/omniauth_callbacks_controller.rb (1)

Line range hint 238-255: Consider adding analytics support for legacy provider usage.

The current implementation logs usage but doesn't fully support the stated goal of removing unused legacy providers after one month of inactivity. Consider these architectural improvements:

  1. Add timestamp tracking in the event data
  2. Create database indexes for efficient querying
  3. Add a background job to analyze usage patterns
  4. Implement automated notifications for unused providers

Let's verify if the Event model supports the required functionality:

Would you like me to propose a detailed implementation for these improvements?

@@ -11,7 +11,7 @@
#

class Event < ApplicationRecord
enum :event_type, { rejudge: 0, permission_change: 1, exercise_repository: 2, error: 3 }
enum :event_type, { rejudge: 0, permission_change: 1, exercise_repository: 2, error: 3, other: 4 }
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Consider using a more specific event type for legacy provider logging.

Using 'other' as the event type for legacy provider usage might make it difficult to track and analyze this specific use case. Consider adding a more descriptive event type like 'legacy_provider_usage' to make the intention clear and facilitate easier querying.

Apply this diff:

- enum :event_type, { rejudge: 0, permission_change: 1, exercise_repository: 2, error: 3, other: 4 }
+ enum :event_type, { rejudge: 0, permission_change: 1, exercise_repository: 2, error: 3, legacy_provider_usage: 4 }
📝 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
enum :event_type, { rejudge: 0, permission_change: 1, exercise_repository: 2, error: 3, other: 4 }
enum :event_type, { rejudge: 0, permission_change: 1, exercise_repository: 2, error: 3, legacy_provider_usage: 4 }

@@ -175,6 +175,7 @@ en:
permission_change: Change in permission level
exercise_repository: Creation of exercise repository
error: Error
other: Other
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Consider using specific event types instead of "other" for tracking legacy providers.

The addition of a generic "other" event type may not align well with the PR's objective of tracking legacy sign-in method usage. To effectively monitor which providers remain unused for a month (as mentioned in PR #5791), consider using specific event types for each legacy provider instead.

Replace the generic "other" with specific provider event types:

-          other: Other
+          legacy_saml_signin: "Legacy SAML Sign-in"
+          legacy_office365_signin: "Legacy Office 365 Sign-in"
+          legacy_smartschool_signin: "Legacy Smartschool Sign-in"
+          legacy_google_signin: "Legacy Google Sign-in"

Committable suggestion was skipped due to low confidence.

Comment on lines +238 to +239
Event.new(event_type: :other, message: 'Office365 user signed in with legacy identifier').save!

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance logging for Office365 legacy identifier usage.

The current logging implementation could be improved in several ways:

  1. Use a more specific event type instead of :other
  2. Include user context in the event message
  3. Handle event creation failures
  4. Add structured data for better analytics

Consider this implementation:

-      Event.new(event_type: :other, message: 'Office365 user signed in with legacy identifier').save!
+      Event.create!(
+        event_type: :legacy_provider_usage,
+        message: "User #{identity.user.email} signed in with Office365 legacy identifier",
+        data: {
+          provider: 'office365',
+          legacy_identifier: identity.identifier,
+          new_identifier: auth_uid,
+          user_id: identity.user_id
+        }
+      )
📝 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
Event.new(event_type: :other, message: 'Office365 user signed in with legacy identifier').save!
Event.create!(
event_type: :legacy_provider_usage,
message: "User #{identity.user.email} signed in with Office365 legacy identifier",
data: {
provider: 'office365',
legacy_identifier: identity.identifier,
new_identifier: auth_uid,
user_id: identity.user_id
}
)

Comment on lines +254 to +255
Event.new(event_type: :other, message: 'Smartschool user signed in with legacy identifier').save!

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Extract duplicated legacy provider logging logic.

The logging code is duplicated between Office365 and Smartschool providers. This should be extracted into a reusable method.

Consider extracting the logging logic:

+    def log_legacy_identifier_usage(identity, provider_name)
+      Event.create!(
+        event_type: :legacy_provider_usage,
+        message: "User #{identity.user.email} signed in with #{provider_name} legacy identifier",
+        data: {
+          provider: provider_name.downcase,
+          legacy_identifier: identity.identifier,
+          new_identifier: auth_uid,
+          user_id: identity.user_id
+        }
+      )
+    end

     def find_identity_by_uid
       # ... existing code ...
       if provider.class.sym == :office365 && auth_email.present?
         # ... existing code ...
         return nil if identity.nil?
-        Event.new(event_type: :other, message: 'Office365 user signed in with legacy identifier').save!
+        log_legacy_identifier_usage(identity, 'Office365')
         # ... existing code ...
       elsif provider.class.sym == :smartschool && auth_username.present?
         # ... existing code ...
         return nil if identity.nil?
-        Event.new(event_type: :other, message: 'Smartschool user signed in with legacy identifier').save!
+        log_legacy_identifier_usage(identity, 'Smartschool')
         # ... existing code ...
       end
       identity
     end

Committable suggestion was skipped due to low confidence.

@jorg-vr jorg-vr merged commit e9ee308 into main Oct 25, 2024
16 checks passed
@jorg-vr jorg-vr deleted the chore/log-events branch October 25, 2024 09:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
chore Repository/build/dependency maintenance
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants