diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index c68765b0..f12296bb 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1 +1 @@ -github: :vendor_name +github: OpenSeaWave diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 64742956..7edea54b 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,11 +1,11 @@ blank_issues_enabled: false contact_links: - name: Ask a question - url: https://github.com/:vendor_slug/:package_name/discussions/new?category=q-a + url: https://github.com/openseawave/keycloak/discussions/new?category=q-a about: Ask the community for help - name: Request a feature - url: https://github.com/:vendor_slug/:package_name/discussions/new?category=ideas + url: https://github.com/openseawave/keycloak/discussions/new?category=ideas about: Share ideas for new features - name: Report a security issue - url: https://github.com/:vendor_slug/:package_name/security/policy + url: https://github.com/openseawave/keycloak/security/policy about: Learn how to notify us for sensitive bugs diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index 39b15807..00000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,19 +0,0 @@ -# Please see the documentation for all configuration options: -# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates - -version: 2 -updates: - - - package-ecosystem: "github-actions" - directory: "/" - schedule: - interval: "weekly" - labels: - - "dependencies" - - - package-ecosystem: "composer" - directory: "/" - schedule: - interval: "weekly" - labels: - - "dependencies" diff --git a/.github/workflows/dependabot-auto-merge.yml b/.github/workflows/dependabot-auto-merge.yml deleted file mode 100644 index c3ad22d6..00000000 --- a/.github/workflows/dependabot-auto-merge.yml +++ /dev/null @@ -1,33 +0,0 @@ -name: dependabot-auto-merge -on: pull_request_target - -permissions: - pull-requests: write - contents: write - -jobs: - dependabot: - runs-on: ubuntu-latest - timeout-minutes: 5 - if: ${{ github.actor == 'dependabot[bot]' }} - steps: - - - name: Dependabot metadata - id: metadata - uses: dependabot/fetch-metadata@v2.2.0 - with: - github-token: "${{ secrets.GITHUB_TOKEN }}" - - - name: Auto-merge Dependabot PRs for semver-minor updates - if: ${{steps.metadata.outputs.update-type == 'version-update:semver-minor'}} - run: gh pr merge --auto --merge "$PR_URL" - env: - PR_URL: ${{github.event.pull_request.html_url}} - GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} - - - name: Auto-merge Dependabot PRs for semver-patch updates - if: ${{steps.metadata.outputs.update-type == 'version-update:semver-patch'}} - run: gh pr merge --auto --merge "$PR_URL" - env: - PR_URL: ${{github.event.pull_request.html_url}} - GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} diff --git a/.github/workflows/phpstan.yml b/.github/workflows/phpstan.yml deleted file mode 100644 index d5db2f14..00000000 --- a/.github/workflows/phpstan.yml +++ /dev/null @@ -1,28 +0,0 @@ -name: PHPStan - -on: - push: - paths: - - '**.php' - - 'phpstan.neon.dist' - - '.github/workflows/phpstan.yml' - -jobs: - phpstan: - name: phpstan - runs-on: ubuntu-latest - timeout-minutes: 5 - steps: - - uses: actions/checkout@v4 - - - name: Setup PHP - uses: shivammathur/setup-php@v2 - with: - php-version: '8.2' - coverage: none - - - name: Install composer dependencies - uses: ramsey/composer-install@v3 - - - name: Run PHPStan - run: ./vendor/bin/phpstan --error-format=github diff --git a/.gitignore b/.gitignore index b60507fb..1e18f355 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,4 @@ phpstan.neon testbench.yaml /docs /coverage +openapi.yaml diff --git a/CHANGELOG.md b/CHANGELOG.md index 87b3242a..06a91161 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,3 @@ # Changelog -All notable changes to `:package_name` will be documented in this file. +All notable changes to `keycloak` will be documented in this file. diff --git a/LICENSE.md b/LICENSE.md index 58c9ad42..a8f0247a 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) :vendor_name +Copyright (c) OpenSeaWave Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 375da962..f2dff1f2 100644 --- a/README.md +++ b/README.md @@ -1,68 +1,47 @@ -# :package_description +# openseawave/keycloak -[![Latest Version on Packagist](https://img.shields.io/packagist/v/:vendor_slug/:package_slug.svg?style=flat-square)](https://packagist.org/packages/:vendor_slug/:package_slug) -[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/:vendor_slug/:package_slug/run-tests.yml?branch=main&label=tests&style=flat-square)](https://github.com/:vendor_slug/:package_slug/actions?query=workflow%3Arun-tests+branch%3Amain) -[![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/:vendor_slug/:package_slug/fix-php-code-style-issues.yml?branch=main&label=code%20style&style=flat-square)](https://github.com/:vendor_slug/:package_slug/actions?query=workflow%3A"Fix+PHP+code+style+issues"+branch%3Amain) -[![Total Downloads](https://img.shields.io/packagist/dt/:vendor_slug/:package_slug.svg?style=flat-square)](https://packagist.org/packages/:vendor_slug/:package_slug) - ---- -This repo can be used to scaffold a Laravel package. Follow these steps to get started: +[![Latest Version on Packagist](https://img.shields.io/packagist/v/openseawave/keycloak.svg?style=flat-square)](https://packagist.org/packages/openseawave/keycloak) +[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/openseawave/keycloak/run-tests.yml?branch=main&label=tests&style=flat-square)](https://github.com/openseawave/keycloak/actions?query=workflow%3Arun-tests+branch%3Amain) +[![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/openseawave/keycloak/fix-php-code-style-issues.yml?branch=main&label=code%20style&style=flat-square)](https://github.com/openseawave/keycloak/actions?query=workflow%3A"Fix+PHP+code+style+issues"+branch%3Amain) +[![Total Downloads](https://img.shields.io/packagist/dt/openseawave/keycloak.svg?style=flat-square)](https://packagist.org/packages/openseawave/keycloak) -1. Press the "Use this template" button at the top of this repo to create a new repo with the contents of this skeleton. -2. Run "php ./configure.php" to run a script that will replace all placeholders throughout all the files. -3. Have fun creating your package. -4. If you need help creating a package, consider picking up our Laravel Package Training video course. ---- - -This is where your description should go. Limit it to a paragraph or two. Consider adding a small example. - -## Support us - -[](https://spatie.be/github-ad-click/:package_name) - -We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us). - -We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards). +The keyclock plugin provides a simple way to integrate Keycloak admin api with full support for Laravel framework. ## Installation You can install the package via composer: ```bash -composer require :vendor_slug/:package_slug -``` - -You can publish and run the migrations with: - -```bash -php artisan vendor:publish --tag=":package_slug-migrations" -php artisan migrate +composer require openseawave/keycloak ``` You can publish the config file with: ```bash -php artisan vendor:publish --tag=":package_slug-config" +php artisan vendor:publish --tag="keycloak-config" ``` -This is the contents of the published config file: +## Usage + +you can use it like this: ```php -return [ -]; -``` +use Openseawave\Keycloak\Keycloak; -Optionally, you can publish the views using +$keycloak = new Keycloak( + baseUrl: 'http://localhost:8080/auth', + username: 'admin', + password: 'admin', +); -```bash -php artisan vendor:publish --tag=":package_slug-views" +$keycloak->getUsers(); ``` -## Usage +Also you can use it using Laravel Facade: ```php -$variable = new VendorName\Skeleton(); -echo $variable->echoPhrase('Hello, VendorName!'); +use Openseawave\Keycloak\Facades\Keycloak; +Keycloak::getUsers(); ``` ## Testing @@ -70,7 +49,6 @@ echo $variable->echoPhrase('Hello, VendorName!'); ```bash composer test ``` - ## Changelog Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently. @@ -85,7 +63,7 @@ Please review [our security policy](../../security/policy) on how to report secu ## Credits -- [:author_name](https://github.com/:author_username) +- [Omar Haris](https://github.com/omar-haris) - [All Contributors](../../contributors) ## License diff --git a/composer.json b/composer.json index 65e9908b..b1b8dee6 100644 --- a/composer.json +++ b/composer.json @@ -1,17 +1,27 @@ { - "name": ":vendor_slug/:package_slug", - "description": ":package_description", + "name": "openseawave/keycloak", + "description": "The keyclock plugin provides a simple way to integrate Keycloak admin api with full support for Laravel framework.", "keywords": [ - ":vendor_name", - "laravel", - ":package_slug" + "openseawave", + "keycloak", + "sso", + "authentication", + "authorization", + "single-sign-on", + "oauth2", + "openid-connect", + "admin", + "api", + "keycloak-api", + "framework", + "laravel" ], - "homepage": "https://github.com/:vendor_slug/:package_slug", + "homepage": "https://github.com/openseawave/keycloak", "license": "MIT", "authors": [ { - "name": ":author_name", - "email": "author@domain.com", + "name": "Omar Haris", + "email": "omar@haris.bz", "role": "Developer" } ], @@ -23,31 +33,26 @@ "require-dev": { "laravel/pint": "^1.14", "nunomaduro/collision": "^8.1.1||^7.10.0", - "larastan/larastan": "^2.9", "orchestra/testbench": "^9.0.0||^8.22.0", "pestphp/pest": "^2.34", "pestphp/pest-plugin-arch": "^2.7", - "pestphp/pest-plugin-laravel": "^2.3", - "phpstan/extension-installer": "^1.3", - "phpstan/phpstan-deprecation-rules": "^1.1", - "phpstan/phpstan-phpunit": "^1.3", - "spatie/laravel-ray": "^1.35" + "pestphp/pest-plugin-laravel": "^2.3" }, "autoload": { "psr-4": { - "VendorName\\Skeleton\\": "src/", - "VendorName\\Skeleton\\Database\\Factories\\": "database/factories/" + "OpenSeaWave\\Keycloak\\": "src/", + "OpenSeaWave\\Keycloak\\Database\\Factories\\": "database/factories/" } }, "autoload-dev": { "psr-4": { - "VendorName\\Skeleton\\Tests\\": "tests/", + "OpenSeaWave\\Keycloak\\Tests\\": "tests/", "Workbench\\App\\": "workbench/app/" } }, "scripts": { "post-autoload-dump": "@composer run prepare", - "clear": "@php vendor/bin/testbench package:purge-skeleton --ansi", + "clear": "@php vendor/bin/testbench package:purge-keycloak --ansi", "prepare": "@php vendor/bin/testbench package:discover --ansi", "build": [ "@composer run prepare", @@ -73,10 +78,10 @@ "extra": { "laravel": { "providers": [ - "VendorName\\Skeleton\\SkeletonServiceProvider" + "OpenSeaWave\\Keycloak\\KeycloakServiceProvider" ], "aliases": { - "Skeleton": "VendorName\\Skeleton\\Facades\\Skeleton" + "Keycloak": "OpenSeaWave\\Keycloak\\Facades\\Keycloak" } } }, diff --git a/config/keycloak.php b/config/keycloak.php new file mode 100644 index 00000000..4cf37897 --- /dev/null +++ b/config/keycloak.php @@ -0,0 +1,88 @@ + env('KEYCLOAK_BASE_URL'), + + /* + |-------------------------------------------------------------------------- + | Keycloak Username + |-------------------------------------------------------------------------- + | + | The username of the Keycloak user that will be used to authenticate with + | the Keycloak API. + | + */ + 'username' => env('KEYCLOAK_USERNAME'), + + /* + |-------------------------------------------------------------------------- + | Keycloak Password + |-------------------------------------------------------------------------- + | + | The password of the Keycloak user that will be used to authenticate to the + | Keycloak API. + | + */ + 'password' => env('KEYCLOAK_PASSWORD'), + + /* + |-------------------------------------------------------------------------- + | Keycloak Realm + |-------------------------------------------------------------------------- + | + | The realm in Keycloak that you wish to interact with. Realms are isolated + | partitions in Keycloak, and this setting specifies which realm your + | application will communicate with. + | + */ + 'realm' => env('KEYCLOAK_REALM','master'), + + /* + |-------------------------------------------------------------------------- + | Keycloak Client ID + |-------------------------------------------------------------------------- + | + | The client ID registered with Keycloak for your application. This client + | should have the appropriate roles and permissions set in your Keycloak + | realm to allow API interactions. + | + */ + 'client_id' => env('KEYCLOAK_CLIENT_ID','admin-cli'), + + /* + |-------------------------------------------------------------------------- + | Keycloak Client Secret + |-------------------------------------------------------------------------- + | + | The client secret associated with the above client ID. This secret is used + | for authenticating your application with Keycloak when obtaining tokens + | and making API requests. + | + */ + 'client_secret' => env('KEYCLOAK_CLIENT_SECRET'), + + /* + |-------------------------------------------------------------------------- + | Keycloak Grant Type + |-------------------------------------------------------------------------- + | + | The grant type to use when authenticating with Keycloak. This value should + | be set to 'password' if using the username and password authentication + | method. Other grant types are available, such as 'client_credentials'. + | + */ + 'grant_type' => env('KEYCLOAK_GRANT_TYPE','password'), +]; diff --git a/config/skeleton.php b/config/skeleton.php deleted file mode 100644 index 7e741865..00000000 --- a/config/skeleton.php +++ /dev/null @@ -1,6 +0,0 @@ - $version) { - if (in_array($name, $names, true)) { - unset($data['require-dev'][$name]); - } - } - - file_put_contents(__DIR__.'/composer.json', json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); -} - -function remove_composer_script($scriptName) -{ - $data = json_decode(file_get_contents(__DIR__.'/composer.json'), true); - - foreach ($data['scripts'] as $name => $script) { - if ($scriptName === $name) { - unset($data['scripts'][$name]); - break; - } - } - - file_put_contents(__DIR__.'/composer.json', json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); -} - -function remove_readme_paragraphs(string $file): void -{ - $contents = file_get_contents($file); - - file_put_contents( - $file, - preg_replace('/.*/s', '', $contents) ?: $contents - ); -} - -function safeUnlink(string $filename) -{ - if (file_exists($filename) && is_file($filename)) { - unlink($filename); - } -} - -function determineSeparator(string $path): string -{ - return str_replace('/', DIRECTORY_SEPARATOR, $path); -} - -function replaceForWindows(): array -{ - return preg_split('/\\r\\n|\\r|\\n/', run('dir /S /B * | findstr /v /i .git\ | findstr /v /i vendor | findstr /v /i '.basename(__FILE__).' | findstr /r /i /M /F:/ ":author :vendor :package VendorName skeleton migration_table_name vendor_name vendor_slug author@domain.com"')); -} - -function replaceForAllOtherOSes(): array -{ - return explode(PHP_EOL, run('grep -E -r -l -i ":author|:vendor|:package|VendorName|skeleton|migration_table_name|vendor_name|vendor_slug|author@domain.com" --exclude-dir=vendor ./* ./.github/* | grep -v '.basename(__FILE__))); -} - -function getGitHubApiEndpoint(string $endpoint): ?stdClass -{ - try { - $curl = curl_init("https://api.github.com/{$endpoint}"); - curl_setopt_array($curl, [ - CURLOPT_RETURNTRANSFER => true, - CURLOPT_FOLLOWLOCATION => true, - CURLOPT_HTTPGET => true, - CURLOPT_HTTPHEADER => [ - 'User-Agent: spatie-configure-script/1.0', - ], - ]); - - $response = curl_exec($curl); - $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); - - curl_close($curl); - - if ($statusCode === 200) { - return json_decode($response); - } - } catch (Exception $e) { - // ignore - } - - return null; -} - -function searchCommitsForGitHubUsername(): string -{ - $authorName = strtolower(trim(shell_exec('git config user.name'))); - - $committersRaw = shell_exec("git log --author='@users.noreply.github.com' --pretty='%an:%ae' --reverse"); - $committersLines = explode("\n", $committersRaw ?? ''); - $committers = array_filter(array_map(function ($line) use ($authorName) { - $line = trim($line); - [$name, $email] = explode(':', $line) + [null, null]; - - return [ - 'name' => $name, - 'email' => $email, - 'isMatch' => strtolower($name) === $authorName && ! str_contains($name, '[bot]'), - ]; - }, $committersLines), fn ($item) => $item['isMatch']); - - if (empty($committers)) { - return ''; - } - - $firstCommitter = reset($committers); - - return explode('@', $firstCommitter['email'])[0] ?? ''; -} - -function guessGitHubUsernameUsingCli() -{ - try { - if (preg_match('/ogged in to github\.com as ([a-zA-Z-_]+).+/', shell_exec('gh auth status -h github.com 2>&1'), $matches)) { - return $matches[1]; - } - } catch (Exception $e) { - // ignore - } - - return ''; -} - -function guessGitHubUsername(): string -{ - $username = searchCommitsForGitHubUsername(); - if (! empty($username)) { - return $username; - } - - $username = guessGitHubUsernameUsingCli(); - if (! empty($username)) { - return $username; - } - - // fall back to using the username from the git remote - $remoteUrl = shell_exec('git config remote.origin.url'); - $remoteUrlParts = explode('/', str_replace(':', '/', trim($remoteUrl))); - - return $remoteUrlParts[1] ?? ''; -} - -function guessGitHubVendorInfo($authorName, $username): array -{ - $remoteUrl = shell_exec('git config remote.origin.url'); - $remoteUrlParts = explode('/', str_replace(':', '/', trim($remoteUrl))); - - $response = getGitHubApiEndpoint("orgs/{$remoteUrlParts[1]}"); - - if ($response === null) { - return [$authorName, $username]; - } - - return [$response->name ?? $authorName, $response->login ?? $username]; -} - -$gitName = run('git config user.name'); -$authorName = ask('Author name', $gitName); - -$gitEmail = run('git config user.email'); -$authorEmail = ask('Author email', $gitEmail); -$authorUsername = ask('Author username', guessGitHubUsername()); - -$guessGitHubVendorInfo = guessGitHubVendorInfo($authorName, $authorUsername); - -$vendorName = ask('Vendor name', $guessGitHubVendorInfo[0]); -$vendorUsername = ask('Vendor username', $guessGitHubVendorInfo[1] ?? slugify($vendorName)); -$vendorSlug = slugify($vendorUsername); - -$vendorNamespace = str_replace('-', '', ucwords($vendorName)); -$vendorNamespace = ask('Vendor namespace', $vendorNamespace); - -$currentDirectory = getcwd(); -$folderName = basename($currentDirectory); - -$packageName = ask('Package name', $folderName); -$packageSlug = slugify($packageName); -$packageSlugWithoutPrefix = remove_prefix('laravel-', $packageSlug); - -$className = title_case($packageName); -$className = ask('Class name', $className); -$variableName = lcfirst($className); -$description = ask('Package description', "This is my package {$packageSlug}"); - -$usePhpStan = confirm('Enable PhpStan?', true); -$useLaravelPint = confirm('Enable Laravel Pint?', true); -$useDependabot = confirm('Enable Dependabot?', true); -$useLaravelRay = confirm('Use Ray for debugging?', true); -$useUpdateChangelogWorkflow = confirm('Use automatic changelog updater workflow?', true); - -writeln('------'); -writeln("Author : {$authorName} ({$authorUsername}, {$authorEmail})"); -writeln("Vendor : {$vendorName} ({$vendorSlug})"); -writeln("Package : {$packageSlug} <{$description}>"); -writeln("Namespace : {$vendorNamespace}\\{$className}"); -writeln("Class name : {$className}"); -writeln('---'); -writeln('Packages & Utilities'); -writeln('Use Laravel/Pint : '.($useLaravelPint ? 'yes' : 'no')); -writeln('Use Larastan/PhpStan : '.($usePhpStan ? 'yes' : 'no')); -writeln('Use Dependabot : '.($useDependabot ? 'yes' : 'no')); -writeln('Use Ray App : '.($useLaravelRay ? 'yes' : 'no')); -writeln('Use Auto-Changelog : '.($useUpdateChangelogWorkflow ? 'yes' : 'no')); -writeln('------'); - -writeln('This script will replace the above values in all relevant files in the project directory.'); - -if (! confirm('Modify files?', true)) { - exit(1); -} - -$files = (str_starts_with(strtoupper(PHP_OS), 'WIN') ? replaceForWindows() : replaceForAllOtherOSes()); - -foreach ($files as $file) { - replace_in_file($file, [ - ':author_name' => $authorName, - ':author_username' => $authorUsername, - 'author@domain.com' => $authorEmail, - ':vendor_name' => $vendorName, - ':vendor_slug' => $vendorSlug, - 'VendorName' => $vendorNamespace, - ':package_name' => $packageName, - ':package_slug' => $packageSlug, - ':package_slug_without_prefix' => $packageSlugWithoutPrefix, - 'Skeleton' => $className, - 'skeleton' => $packageSlug, - 'migration_table_name' => title_snake($packageSlug), - 'variable' => $variableName, - ':package_description' => $description, - ]); - - match (true) { - str_contains($file, determineSeparator('src/Skeleton.php')) => rename($file, determineSeparator('./src/'.$className.'.php')), - str_contains($file, determineSeparator('src/SkeletonServiceProvider.php')) => rename($file, determineSeparator('./src/'.$className.'ServiceProvider.php')), - str_contains($file, determineSeparator('src/Facades/Skeleton.php')) => rename($file, determineSeparator('./src/Facades/'.$className.'.php')), - str_contains($file, determineSeparator('src/Commands/SkeletonCommand.php')) => rename($file, determineSeparator('./src/Commands/'.$className.'Command.php')), - str_contains($file, determineSeparator('database/migrations/create_skeleton_table.php.stub')) => rename($file, determineSeparator('./database/migrations/create_'.title_snake($packageSlugWithoutPrefix).'_table.php.stub')), - str_contains($file, determineSeparator('config/skeleton.php')) => rename($file, determineSeparator('./config/'.$packageSlugWithoutPrefix.'.php')), - str_contains($file, 'README.md') => remove_readme_paragraphs($file), - default => [], - }; -} - -if (! $useLaravelPint) { - safeUnlink(__DIR__.'/.github/workflows/fix-php-code-style-issues.yml'); - safeUnlink(__DIR__.'/pint.json'); -} - -if (! $usePhpStan) { - safeUnlink(__DIR__.'/phpstan.neon.dist'); - safeUnlink(__DIR__.'/phpstan-baseline.neon'); - safeUnlink(__DIR__.'/.github/workflows/phpstan.yml'); - - remove_composer_deps([ - 'phpstan/extension-installer', - 'phpstan/phpstan-deprecation-rules', - 'phpstan/phpstan-phpunit', - 'larastan/larastan', - ]); - - remove_composer_script('phpstan'); -} - -if (! $useDependabot) { - safeUnlink(__DIR__.'/.github/dependabot.yml'); - safeUnlink(__DIR__.'/.github/workflows/dependabot-auto-merge.yml'); -} - -if (! $useLaravelRay) { - remove_composer_deps(['spatie/laravel-ray']); -} - -if (! $useUpdateChangelogWorkflow) { - safeUnlink(__DIR__.'/.github/workflows/update-changelog.yml'); -} - -confirm('Execute `composer install` and run tests?') && run('composer install && composer test'); - -confirm('Let this script delete itself?', true) && unlink(__FILE__); diff --git a/database/factories/ModelFactory.php b/database/factories/ModelFactory.php deleted file mode 100644 index c51604f4..00000000 --- a/database/factories/ModelFactory.php +++ /dev/null @@ -1,19 +0,0 @@ -id(); - - // add fields - - $table->timestamps(); - }); - } -}; diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon deleted file mode 100644 index e69de29b..00000000 diff --git a/phpstan.neon.dist b/phpstan.neon.dist deleted file mode 100644 index ab1b4c30..00000000 --- a/phpstan.neon.dist +++ /dev/null @@ -1,12 +0,0 @@ -includes: - - phpstan-baseline.neon - -parameters: - level: 5 - paths: - - src - - config - - database - tmpDir: build/phpstan - checkOctaneCompatibility: true - checkModelProperties: true diff --git a/phpunit.xml.dist b/phpunit.xml.dist index bfe434d8..7d8ec2ba 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -16,7 +16,7 @@ backupStaticProperties="false" > - + tests diff --git a/src/Commands/SkeletonCommand.php b/src/Commands/SkeletonCommand.php deleted file mode 100644 index 3e5f6280..00000000 --- a/src/Commands/SkeletonCommand.php +++ /dev/null @@ -1,19 +0,0 @@ -comment('All done'); - - return self::SUCCESS; - } -} diff --git a/src/Enums/CredentialType.php b/src/Enums/CredentialType.php new file mode 100644 index 00000000..ab2fc895 --- /dev/null +++ b/src/Enums/CredentialType.php @@ -0,0 +1,36 @@ +statusCode = $statusCode; + $this->response = $response; + } + + /** + * Get the HTTP status code from Keycloak. + * + * @return int|null + */ + public function getStatusCode(): ?int + { + return $this->statusCode; + } + + /** + * Get the HTTP response object. + * + * @return ResponseInterface|null + */ + public function getResponse() + { + return $this->response; + } + + /** + * Get the body of the HTTP response as an associative array. + * + * @return array|null + */ + public function getResponseBody(): ?array + { + if ($this->response) { + $body = (string) $this->response->getBody(); + return json_decode($body, true); + } + return null; + } + + /** + * Static method to create an exception from a Guzzle RequestException. + * + * @param RequestException $exception + * @return static + */ + public static function fromRequestException(RequestException $exception): self + { + $response = $exception->getResponse(); + $statusCode = $response ? $response->getStatusCode() : null; + $message = $response ? (string) $response->getBody() : $exception->getMessage(); + + return new static($message, $statusCode, $exception, $response); + } +} diff --git a/src/Facades/Keycloak.php b/src/Facades/Keycloak.php new file mode 100644 index 00000000..4a17b49d --- /dev/null +++ b/src/Facades/Keycloak.php @@ -0,0 +1,56 @@ +username = $username ?? config('keycloak.username'); + $this->password = $password ?? config('keycloak.password'); + $this->baseUrl = $baseUrl ?? config('keycloak.base_url'); + $this->realm = $realm ?? config('keycloak.realm'); + $this->clientId = $clientId ?? config('keycloak.client_id'); + $this->clientSecret = $clientSecret ?? config('keycloak.client_secret'); + $this->grantType = $grantType ?? config('keycloak.grant_type'); + + $this->httpClient = new Client([ + 'base_uri' => $this->baseUrl, + 'headers' => [ + 'Content-Type' => 'application/json', + ] + ]); + } + + /** + * Set base URL for the Keycloak client. + * + * @param string $baseUrl The base URL to set. + * @return Keycloak + */ + public function setBaseUrl(string $baseUrl): Keycloak + { + $this->baseUrl = $baseUrl; + + return $this; + } + + /** + * Set realm for the Keycloak client. + * + * @param string $realm The realm to set. + * @return Keycloak + */ + public function setRealm(string $realm): Keycloak + { + $this->realm = $realm; + + return $this; + } + + /** + * Set grant type for the Keycloak client. + * + * @param string $grantType The grant type to set. + * @return Keycloak + */ + public function setGrantType(string $grantType): Keycloak + { + $this->grantType = $grantType; + + return $this; + } + + /** + * Set Client ID for the Keycloak client. + * + * @param string $clientId The client ID to set. + * @return Keycloak + */ + public function setClientId(string $clientId): Keycloak + { + $this->clientId = $clientId; + + return $this; + } + + /** + * Set Client secret for the Keycloak client. + * + * @param string $clientSecret The client secret to set. + * @return Keycloak + */ + public function setClientSecret(string $clientSecret): Keycloak + { + $this->clientSecret = $clientSecret; + + return $this; + } + + /** + * Set username for the Keycloak client. + * + * @param string $username The username to set. + * @return Keycloak + */ + public function setUsername(string $username): Keycloak + { + $this->username = $username; + + return $this; + } + + /** + * Set password for the Keycloak client. + * + * @param string $password The password to set. + * @return Keycloak + */ + public function setPassword(string $password): Keycloak + { + $this->password = $password; + + return $this; + } + + /** + * Retrieve an access token from Keycloak. + * + * @param ?string $realm The realm for which to retrieve the token. + * @return object the token object. + * @throws GuzzleException If the HTTP request fails. + */ + public function getToken(?string $realm = null): object + { + // Create a new instance of the KeycloakUrlBuilder + $urlBuilder = new KeycloakUrlBuilder( + baseUrl: $this->baseUrl, + realm: $realm ?? $this->realm + ); + + // Make a POST request to the token endpoint + $response = $this->httpClient->post($urlBuilder->getTokenUrl(), [ + 'form_params' => [ + 'grant_type' => $this->grantType, + 'client_id' => $this->clientId, + 'client_secret' => $this->clientSecret, + 'username' => $this->username, + 'password' => $this->password, + ], + ]); + + // Return the token object + return json_decode( + $response->getBody()->getContents() + ); + } + + /** + * Count the total number of users in a realm based on filters. + * + * @param ?CountUsersRequest $query An object representing the query parameters. + * @param ?string $realm The realm for which to count users. + * @return int The number of users matching the criteria. + * @throws GuzzleException If the HTTP request fails. + */ + public function countUsers(?string $realm = null,?CountUsersRequest $query = null): int + { + // Create a new instance of the KeycloakUrlBuilder + $urlBuilder = new KeycloakUrlBuilder( + baseUrl: $this->baseUrl, + realm: $realm ?? $this->realm + ); + + // Make a GET request to the count users endpoint + $response = $this->httpClient->get($urlBuilder->getCountUsersUrl(), [ + 'headers' => [ + 'Authorization' => "Bearer {$this->getToken()->access_token}", + ], + 'query' => $query?->toArray(), + ]); + + // Return the count of users + return json_decode( + $response->getBody()->getContents() + ); + } + + /** + * Retrieve a list of users based on filters. + * + * @param ?GetUsersRequest $query An object representing the query parameters. + * @param ?string $realm The realm for which to retrieve users. + * @return array An array of user objects. + * @throws GuzzleException If the HTTP request fails. + */ + public function getUsers(?string $realm = null,?GetUsersRequest $query = null): array + { + // Create a new instance of the KeycloakUrlBuilder + $urlBuilder = new KeycloakUrlBuilder( + baseUrl: $this->baseUrl, + realm: $realm ?? $this->realm + ); + + // Make a GET request to the count users endpoint + $response = $this->httpClient->get($urlBuilder->getUsersUrl(), [ + 'headers' => [ + 'Authorization' => "Bearer {$this->getToken()->access_token}", + ], + 'query' => $query?->toArray() + ]); + + return json_decode( + $response->getBody()->getContents() + ); + } + + /** + * Retrieve user details by user ID. + * + * @param string $id The UUID of the user to retrieve. + * @param ?string $realm The realm for which to retrieve the user. + * @return object A user representation. + * @throws GuzzleException If the HTTP request fails. + */ + public function getUser(string $id,?string $realm = null): object + { + // Create a new instance of the KeycloakUrlBuilder + $urlBuilder = new KeycloakUrlBuilder( + baseUrl: $this->baseUrl, + realm: $realm ?? $this->realm + ); + + // Make a GET request to the user endpoint + $response = $this->httpClient->get($urlBuilder->getUserByIdUrl($id), [ + 'headers' => [ + 'Authorization' => "Bearer {$this->getToken()->access_token}", + ], + ]); + + // Return the user object + return json_decode( + $response->getBody()->getContents() + ); + } + + /** + * Create a new user in the realm. + * + * @param UserRepresentation $data The user data for creating a new user. + * @param ?string $realm The realm for which to create the user. + * @return UserRepresentation The user object that was created. + * @throws KeycloakException If the API request fails. + * @throws GuzzleException + */ + public function createUser(UserRepresentation $data, ?string $realm = null): UserRepresentation + { + // Create a new instance of the KeycloakUrlBuilder + $urlBuilder = new KeycloakUrlBuilder( + baseUrl: $this->baseUrl, + realm: $realm ?? $this->realm + ); + + // Make a POST request to the users endpoint + $response = $this->httpClient->post($urlBuilder->getUsersUrl(), [ + 'json' => $data, + 'headers' => [ + 'Authorization' => "Bearer {$this->getToken()->access_token}", + ], + ]); + + // Return the user object + if (!$this->isSuccessfulResponse($response)) { + throw new KeycloakException('Failed to create user', 0); + } + + return $data; + } + + /** + * Update an existing user in the realm. + * + * @param UserRepresentation $data The user data for creating a new user. + * @param ?string $realm The realm for which to create the user. + * @return UserRepresentation The user object that was created. + * @throws KeycloakException If the API request fails. + * @throws GuzzleException + */ + public function updateUser(string $id, UserRepresentation $data, ?string $realm = null): UserRepresentation + { + // Create a new instance of the KeycloakUrlBuilder + $urlBuilder = new KeycloakUrlBuilder( + baseUrl: $this->baseUrl, + realm: $realm ?? $this->realm + ); + + // Make a POST request to the users endpoint + $response = $this->httpClient->put($urlBuilder->getUserByIdUrl($id), [ + 'json' => $data, + 'headers' => [ + 'Authorization' => "Bearer {$this->getToken()->access_token}", + ], + ]); + + // Return the user object + if (!$this->isSuccessfulResponse($response)) { + throw new KeycloakException('Failed to update user', 0); + } + + return $data; + } + + /** + * Delete a user in the realm. + * + * @param string $id The UUID of the user to delete. + * @param string|null $realm The realm for which to delete the user. + * @return bool True if the user was deleted successfully. + * @throws GuzzleException If the HTTP request fails. + * @throws KeycloakException If the API request fails. + */ + public function deleteUser(string $id,?string $realm = null): bool + { + $urlBuilder = new KeycloakUrlBuilder( + baseUrl: $this->baseUrl, + realm: $realm ?? $this->realm + ); + + $response = $this->httpClient->delete($urlBuilder->getUserByIdUrl($id), [ + 'headers' => [ + 'Authorization' => "Bearer {$this->getToken()->access_token}", + ], + ]); + + if (!$this->isSuccessfulResponse($response)) { + throw new KeycloakException('Failed to update user', 0); + } + + return true; + } + + /** + * Retrieve a list of roles from the realm. + * + * @param string|null $realm The realm for which to retrieve roles. + * @param GetRolesRequest|null $request An object representing the query parameters. + * @return array An array of role objects. + * @throws GuzzleException If the HTTP request fails. + * @throws KeycloakException If the API request fails. + */ + public function getRoles(?GetRolesRequest $request,string $realm = null): array + { + $urlBuilder = new KeycloakUrlBuilder( + baseUrl: $this->baseUrl, + realm: $realm ?? $this->realm + ); + + $response = $this->httpClient->get($urlBuilder->getRolesUrl(), [ + 'headers' => [ + 'Authorization' => "Bearer {$this->getToken()->access_token}", + ], + 'query' => $request?->toArray() + ]); + + if (!$this->isSuccessfulResponse($response)) { + throw new KeycloakException('Failed to retrieve roles', 0); + } + + return json_decode( + $response->getBody()->getContents() + ); + } + + /** + * Create a new role in the realm. + * + * @param CreateRoleRequest $data The role data for creating a new role. + * @param string|null $realm The realm for which to create the role. + * @return bool True if the role was created successfully. + * @throws GuzzleException If the HTTP request fails. + * @throws KeycloakException If the API request fails. + */ + public function createRole(CreateRoleRequest $data, ?string $realm = null): bool + { + $urlBuilder = new KeycloakUrlBuilder( + baseUrl: $this->baseUrl, + realm: $realm ?? $this->realm + ); + + $response = $this->httpClient->post($urlBuilder->getRolesUrl(), [ + 'json' => $data, + 'headers' => [ + 'Authorization' => "Bearer {$this->getToken()->access_token}", + ], + ]); + + if (!$this->isSuccessfulResponse($response)) { + throw new KeycloakException('Failed to create role', 0); + } + + return true; + } + + /** + * @param string $roleName + * @param UpdateRoleRequest $data + * @param string|null $realm + * @return void + */ + public function updateRole(string $roleName, UpdateRoleRequest $data, ?string $realm = null): void + { + // TODO: Implement updateRole() method. + } + + /** + * @param string $roleName + * @param string|null $realm + * @return void + */ + public function deleteRole(string $roleName,?string $realm = null): void + { + // TODO: Implement deleteRole() method. + } + + /** + * @param string $userId + * @param ?string $realm + * @return array + */ + public function getUserRoles(string $userId,?string $realm = null): array + { + // TODO: Implement getUserRoles() method. + } + + /** + * @param string $userId + * @param AddUserRolesRequest $roles + * @param string|null $realm + * @return void + */ + public function addUserRoles(string $userId, AddUserRolesRequest $roles, ?string $realm = null): void + { + // TODO: Implement addUserRoles() method. + } + + /** + * @param string $userId + * @param DeleteUserRolesRequest $roles + * @param string|null $realm + * @return void + */ + public function deleteUserRoles(string $userId, DeleteUserRolesRequest $roles, ?string $realm = null): void + { + // TODO: Implement deleteUserRoles() method. + } + + /** + * @param string $userId + * @param string $password + * @param string|null $realm + * @return void + */ + public function changeUserPassword(string $userId, string $password,?string $realm = null): void + { + // TODO: Implement changeUserPassword() method. + } + + /** + * @param string $userId + * @param bool $enabled + * @param string|null $realm + * @return void + */ + public function changeUserActivationStatus(string $userId, bool $enabled,?string $realm = null): void + { + // TODO: Implement changeUserActivationStatus() method. + } + + /** + * Check if the response is successful. + * + * @param $response + * @return bool + */ + private function isSuccessfulResponse($response): bool + { + return $response->getStatusCode() === 201 || $response->getStatusCode() === 200 || $response->getStatusCode() === 204 || $response->getStatusCode() === 202; + } +} + diff --git a/src/KeycloakInterface.php b/src/KeycloakInterface.php new file mode 100644 index 00000000..a5eb8c72 --- /dev/null +++ b/src/KeycloakInterface.php @@ -0,0 +1,136 @@ +name('keycloak'); + $package->hasConfigFile(); + } +} diff --git a/src/KeycloakUrlBuilder.php b/src/KeycloakUrlBuilder.php new file mode 100644 index 00000000..3326b244 --- /dev/null +++ b/src/KeycloakUrlBuilder.php @@ -0,0 +1,100 @@ +baseUrl = rtrim($baseUrl, '/'); + $this->realm = $realm; + } + + /** + * Get the URL for obtaining a token. + * + * @return string + */ + public function getTokenUrl(): string + { + return "{$this->baseUrl}/realms/{$this->realm}/protocol/openid-connect/token"; + } + + /** + * Get the URL for counting users in a realm. + * + * @return string + */ + public function getCountUsersUrl(): string + { + return "{$this->baseUrl}/admin/realms/{$this->realm}/users/count"; + } + + /** + * Get the URL for retrieving users in a realm. + * + * @return string + */ + public function getUsersUrl(): string + { + return "{$this->baseUrl}/admin/realms/{$this->realm}/users"; + } + + /** + * Get the URL for a specific user by ID. + * + * @param string $userId The ID of the user. + * @return string + */ + public function getUserByIdUrl(string $userId): string + { + return "{$this->baseUrl}/admin/realms/{$this->realm}/users/{$userId}"; + } + + /** + * Get the URL for managing roles in a realm. + * + * @return string + */ + public function getRolesUrl(): string + { + return "{$this->baseUrl}/admin/realms/{$this->realm}/roles"; + } + + /** + * Get the URL for a specific role by role name. + * + * @param string $roleName The name of the role. + * @return string + */ + public function getRoleByNameUrl(string $roleName): string + { + return "{$this->baseUrl}/admin/realms/{$this->realm}/roles/{$roleName}"; + } +} diff --git a/src/Representation/AddUserRolesRequest.php b/src/Representation/AddUserRolesRequest.php new file mode 100644 index 00000000..49c38a6d --- /dev/null +++ b/src/Representation/AddUserRolesRequest.php @@ -0,0 +1,26 @@ + ['role1', 'role2'], 'client-id-2' => ['role3']] + */ + public ?array $client = null, + + /** + * @var array|null A mapping of application IDs to an array of application-level roles (deprecated). + * Each application ID maps to a list of role names. + * @example ['app-id-1' => ['app-role1', 'app-role2']] + * @deprecated + */ + public ?array $application = null, + ){} +} diff --git a/src/Representation/CountUsersRequest.php b/src/Representation/CountUsersRequest.php new file mode 100644 index 00000000..86f240a2 --- /dev/null +++ b/src/Representation/CountUsersRequest.php @@ -0,0 +1,109 @@ + $value) { + if (!is_null($value)) { + $array[$key] = $this->optimize($value); + } + } + + // Remove all the null values from the array. + return array_filter($array, function ($value) { + return !is_null($value); + }); + } + + /** + * Optimize the value for serialization. + * + * @param mixed $value The value to optimize. + * + * @return mixed + */ + private function optimize(mixed $value): mixed + { + if (is_bool($value)) { + return var_export($value, true); + } + + return $value; + } +} diff --git a/src/Representation/RoleRepresentation.php b/src/Representation/RoleRepresentation.php new file mode 100644 index 00000000..a0493b4d --- /dev/null +++ b/src/Representation/RoleRepresentation.php @@ -0,0 +1,77 @@ + '1234567890', 'address' => '123 Baghdad St'] + */ + public ?array $attributes = null, + + /** + * @var CredentialRepresentation[]|null The user's credentials (optional). + */ + public ?array $credentials = null, + + /** + * @var UserActionType[]|null A list of actions required by the user on the next login (optional). + * @example ['UPDATE_PASSWORD'] + */ + public ?array $requiredActions = null, + + /** + * @var array|null A list of groups the user belongs to (optional). + * @example ['/developers', '/admin'] + */ + public ?array $groups = null, + + /** + * @var array|null A list of realm roles assigned to the user (optional). + * @example ['offline_access', 'uma_authorization'] + */ + public ?array $realmRoles = null, + + /** + * @var array|null Federated identities associated with the user from external identity providers (optional). + * @example [['identityProvider' => 'google', 'userId' => '1234567890', 'userName' => 'googleuser@example.com']] + */ + public ?array $federatedIdentities = null, + + /** + * @var array|null A list of client roles assigned to the user (optional). + * @example ['client-id' => ['role1', 'role2']] + */ + public ?array $clientRoles = null, + + /** + * @var array|null Types of credentials that are disabled for the user (optional). + * @example ['password', 'otp'] + */ + public ?array $disableableCredentialTypes = null, + + /** + * @var array|null Access level control for the user (optional). + * @example ['manageGroupMembership' => true, 'view' => true, 'mapRoles' => true, 'impersonate' => false] + */ + public ?array $access = null, + + /** + * @var array|null The user's profile metadata (optional). + */ + public ?array $userProfileMetadata = null, + + /** + * @var int|null The timestamp when the user was created (optional). + * @example 1631234567 + */ + public ?int $createdTimestamp = null, + + /** + * @var array|null A list of application roles assigned to the user (optional). + * @deprecated + */ + public ?array $applicationRoles = null, + + /** + * @var array|null A list of social links associated with the user (optional). + * @deprecated + */ + public ?array $socialLinks = null, + + /** + * @var bool|null Whether the user has time-based OTP enabled (optional). + * @example false + */ + public ?bool $totp = null, + + /** + * @var string|null The client ID for the service account associated with the user (optional). + */ + public ?string $serviceAccountClientId = null, + + /** + * @var array|null A list of client consents granted by the user (optional). + */ + public ?array $clientConsents = null, + + /** + * @var int|null The "not before" timestamp for the user (optional). + * @example 1627683600 + */ + public ?int $notBefore = null, + + /** + * @var string|null The self-link for the user (optional). + */ + public ?string $self = null, + + /** + * @var string|null The origin of the user (optional). + */ + public ?string $origin = null, + ){} +} diff --git a/src/Skeleton.php b/src/Skeleton.php deleted file mode 100755 index 34c7194b..00000000 --- a/src/Skeleton.php +++ /dev/null @@ -1,5 +0,0 @@ -name('skeleton') - ->hasConfigFile() - ->hasViews() - ->hasMigration('create_migration_table_name_table') - ->hasCommand(SkeletonCommand::class); - } -} diff --git a/tests/Pest.php b/tests/Pest.php index 7fe1500a..db37fec7 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -1,5 +1,5 @@ in(__DIR__); diff --git a/tests/TestCase.php b/tests/TestCase.php index d04fb0cc..5d778b01 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -1,10 +1,10 @@ 'VendorName\\Skeleton\\Database\\Factories\\'.class_basename($modelName).'Factory' + fn (string $modelName) => 'OpenSeaWave\\Keycloak\\Database\\Factories\\'.class_basename($modelName).'Factory' ); } protected function getPackageProviders($app) { return [ - SkeletonServiceProvider::class, + KeycloakServiceProvider::class, ]; } @@ -29,7 +29,7 @@ public function getEnvironmentSetUp($app) config()->set('database.default', 'testing'); /* - $migration = include __DIR__.'/../database/migrations/create_skeleton_table.php.stub'; + $migration = include __DIR__.'/../database/migrations/create_keycloak_table.php.stub'; $migration->up(); */ }