Skip to content

Conversation

evansharp
Copy link

@evansharp evansharp commented Feb 24, 2025

Oauth uses the Shield-created users.username field to hold the email address of a user registered with oauth.

The default size of this field is just 30 characters, which makes truncation of an email address likley.

In this PR, I've made an addition to the migrations to alter the field to be VARCHAR(100) and added a note in the documentation to highlight the suggestion.

Summary by CodeRabbit

  • Documentation

    • Added a note in the installation guide regarding the default size of the username field, recommending an increase to accommodate email addresses used with OAuth.
  • Chores

    • Updated the database migration to modify the username field to a VARCHAR(256) type, ensuring better support for user authentication.
  • Bug Fixes

    • Adjusted the retrieval of the first name from the user information to use a more specific property for better alignment with the Google API.

Copy link

coderabbitai bot commented Feb 24, 2025

Walkthrough

The changes update the installation documentation and the Shield OAuth migration. The documentation now includes a note that the default username field size may be insufficient when used for email addresses, suggesting an increase to VARCHAR(256). In the migration file, the up method is modified to add a new, nullable username column with type VARCHAR(256) to the users table. The down method remains unchanged.

Changes

File(s) Changes Summary
docs/install.md Added note about the default username field size and recommendation to use VARCHAR(256) for email addresses.
src/Database/Migrations/... Modified the up method to add a new, nullable username column (type VARCHAR(256)) to the users table. The down method remains unchanged.
src/Libraries/GoogleOAuth.php Updated the setColumnsName method to retrieve the first name using $userInfo->given_name instead of $userInfo->name.

Sequence Diagram(s)

sequenceDiagram
    participant M as ShieldOAuth Migration
    participant F as Forge
    M->>F: Call modifyColumn() to add 'username' (VARCHAR(256), nullable)
    F-->>M: Apply column update to users table
Loading

Poem

I'm a bunny dashing through the code,
Hoping changes light a brighter road.
The username field grows, wide and free,
With VARCHAR(256) it dances with glee.
Hoppy cheers as the schema takes a leap!
🐇💻

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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

🔭 Outside diff range comments (1)
src/Database/Migrations/2022-10-20-182737_ShieldOAuth.php (1)

69-78: ⚠️ Potential issue

Add username column reversion in down method.

The down method should revert all changes made in the up method, including the username column modification.

     public function down(): void
     {
+        // Revert username column modification
+        $fields2 = [
+            'username'     => [
+                'type'     => 'VARCHAR(30)',
+                'null'     => true,
+            ]
+        ];
+        $this->forge->modifyColumn('users', $fields2);
+
         $fields = [
             $this->first_name,
             $this->last_name,
             $this->avatar,
         ];

         $this->forge->dropColumn('users', $fields);
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 82f07b6 and 381e76d.

📒 Files selected for processing (2)
  • docs/install.md (1 hunks)
  • src/Database/Migrations/2022-10-20-182737_ShieldOAuth.php (2 hunks)
🧰 Additional context used
🪛 GitHub Check: PHP 8.1 Static Analysis
src/Database/Migrations/2022-10-20-182737_ShieldOAuth.php

[failure] 24-24:
Property Datamweb\ShieldOAuth\Database\Migrations\ShieldOAuth::$username is unused.

🪛 GitHub Actions: PHPCSFixer
src/Database/Migrations/2022-10-20-182737_ShieldOAuth.php

[error] 57-57: PHP CS Fixer: trailing_comma_in_multiline and binary_operator_spaces rule violations. A trailing comma is required in the multiline array and binary operator spacing is incorrect.

🪛 GitHub Actions: Rector
src/Database/Migrations/2022-10-20-182737_ShieldOAuth.php

[warning] 20-20: Skipped rule "Rector\Php73\Rector\FuncCall\JsonThrowOnErrorRector" is never registered. You can remove it from "->withSkip()".

🔇 Additional comments (1)
docs/install.md (1)

55-55: LGTM! Clear and helpful documentation update.

The added note effectively communicates:

  • The current limitation (30 chars default size)
  • The potential issue (email truncation)
  • The solution (increasing to VARCHAR(100))
  • The implementation method (handled by migrations)

@datamweb datamweb added enhancement New feature or request GPG-Signing needed Pull requests that need GPG-Signing labels Feb 25, 2025
Copy link
Owner

@datamweb datamweb left a comment

Choose a reason for hiding this comment

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

Thank you for submitting PR. I have suggested some changes. Please note that you need to register and configure your GPG key according to the instructions below, as pull requests without a signature will not be accepted.

https://docs.github.com/en/authentication/managing-commit-signature-verification/adding-a-gpg-key-to-your-github-account

]
];

$this->forge->modifyColumn('users', $fields2);
Copy link
Owner

Choose a reason for hiding this comment

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

If a developer has already run the migration, executing it again will have no effect because the migration system only detects new migrations.

Therefore, it's best to create a new migration file and apply the necessary changes there, according to what you have done. This ensures that your changes are properly applied to the database without modifying previous migrations.

Copy link
Author

Choose a reason for hiding this comment

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

I don't think that is a problem though. Any developer already using the library will already have handled this short field somehow; if anything, adjusting their table could break their fix.

I think it is something only necessary for a new installation and so updating the existing migration is all that is needed.

@evansharp
Copy link
Author

I have added a PGP key to my account. It will not apply retroactively to this PR though.

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

🔭 Outside diff range comments (1)
src/Database/Migrations/2022-10-20-182737_ShieldOAuth.php (1)

68-77: ⚠️ Potential issue

Update the down method to revert username column changes.

The up() method modifies the username column, but the down() method doesn't include any action to revert this change. This creates an asymmetry in the migration process that could cause issues when rolling back.

Consider updating the down() method to also revert the username column changes:

    public function down(): void
    {
        $fields = [
            $this->first_name,
            $this->last_name,
            $this->avatar,
+           'username',
        ];

        $this->forge->dropColumn('users', $fields);
    }

Alternatively, if you intend to keep the username column but revert its size when rolling back:

    public function down(): void
    {
        $fields = [
            $this->first_name,
            $this->last_name,
            $this->avatar,
        ];

        $this->forge->dropColumn('users', $fields);
+        
+        $fields2 = [
+            'username' => [
+                'type' => 'VARCHAR(30)',
+                'null' => true,
+            ]
+        ];
+        
+        $this->forge->modifyColumn('users', $fields2);
    }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 381e76d and 3e27b27.

📒 Files selected for processing (2)
  • docs/install.md (1 hunks)
  • src/Database/Migrations/2022-10-20-182737_ShieldOAuth.php (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/install.md
🧰 Additional context used
🪛 GitHub Actions: PHPCSFixer
src/Database/Migrations/2022-10-20-182737_ShieldOAuth.php

[error] 56-56: PHP CS Fixer: trailing_comma_in_multiline, binary_operator_spaces issues found. Please fix the formatting.

🔇 Additional comments (1)
src/Database/Migrations/2022-10-20-182737_ShieldOAuth.php (1)

61-61: Consider username nullability requirements.

You've set the username column to allow NULL values. Consider whether this is appropriate for your authentication system. If username is used for authentication or as a unique identifier, it might be better to make it NOT NULL.

-                'null'     => true
+                'null'     => false,

Comment on lines +58 to +63
$fields2 = [
'username' => [
'type' => 'VARCHAR(256)',
'null' => true
]
];
Copy link

@coderabbitai coderabbitai bot Feb 26, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix formatting issues and consider whether modifyColumn is the right approach.

There are several issues with this code block:

  1. Missing trailing comma after true (line 61)
  2. Inconsistent spacing around the equal sign
  3. modifyColumn() will only work if the column already exists, but may fail for new installations where the column doesn't exist yet
        $fields2 = [
            'username'     => [
                'type'     => 'VARCHAR(256)',
-                'null'     => true
+                'null'     => true,
            ]
        ];

Consider using addColumn() with an IF NOT EXISTS check or use a try-catch block to handle cases where the column might not exist yet:

try {
    // Try to modify if exists
    $this->forge->modifyColumn('users', $fields2);
} catch (\Exception $e) {
    // Add if it doesn't exist
    $this->forge->addColumn('users', $fields2);
}

Copy link
Author

Choose a reason for hiding this comment

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

The field as created by CI Shield is nullable, so I maintained that. I would normally not modify this attribute at all, but CI docs for migrations state that nullable is buggy and should be set every time to ensure expected outcome.

Copy link

Choose a reason for hiding this comment

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

@evansharp Thanks for clarifying about maintaining the nullable attribute - that makes sense and aligns with what we already know about CodeIgniter Shield's default behavior.

What about the other issues mentioned in the original comment? Specifically:

  1. The missing trailing comma after true
  2. The concern about using modifyColumn() which might fail for new installations where the column doesn't exist yet

Would you like to address these points as well?


✏️ Learnings added
Learnt from: evansharp
PR: datamweb/shield-oauth#186
File: src/Database/Migrations/2022-10-20-182737_ShieldOAuth.php:58-63
Timestamp: 2025-02-26T23:50:21.777Z
Learning: According to CodeIgniter documentation, the "nullable" attribute in migrations is buggy and should be explicitly set every time to ensure expected behavior, even when not changing this property.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: evansharp
PR: datamweb/shield-oauth#186
File: src/Database/Migrations/2022-10-20-182737_ShieldOAuth.php:0-0
Timestamp: 2025-02-26T23:48:09.146Z
Learning: The username field as created by CodeIgniter Shield is nullable by default, and maintaining this property is important when modifying the field in migrations.

Comment on lines 56 to +57
$this->forge->addColumn('users', $fields);

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the trailing comma formatting issue.

There's a formatting issue reported by PHPCSFixer regarding missing trailing commas.

        $this->forge->addColumn('users', $fields);

        $fields2 = [

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 GitHub Actions: PHPCSFixer

[error] 56-56: PHP CS Fixer: trailing_comma_in_multiline, binary_operator_spaces issues found. Please fix the formatting.

@datamweb
Copy link
Owner

datamweb commented Feb 27, 2025

I have added a PGP key to my account. It will not apply retroactively to this PR though.

If you are using Git, the process for signing previous commits is explained below.
https://github.com/codeigniter4/CodeIgniter4/blob/develop/contributing/workflow.md#gpg-signing-old-commits

If you are not using Git, the simplest solution is to close PR and create a new one.

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

🧹 Nitpick comments (2)
src/Libraries/GoogleOAuth.php (2)

79-92: Consider adding error handling with appropriate user feedback

The current error handling simply exits with the error message, which might not be user-friendly. Consider implementing a more graceful error handling approach that provides meaningful feedback to the user.

try {
    $response = $this->client->request('POST', self::$API_USER_INFO_URL, [
        'headers' => [
            'Accept'        => 'application/json',
            'User-Agent'    => self::$APPLICATION_NAME . '/1.0',
            'Authorization' => 'Bearer ' . $this->getToken(),
        ],
        'http_errors' => false,
    ]);
} catch (Exception $e) {
-    exit($e->getMessage());
+    log_message('error', 'Google OAuth error: ' . $e->getMessage());
+    throw new \RuntimeException('Unable to fetch user information from Google. Please try again later.');
}

52-74: Same error handling improvement needed in fetchAccessTokenWithAuthCode

Similar to the previous comment, improve error handling here as well to provide better user experience.

try {
    // send request to API URL
    $response = $this->client->request('POST', self::$API_TOKEN_URL, [
        'form_params' => [
            'client_id'     => $this->client_id,
            'client_secret' => $this->client_secret,
            'code'          => $allGet['code'],
            'redirect_uri'  => $this->callback_url,
            'grant_type'    => 'authorization_code',
        ],
        'headers' => [
            'User-Agent' => self::$APPLICATION_NAME . '/1.0',
            'Accept'     => 'application/json',
        ],
    ]);
} catch (Exception $e) {
-    exit($e->getMessage());
+    log_message('error', 'Google OAuth token error: ' . $e->getMessage());
+    throw new \RuntimeException('Authentication failed. Please try again later.');
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 84212de and 239a494.

📒 Files selected for processing (1)
  • src/Libraries/GoogleOAuth.php (1 hunks)
🔇 Additional comments (2)
src/Libraries/GoogleOAuth.php (2)

99-99: Correct implementation of Google OAuth user profile field mapping

This change properly aligns the code with Google's OAuth API response structure by using given_name instead of name for the first name. This matches line 112 in the newUser case that already uses given_name, creating consistency throughout the codebase.


108-108:

✅ Verification successful

Confirms the need for increasing the username column size

This line demonstrates why increasing the username column size (as mentioned in the PR objectives) is necessary - the field stores email addresses which can exceed the current 30 character limit.


🏁 Script executed:

#!/bin/bash
# Check for any other places in the codebase where emails are assigned to username
rg "username.+\bemail\b" --type php

Length of output: 150


Email-based username assignment verified

The verification confirms that the only occurrence where an email is assigned to the username field is in src/Libraries/GoogleOAuth.php (line 108). This supports the need for increasing the username column size, as email addresses may exceed the previous 30-character limit.

  • Location: src/Libraries/GoogleOAuth.php (line 108)

datamweb and others added 25 commits April 12, 2025 08:25
Updates the requirements on [rector/rector](https://github.com/rectorphp/rector) to permit the latest version.
- [Release notes](https://github.com/rectorphp/rector/releases)
- [Commits](rectorphp/rector@1.2.5...1.2.6)

---
updated-dependencies:
- dependency-name: rector/rector
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <[email protected]>
Updates the requirements on [rector/rector](https://github.com/rectorphp/rector) to permit the latest version.
- [Release notes](https://github.com/rectorphp/rector/releases)
- [Commits](rectorphp/rector@1.2.8...1.2.10)

---
updated-dependencies:
- dependency-name: rector/rector
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <[email protected]>
Added a new translation file for Brazilian Portuguese (pt-BR). This includes translations for OAuth error messages, button labels, and other related text. It improves localization support for users in Brazil.
Bumps [NexusPHP/no-merge-commits](https://github.com/nexusphp/no-merge-commits) from 2.1.0 to 2.2.1.
- [Release notes](https://github.com/nexusphp/no-merge-commits/releases)
- [Changelog](https://github.com/NexusPHP/no-merge-commits/blob/2.x/CHANGELOG.md)
- [Commits](NexusPHP/no-merge-commits@v2.1.0...v2.2.1)

---
updated-dependencies:
- dependency-name: NexusPHP/no-merge-commits
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <[email protected]>
* 'develop' of github.com:evansharp/shield-oauth: (238 commits)
  fix property name to address datamweb#177
  Coderabbit is kid of annoying eh?
  PR updates based on conversations
  Add to migrations and update docs
  chore(deps): bump NexusPHP/no-merge-commits from 2.1.0 to 2.2.1
  feat: add translation for Brazilian Portuguese (pt-BR)
  chore(deps-dev): update rector/rector requirement from 1.2.8 to 1.2.10
  chore(deps-dev): update rector/rector requirement from 1.2.7 to 1.2.8 (datamweb#178)
  chore(deps-dev): update rector/rector requirement from 1.2.6 to 1.2.7 (datamweb#176)
  chore(deps-dev): update rector/rector requirement from 1.2.5 to 1.2.6
  fix: invalid combination
  fix: func not found, rm require package
  fix: add phpstan-ignore for setting func
  remove unnecessary code
  require codeigniter4/settings
  feat: apply config setting
  fix: ensure ban check for existing users
  chore(deps-dev): update rector/rector requirement from 1.2.4 to 1.2.5 (datamweb#168)
  apply coding standar suggest
  check for blocked users and prevent them from logging in
  ...
@evansharp
Copy link
Author

Fully back-signed my fork... should be good to merge now.

@evansharp evansharp closed this Apr 12, 2025
@evansharp
Copy link
Author

I made a mess of this PR with a commit aimed at #177 . I'm closing this and will try to sort out making two separate PRs. Sorry the back-signing messed this up so much.

evansharp added a commit to evansharp/shield-oauth that referenced this pull request Apr 12, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request GPG-Signing needed Pull requests that need GPG-Signing
Projects
None yet
Development

Successfully merging this pull request may close these issues.