datamweb / shield-oauth

OAuth for CodeIgniter Shield
https://www.shield-oauth.codeigniter4.ir/
MIT License
61 stars 16 forks source link

feat: add support for microsoft services #171

Open warcooft opened 2 months ago

warcooft commented 2 months ago

Official support for Microsoft services.

If you have any questions feel free to ask. Thanks.

Summary by CodeRabbit

coderabbitai[bot] commented 2 months ago

[!WARNING]

Rate limit exceeded

@warcooft has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 19 minutes and 8 seconds before requesting another review.

How to resolve this issue? After the wait time has elapsed, a review can be triggered using the `@coderabbitai review` command as a PR comment. Alternatively, push new commits to this PR. We recommend that you space out your commits to avoid hitting the rate limit.
How do rate limits work? CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our [FAQ](https://coderabbit.ai/docs/faq) for further information.
Commits Files that changed from the base of the PR and between 082657b9662aa7815db37b49b2ad09412b601b2f and 28960c2f9d7bb0ebe91c24f3436341458b2b9143.

Walkthrough

The changes introduced in the pull request enhance the documentation and functionality of the OAuth library by adding support for Microsoft OAuth. This includes updates to the documentation files to clarify the process of obtaining OAuth keys and integrating Microsoft OAuth. A new MicrosoftOAuth class has been created to manage Microsoft OAuth 2.0 authentication, providing methods for generating authorization links, fetching access tokens, and retrieving user information.

Changes

Files Change Summary
docs/get_keys.md Added section for Microsoft keys, improved formatting, and clarified instructions for key acquisition.
src/Libraries/MicrosoftOAuth.php Created a new class MicrosoftOAuth to manage Microsoft OAuth 2.0 authentication processes.

Possibly related PRs

Poem

🐰 In the garden of code, a new path we weave,
With Microsoft OAuth, we joyfully believe.
Keys and tokens, in harmony they play,
A dance of integration, brightening the day.
Hops of delight as users connect,
In this world of OAuth, we all can reflect! 🌼


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 - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)
Tips ### Chat There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai): - Review comments: Directly reply to a review comment made by CodeRabbit. Example: - `I pushed a fix in commit .` - `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 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](https://docs.coderabbit.ai/guides/configure-coderabbit) 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](https://coderabbit.ai/docs) for detailed information on how to use CodeRabbit. - Join our [Discord Community](https://discord.com/invite/GsXnASn26c) to get help, request features, and share feedback. - Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.
datamweb commented 2 months ago

Need update : 1- REDME file. 2- Libraries/Basic/ShieldOAuth.php https://github.com/datamweb/shield-oauth/blob/4d31367f366e400aa14419c34614487dad25ed73/src/Libraries/Basic/ShieldOAuth.php#L87-L148

warcooft commented 2 months ago

Microsoft oauth by default does not provide avatar in its payload, if we want it we can fetch it from a different endpoint.

example:

private static $API_USER_AVATAR_URL = 'https://graph.microsoft.com/v1.0/me/photos/240x240/$value';

private function getUserAvatarWithToken(): string|null
{
     try {
         $response = $this->client->request('GET', self::$API_USER_AVATAR_URL, [
             'headers' => [
                 'Authorization' => 'Bearer ' . $this->getToken(),
                 'Content-Type'  => 'image/jpg',
             ],
             'http_errors' => false,
         ]);
     } catch (Exception $e) {
         die($e->getMessage());
     }

     $body   = $response->getBody();
     $base64 = base64_encode($body);
     $avatar = $this->createAvatar($base64);

     return $avatar;
}

private function createAvatar(string $base64, string $pathToSave = 'ShieldOauth/avatar/', string|null $newName = null): string|null
{
    helper('text');

    $decodedBase64 = base64_decode($base64);

    if ($decodedBase64 === false) {
        return null;
    }

    $pathToSave .= date('Y/m/');

    $newName = $newName ?? 'avatar_' . random_string('alnum', 8) . '.jpg';

    if (!is_dir($pathToSave) && !mkdir($pathToSave, 0777, true)) {
        return null; 
    }

    if (file_put_contents($pathToSave . $newName, $decodedBase64) === false) {
        return null;
    }

    return $pathToSave . $newName;
}

then in fetchUserInfoWithToken()

protected function fetchUserInfoWithToken(): object
{
     try {
         $response = $this->client->request('GET', 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());
     }

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

     $userInfo->email  = $userInfo->mail;
     $userInfo->avatar = $this->getUserAvatarWithToken(); // add this

     return $userInfo;
}
datamweb commented 2 months ago

Microsoft oauth by default does not provide avatar in its payload, if we want it we can fetch it from a different endpoint.

See: https://github.com/datamweb/shield-oauth/discussions/106#discussioncomment-9425096

warcooft commented 2 months ago

Do you mean we should save the base64 data in the avatar column instead of just saving the file path?

datamweb commented 2 months ago

Hi, and thanks for the submitted PR! Could you please look into how other packages(Laravel Socialite, Hybridauth,Python Social Auth,Passport.js) handle avatar management? This information could help us choose the best approach for implementation.

warcooft commented 2 months ago

I think the avatar column should be left null, if anyone wants to implement avatar, they can send PR.