Skip to content

Commit

Permalink
feat(core): Support Laravel (#30)
Browse files Browse the repository at this point in the history
* usage with laravel app

* add middleware and make base url dynamic for laravel

* update middleware tag

* rename services and components

* Update UserInfoMiddleware.php

* rename middleware and service provider and user registred class

* WIP

Signed-off-by: Salah Alkhwlani <[email protected]>

* Create unit-test.yaml

* Update unit-test.yaml

* Update unit-test.yaml

* Create lint-pr.yaml

* Create lint-branch.yaml

* Update unit-test.yaml

* wip

Signed-off-by: Salah Alkhwlani <[email protected]>

* WIP

Signed-off-by: Salah Alkhwlani <[email protected]>

* WIP

Signed-off-by: Salah Alkhwlani <[email protected]>

* wip

Signed-off-by: Salah Alkhwlani <[email protected]>

* WIP

Signed-off-by: Salah Alkhwlani <[email protected]>

* wip

Signed-off-by: Salah Alkhwlani <[email protected]>

* wip

Signed-off-by: Salah Alkhwlani <[email protected]>

* wip

Signed-off-by: Salah Alkhwlani <[email protected]>

* wip

Signed-off-by: Salah Alkhwlani <[email protected]>

---------

Signed-off-by: Salah Alkhwlani <[email protected]>
Co-authored-by: Salah Alkhwlani <[email protected]>
Co-authored-by: Salah Alkhwlani <[email protected]>
  • Loading branch information
3 people authored Jul 18, 2024
1 parent f7c6ee4 commit 7c22716
Show file tree
Hide file tree
Showing 24 changed files with 899 additions and 215 deletions.
17 changes: 17 additions & 0 deletions .github/workflows/lint-branch.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: Lint Branch
on: pull_request
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
lint:
runs-on: ubuntu-latest
name: Validate branch name
steps:
- name: Lint branch name
uses: lekterable/[email protected]
with:
allowed: |
/(bugfix|hotfix|feature)\/[a-zA-Z]+-\d{1,10}(?:-[^\/]+)?$/i
errorMessage: 'The allowed prefixs for branch name are (bugfix|hotfix|feature)'
startAfter: '2023-12-03 00:00:00'
65 changes: 65 additions & 0 deletions .github/workflows/lint-pr.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
name: "Lint PR"

on:
pull_request_target:
types:
- opened
- edited
- synchronize
- labeled
- unlabeled
jobs:
main:
name: Validate PR title
runs-on: ubuntu-latest
steps:
- uses: amannn/action-semantic-pull-request@v5
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
# Configure which types are allowed (newline-delimited).
# Default: https://github.com/commitizen/conventional-commit-types
types: |
fix
feat
BREAKING CHANGE
refactor
test
perf
build
ci
revert
# Configure which scopes are allowed (newline-delimited).
# These are regex patterns auto-wrapped in `^ $`.
scopes: |
JIRA-\d+
[A-Z]+-\d+
catalog
orders
payments
checkout
journey
partners
platform
themes
auth
marketing
devops
# Configure that a scope must always be provided.
requireScope: true
# If the PR contains one of these newline-delimited labels, the
# validation is skipped. If you want to rerun the validation when
# labels change, you might want to use the `labeled` and `unlabeled`
# event triggers in your workflow.
ignoreLabels: |
bot
ignore-semantic-pull-request
# If you're using a format for the PR title that differs from the traditional Conventional
# Commits spec, you can use these options to customize the parsing of the type, scope and
# subject. The `headerPattern` should contain a regex where the capturing groups in parentheses
# correspond to the parts listed in `headerPatternCorrespondence`.
# See: https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-commits-parser#headerpattern
headerPattern: '^(\w*)(?:\(([\w$.\-*/ ]*)\))?: (.*)$'
headerPatternCorrespondence: type, scope, subject
wip: true
# upperCase: true
76 changes: 76 additions & 0 deletions .github/workflows/unit-test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
name: Tests

on:
push:
branches:
- master
pull_request:
types: [opened, synchronize, reopened]

jobs:
test:
name: Test PHP ${{ matrix.php-version }}
runs-on: ubuntu-latest

strategy:
matrix:
php-version: ['8.1', '8.2']

services:
redis:
image: bitnami/redis:6.2.4-debian-10-r35
ports:
- 6379:6379
env:
ALLOW_EMPTY_PASSWORD: 'yes'
options: >-
--health-cmd "redis-cli -p 6379 ping"
--health-start-period 5s
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0

- name: Install dependencies
uses: php-actions/composer@v6
with:
php_version: ${{ matrix.php-version }}
php_extensions: "redis-5.3.7"

- name: PHPUnit Tests
uses: php-actions/phpunit@v3
with:
version: 9.5.26
php_version: ${{ matrix.php-version }}
php_extensions: "xdebug redis-5.3.7"
bootstrap: vendor/autoload.php
configuration: phpunit.xml
coverage_clover: "coverage/clover.xml"
args: --coverage-text
env:
XDEBUG_MODE: coverage
REDIS_HOST: 127.0.0.1
REDIS_PORT: 6379

- name: Run codacy-coverage-reporter
uses: codacy/codacy-coverage-reporter-action@v1
with:
project-token: ${{ secrets.CODACY_API_TOKEN }}
coverage-reports: "coverage/clover.xml"

- name: Dump docker logs on failure
if: failure()
uses: jwalton/gh-docker-logs@v2


unit-test-ready:
needs: [ test ]
runs-on: ubuntu-latest
name: "Testing Ready"
steps:
- name: All tests passed
run: echo "All matrix jobs succeeded"
53 changes: 53 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,59 @@ $token = $provider->getAccessToken('refresh_token', ['refresh_token' => $refresh

```

## Using Salla OAuth2 Inside Laravel

You can seamlessly integrate Salla OAuth2 within Laravel using the facade helper provided by the package. Here's how you can do it:

First, use the facade helper in your Laravel project:

```php
use \Salla\OAuth2\Client\Facade\SallaOauth;

// Generate the authorization URL with the required scope
$authUrl = SallaOauth::getAuthorizationUrl([
'scope' => 'offline_access',
// Important: Set this value to 'offline_access' to generate a refresh token
]);

// Retrieve the access token using the authorization code
$token = SallaOauth::getAccessToken('authorization_code', [
'code' => request()->get('code')
]);
```

To configure the OAuth2 service, set the necessary environment variables in your `.env` file:

```dotenv
SALLA_OAUTH_CLIENT_ID=""
SALLA_OAUTH_CLIENT_SECRET=""
SALLA_OAUTH_CLIENT_REDIRECT_URI=""
```

These settings ensure that your Laravel application can properly communicate with the Salla OAuth2 service, allowing you to handle authentication and retrieve access tokens efficiently.

## Using Salla OAuth2 as a Laravel Guard

When integrating Salla OAuth2 for authentication, you may need to validate the merchant's access token and retrieve user information during a request.

To achieve this, add the `\Salla\OAuth2\Client\Http\OauthMiddleware` middleware to the routes you wish to protect. This middleware ensures that a user is logged in via Salla OAuth2.

However, note that this middleware only verifies user authentication. Additional authorization checks must be implemented separately as needed. The package conveniently stores the resource owner information as a request attribute, facilitating further authorization.

After adding the middleware to your route, you can access the current authenticated user using the following code:

```php
auth()->guard('salla-oauth');
// To check if a user is authenticated:
auth()->guard('salla-oauth')->check();
// To get the authenticated user's ID:
auth()->guard('salla-oauth')->id();
// To get the merchant information of the authenticated user:
auth()->guard('salla-oauth')->merchant();
```

By leveraging this middleware, you ensure secure access to your routes while maintaining flexibility for additional authorization requirements.

## Testing

```bash
Expand Down
28 changes: 19 additions & 9 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,20 @@
"type": "library",
"authors": [
{
"name": "Ahmed Bally",
"email": "ahmed.bally@salla.sa"
"name": "Salla Team",
"email": "support@salla.dev"
}
],
"minimum-stability": "dev",
"require": {
"league/oauth2-client": "^2.0"
"php": "^8.1",
"league/oauth2-client": "^2.0",
"illuminate/support": "^9.0|^10.0"
},
"require-dev": {
"eloquent/phony-phpunit": "^4.0.0 || ^7.0.0",
"phpunit/phpunit": "~7.0.0 || ~7.5.0",
"mockery/mockery": "~1.3.0 || ~1.3.0 || ~1.3.0 || ~1.3.0",
"jakub-onderka/php-parallel-lint": "^0.9.2 || ^1.0.0",
"php-coveralls/php-coveralls": "^2.1",
"laravel/framework": ">=8.0",
"orchestra/testbench": "^6.0|^7.0|^8.0",
"phpunit/phpunit": "^8.0|^9.0",
"squizlabs/php_codesniffer": "^2.0 || ^3.0"
},
"autoload": {
Expand All @@ -37,7 +37,17 @@
},
"autoload-dev": {
"psr-4": {
"Salla\\OAuth2\\Client\\Test\\": "test/src/"
"Salla\\OAuth2\\Client\\Test\\": "test/"
}
},
"extra": {
"laravel": {
"providers": [
"Salla\\OAuth2\\Client\\ServiceProvider"
],
"aliases": {
"SallaOauth": "Salla\\OAuth2\\Client\\Facade\\SallaOauth"
}
}
},
"scripts": {
Expand Down
9 changes: 9 additions & 0 deletions config/salla-oauth.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

return [
'client_id' => env('SALLA_OAUTH_CLIENT_ID'),
'client_secret' => env('SALLA_OAUTH_CLIENT_SECRET'),
'redirect_url' => env('SALLA_OAUTH_CLIENT_REDIRECT_URI'),
'base_url' => env('SALLA_OAUTH_BASE_URL', 'https://accounts.salla.sa'),
'cache-prefix' => env('SALLA_OAUTH_PREFIX_CACHE', 'oauth'),
];
10 changes: 5 additions & 5 deletions phpunit.xml.dist → phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@
processIsolation="false"
stopOnFailure="false"
>
<coverage>
<include>
<directory suffix=".php">src</directory>
</include>
</coverage>
<testsuites>
<testsuite name="all">
<directory>./test</directory>
Expand All @@ -19,9 +24,4 @@
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
<logging>
<log type="coverage-text" target="php://stdout"/>
<log type="coverage-clover" target="build/logs/clover.xml"/>
<log type="coverage-html" target="build/coverage"/>
</logging>
</phpunit>
20 changes: 20 additions & 0 deletions src/Auth/AuthRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace Salla\OAuth2\Client\Auth;

use Illuminate\Http\Request;
use Salla\OAuth2\Client\Models\OAuthUser;

class AuthRequest
{
public function __invoke(Request $request)
{
$user = $request->attributes->get('salla.oauth.user');

if (!$user) {
return null;
}

return new OAuthUser($user);
}
}
8 changes: 8 additions & 0 deletions src/Auth/Guard.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace Salla\OAuth2\Client\Auth;

class Guard extends \Illuminate\Auth\RequestGuard
{

}
8 changes: 8 additions & 0 deletions src/Contracts/SallaOauth.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace Salla\OAuth2\Client\Contracts;

interface SallaOauth
{
public function getCurrentUser();
}
13 changes: 13 additions & 0 deletions src/Facade/SallaOauth.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Salla\OAuth2\Client\Facade;

use Illuminate\Support\Facades\Facade;

class SallaOauth extends Facade
{
protected static function getFacadeAccessor()
{
return \Salla\OAuth2\Client\Contracts\SallaOauth::class;
}
}
Loading

0 comments on commit 7c22716

Please sign in to comment.