Compare commits

...

5 Commits
1.2 ... master

  1. 241
      README.md
  2. 11
      config/bconnect.php
  3. 45
      src/Commands/RefreshTokens.php
  4. 58
      src/Commands/Sync.php
  5. 354
      src/Connect.php
  6. 56
      src/ConnectServiceProvider.php
  7. 15
      src/Controllers/ConnectController.php
  8. 47
      src/Traits/HasConnectData.php
  9. 54
      src/Traits/HasConnectSync.php
  10. 7
      src/Traits/HasConnectTokens.php
  11. 41
      src/Traits/HasConnectWebhook.php

241
README.md

@ -1,10 +1,10 @@
# laravel-connect
The Bluesquare Connect package allows you to use its OAuth server and sync its resources.
Ce package permet d'utiliser [Bluesquare Connect](https://connect.bluesquare.io) comme méthode d'authentification grâce au protocole OAuth 2.0.
## Installation
Update your `composer.json`:
Mettre à jour `composer.json` avec :
```
"repositories": [
@ -15,199 +15,194 @@ Update your `composer.json`:
]
```
Install the package:
Puis installer le package :
```bash
composer require bluesquare/laravel-connect "1.2"
composer require bluesquare/laravel-connect "2.1"
```
Finally, update your `.env` with your client's credentials:
Mettre à jour le `.env` avec les identifiants du client OAuth généré sur [Bluesquare Connect](https://connect.bluesquare.io) :
```bash
BCONNECT_CLIENT_ID=your_client_id
BCONNECT_CLIENT_SECRET=your_client_secret
BCONNECT_REDIRECT=http://localhost:8000/connect/callback
BCONNECT_REDIRECT="${APP_URL}/connect/callback"
```
### Sign in with Bluesquare Connect
Et optionnellement :
Follow there instructions to add Bluesquare Connect's authentication to your app.
Update your `routes/web.php`:
```bash
# URL du serveur OAuth
BCONNECT_URL=https://connect.bluesquare.io
```
Connect::routes();
# Données demandées (scopes)
BCONNECT_USER_SCOPES=profile
```
Add the "Sign in with Bluesquare Connect" button in your blade login page:
Il est possible de modifier d'autres comportements, à savoir :
- Model utilisateur utilisé (par défaut `App\Models\User`)
- URL de connexion via Bluesquare Connect (par défaut `/connect/authorize`)
- Remember me : garder la session active post-connexion (par défaut `true`)
```blade
<x-connect-button/>
```
Pour cela, il suffit de modifier le fichier `config/bconnect.php` généré via la commande `php artisan vendor:publish`.
Make sure that the `password` column of users table is nullable.
### Configuration minimale de `User`
#### Keep user tokens (optional)
À moins d'utiliser le trait `HasConnectData` (voir ci-dessous), il faut s'assurer que toutes les colonnes autres que `email` sont `nullable` dans la table `users` (y compris `password`).
La colonne `email` est alors utilisée comme identifiant de référence par Bluesquare Connect.
First, make sure that your model implements `HasConnectTokens` trait.
### Connexion
Then, add the following columns to your table:
Pour activer la connexion via Bluesquare Connect, il faut mettre à jour `web.php` en y ajoutant :
```
$table->text('connect_access_token')->nullable();
$table->text('connect_refresh_token')->nullable();
$table->dateTime('connect_expires_at')->nullable();
```
### Database syncing
```php
use Bluesquare\Connect\Facades\Connect;
Follow these instructions to sync your database with Bluesquare Connect.
Connect::routes();
```
In your `AppServiceProvider`, specify in the `boot()` function which entities you want to sync:
Si Blade est utilisé, un bouton "Connexion via Bluesquare Connect" peut être ajouté ainsi :
```
$connect->setSynchronized([
Role::class,
Company::class,
Team::class,
User::class,
UserTeam::class
]);
```blade
<x-connect-button/>
```
Your models must use `HasConnectSync` trait. This trait allows you to customize the syncing behavior.
Sinon il suffit de rediriger vers `/connect/authorize` pour déclencher le flux.
You also need to add this column to your synced tables:
### Configuration personnalisée de `User`
```
$table->unsignedBigInteger('connect_resource_id')->unique();
```
Le trait `HasConnectData` permet d'exploiter au maximum les données fournies par Bluesquare Connect. Notamment :
- Définir quelle colonne sert d'identifiant unique (par défaut `connect_id`) avec `$connectIdentifier` ;
- Définir quelles données sont à injectées dans le Model à la connexion, avec `$connectFillable`
_You can customize this column name and the syncing behavior in your model. Take a look at `HasConnectSync`._
Pour utiliser l'identifiant par défaut, il convient d'ajouter cette colonne à `User` :
Finally, use this command to sync everything:
```bash
php artisan connect:sync
```php
$table->string('connect_id')->nullable();
```
#### Live updates (optional)
Ou alors, et pour revenir à l'utilisation de `email` comme identifiant :
First, configure a webhook on Bluesquare Connect :
```php
use HasConnectData;
```
https://your-app.com/api/connect/webhook
protected $connectIdentifier = 'email';
```
Then, update your `routes/api.php`:
Ensuite, pour injecter automatiquement les données fournies par Bluesquare Connect (liste indicative ci-dessous) :
```
Connect::apiRoutes();
```php
protected $connectFillable = [
'name',
'email'
];
```
## Advanced usage
Il est possible de mapper les colonnes avec des noms différents et des valeurs par defaut, voire même d'injecter dans plusieurs colonnes, comme ceci :
### OAuth (sign in)
```php
protected $connectIdentifier = ['connect_id' => 'oauth_id'];
#### Authorization
protected $connectFillable = [
'name' => 'fullname|Anonymous',
'firstname' => ['firstname', 'nickname'],
'email' => 'email_address',
'group' => 'role|user'
];
```
Redirect to Bluesquare Connect authorization page:
## Synchronisation des données _(optionnel)_
```
public function authorize(Connect $connect)
{
return $connect->redirect($optional_custom_state);
}
```
Par défaut, les données des utilisateurs sont mises à jour à chaque nouvelle connexion.
Cependant, deux méthodes peuvent être utilisées pour conserver les données de tous les utilisateurs à jour sans reconnexion.
#### Authorization callback
### 1. Synchronisation passive
Auto: check state, login and redirect
Le trait `HasConnectTokens` permet de conserver les tokens OAuth pour une utilisation future (par exemple, pour synchroniser les utilisateurs périodiquement).
```
public function callback(Request $request, Connect $connect)
{
return $connect->loginFromCallback($request, $optional_redirect_to);
}
Avant tout, il faut ajouter ces colonnes dans la table `users` :
```php
$table->text('connect_access_token')->nullable();
$table->text('connect_refresh_token')->nullable();
$table->datetime('connect_expires_at')->nullable();
```
Manual: check state
Il est ensuite possible de mettre à jour les utilisateurs avec cette commande :
```
public function callback(Request $request, Connect $connect)
{
$valid = $connect->checkState($request);
// ...
}
```bash
php artisan connect:sync
```
#### Tokens management
Mais aussi de seulement mettre à jour les tokens avant expiration avec cette commande :
```bash
php artisan connect:refresh
```
// Retrieve tokens from an authorization code
$connect_data = $connect->getAccessTokenFromAuthorizationCode($code);
// Retrieve tokens from a refresh token
$connect_data = $connect->getAccessTokenFromRefreshToken($connect_data['refresh_token']);
Il est conseillé d'appeler ces commandes périodiquement via une tâche CRON dans `Console/Kernel.php`.
// With HasConnectTokens trait: get your local user tokens
$connect->getUserAccessToken($user);
```
### 2. Synchronisation active (webhook)
#### User data
Avant tout, il est requis de créer une `App` liée au client utilisé sur Bluesquare Connect, et d'en activer le webhook.
```
// Retrieve user data from an access token
$user_data = $connect->getUserData($connect_data['access_token']);
Ensuite, pour pouvoir utiliser le webhook, il faut ajouter ceci à `routes/api.php`:
// Example: find the corresponding user in your database
$user = User::where('email', $user_data['email'])->first();
```
use Bluesquare\Connect\Facades\Connect;
### OAuth (client)
Connect::apiRoutes();
```
#### Token management
Cela va permettre à Bluesquare Connect d'appeler cette URL à chaque modification d'un utilisateur :
```
// Get an access token
$connect->getAccessToken();
// Delete the current access token from cache
$connect->deleteAccessToken();
https://your-app.com/api/connect/webhook
```
#### API resources
Pour terminer, il suffit d'ajouter le trait `HasConnectWebhook` à `User`.
```
// Fetch all users
$connect->getAll('User');
#### Configurer le comportement du webhook
// Fetch an user
$connect->get('User', 1);
```
Par défaut, le webhook se comporte ainsi :
- Lorsqu'un utilisateur est créé, il est inséré dans `users` comme à la première connexion ;
- Lorsqu'un utilisateur est mis à jour, il est modifié comme à chaque connexion / synchronisation ;
- Lorsqu'un utilisateur est supprimé, deux cas se présentent :
- si `User` implémente `SoftDeletes`, alors le webhook fait appel à `$user->delete()` ;
- si `SoftDeletes` est absent, alors la session utilisateur est simplement expirée en repassant `remember_token` à `null`.
- Si l'utilisateur est restauré, deux cas se présentent :
- si `User` implémente `SoftDeletes` et que l'utilisateur est bien présent en base de données, alors le webhook fait appel à `$user->restore()` ;
- si `SoftDeletes` est absent ou que l'utilisateur n'existe pas, alors on recréé l'utilisateur (s'il existe, il est simplement mis à jour).
#### Syncing
Il est recommandé de personnaliser le cas de la suppression en ajoutant la fonction suivante à `User.php` :
```
// Sync everything
$optional_resource_types = ['User', ...];
$connect->syncAll($optional_resource_types);
```php
public function onConnectDelete(array $data)
{
// Optionnel : avec cette fonction on met à jour une dernière fois l'utilisateur
$this->onConnectUpdate($data);
// Sync a specific resource
$connect->sync('User', 1);
//...supprimer l'utilisateur comme souhaité...
}
```
### Webhook
Les autres cas peuvent être personnalisés avec ces différentes fonctions :
```
// Handle a webhook request
$connect->handleWebhook($request);
```php
public function onConnectCreate(array $data);
public function onConnectUpdate(array $data);
public function onConnectRestore(array $data);
```
### Configuration
## Données fournies par Bluesquare Connect
Publish our config file (`config/bconnect.php`) to customize the package configuration:
```bash
php artisan vendor:publish
```
- `id` et `connect_id` : identifiant unique de l'utilisateur
- `email` : adresse e-mail
- `name` : nom complet
- `firstname` et `nickname` : prénom
- `lastname` : nom de famille
- `avatar`, `picture` et `profile_picture` : URL de la photo de profil
- `company` : entreprise
- `job` : mêtier exercé dans l'entreprise
- `group` : rôle principal (les groupes sont personnalisées pour chaque App sur Bluesquare Connect)
- `groups` : tableau contenant tous les rôles associés à l'utilisateur

11
config/bconnect.php

@ -13,18 +13,19 @@ return [
'login_url' => '/connect/authorize',
/**
* OAuth callback URL
* Use post-login remember cookie
*/
'redirect_url' => env('BCONNECT_REDIRECT', 'http://localhost:8000/connect/callback'),
'login_remember' => true,
/**
* OAuth client id
* OAuth callback URL
*/
'client_id' => env('BCONNECT_CLIENT_ID', null),
'redirect_url' => env('BCONNECT_REDIRECT', 'http://localhost:8000/connect/callback'),
/**
* OAuth client secret
* OAuth client identifiers
*/
'client_id' => env('BCONNECT_CLIENT_ID', null),
'client_secret' => env('BCONNECT_CLIENT_SECRET', null),
/**

45
src/Commands/RefreshTokens.php

@ -0,0 +1,45 @@
<?php
namespace Bluesquare\Connect\Commands;
use Bluesquare\Connect\Connect;
use Bluesquare\Connect\ConnectException;
use Bluesquare\Connect\Traits\HasConnectTokens;
use Illuminate\Console\Command;
class RefreshTokens extends Command
{
protected $signature = 'connect:refresh';
protected $description = 'Refresh Bluesquare Connect tokens';
public function handle(Connect $connect)
{
$class = config('bconnect.model');
$has_fields = in_array(HasConnectTokens::class, class_uses($class));
if (! $has_fields) {
throw new ConnectException("$class does not implement HasConnectTokens");
}
$class::query()->chunks(10, function ($models) use ($connect) {
$models->each(function ($model) use ($connect) {
if (! empty($model->connect_refresh_token) && $model->connect_expires_at <= now()->addHour()) {
try {
$tokens = $connect->getAccessTokenFromRefreshToken($model->connect_refresh_token);
$connect->updateUserConnectData($model, $tokens);
$model->save();
}
catch (\Exception $exception) {
$this->warn("Failed to refresh model tokens", $model->toArray());
}
}
});
});
$this->info("Tokens refreshed");
return 0;
}
}

58
src/Commands/Sync.php

@ -3,41 +3,45 @@
namespace Bluesquare\Connect\Commands;
use Bluesquare\Connect\Connect;
use Bluesquare\Connect\ConnectException;
use Bluesquare\Connect\Traits\HasConnectTokens;
use Illuminate\Console\Command;
class Sync extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'connect:sync';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Synchronize Bluesquare Connect resources';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
protected $description = 'Sync Bluesquare Connect users';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle(Connect $connect)
{
$connect->syncAll();
$this->call('connect:refresh');
$class = config('bconnect.model');
$has_fields = in_array(HasConnectTokens::class, class_uses($class));
if (! $has_fields) {
throw new ConnectException("$class does not implement HasConnectTokens");
}
$class::query()->chunks(10, function ($models) use ($connect) {
$models->each(function ($model) use ($connect) {
try {
if (! empty($model->connect_access_token)) {
$data = $connect->getUserData($model->connect_access_token);
$connect->updateUserData($model, $data);
$model->save();
}
}
catch (\Exception $exception) {
$this->warn("Failed to sync model data", $model->toArray());
}
});
});
$this->info("Models synced");
return 0;
}
}

354
src/Connect.php

@ -2,8 +2,9 @@
namespace Bluesquare\Connect;
use Bluesquare\Connect\Traits\HasConnectSync;
use Bluesquare\Connect\Traits\HasConnectData;
use Bluesquare\Connect\Traits\HasConnectTokens;
use Bluesquare\Connect\Traits\HasConnectWebhook;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Routing\Router;
@ -14,59 +15,13 @@ use Psr\Http\Message\StreamInterface;
class Connect
{
protected static $resources = [
'Role',
'Company',
'Team',
'User',
'UserTeam'
];
protected static $foreignKeys = [
'role_id' => 'Role',
'company_id' => 'Company',
'team_id' => 'Team',
'user_id' => 'User',
'user_teams_id' => 'UserTeam'
];
protected $app;
protected $synchronized = [];
public function __construct($app)
{
$this->app = $app;
}
// User config
public function setSynchronized($models)
{
$items = [];
foreach ($models as $model)
{
if (!in_array(HasConnectSync::class, class_uses($model)))
throw new ConnectException("$model does not implement HasConnectSync trait.");
$class = explode('\\', $model);
$resource = $model::$connectResource ?? end($class);
$items[$resource] = $model;
}
$synchronized = [];
foreach (self::$resources as $resourceType) { // Re-ordering
foreach ($items as $resource => $model) {
if ($resource == $resourceType)
$synchronized[$resource] = $model;
}
}
$this->synchronized = $synchronized;
}
// API
/**
@ -76,7 +31,7 @@ class Connect
* @return array
* @throws ConnectException
*/
public function request($method, $uri, $data = null, $auth = true): array
public function request($method, $uri, $data = null, $access_token = null): array
{
$url = $this->getUrl();
$url = $url . '/' . trim($uri, '/');
@ -89,14 +44,11 @@ class Connect
]
];
if ($auth === true) {
$config['headers']['Authorization'] = 'Bearer ' . $this->getAccessToken();
}
elseif ($auth !== false) {
$config['headers']['Authorization'] = 'Bearer ' . $auth;
if (! is_null($access_token)) {
$config['headers']['Authorization'] = 'Bearer ' . $access_token;
}
if (!is_null($data)) {
if (! is_null($data)) {
$config['form_params'] = $data;
}
@ -110,12 +62,13 @@ class Connect
return json_decode($body, true);
} catch(\Exception $e) {
$this->deleteAccessToken();
$this->flushTokens();
throw new ConnectException($e->getMessage());
}
}
// OAuth (user)
// Authorization flow
public function redirect($state = null)
{
@ -123,9 +76,12 @@ class Connect
$state = Str::random();
$states = session()->get('connect_states');
if (!is_array($states))
if (! is_array($states))
$states = [];
$states[] = $state;
session()->put('connect_states', $states);
$query = http_build_query([
@ -137,106 +93,80 @@ class Connect
]);
$url = $this->getUrl() . '/oauth/authorize?' . $query;
return redirect()->to($url);
}
public function checkState(Request $request)
{
if (!session()->has('connect_states')) {
Log::debug("Missing session states");
if (! session()->has('connect_states'))
return false;
}
$states = session()->get('connect_states');
if (!is_array($states)) {
Log::debug("Invalid session state");
if (! is_array($states))
return false;
}
if (!$request->has('state') || !in_array($request->state, $states)) {
Log::debug("Missing valid state in request");
if (! $request->has('state') || ! in_array($request->state, $states))
return false;
}
unset($states[array_search($request->state, $states)]);
session()->put('connect_states', $states);
return true;
}
public function loginFromCallback(Request $request, $redirect_to = '/')
{
if (!$this->checkState($request))
return redirect('/');
// Code check
if (!$request->has('code')) {
Log::debug("Missing authorization code");
if (! $this->checkState($request) || ! $request->has('code'))
return redirect('/');
}
// Access token
$expires_at = now();
$connect_data = $this->getAccessTokenFromAuthorizationCode($request->code);
$connect_data = $this->getAccessTokenFromAuthorizationCode($request->get('code'));
$connect_data['expires_at'] = $expires_at->addSeconds($connect_data['expires_in']);
$model_data = $this->getUserData($connect_data['access_token']);
$model = config('bconnect.model');
// User data
if (in_array($model, $this->synchronized)) {
$user = $model::findConnectResource($model_data['id']) ?? new $model;
}
else {
$user = $model::where('email', $model_data['email'])->first() ?? new $model;
}
$model_data = $this->convertForeignKeys($model_data);
$user->fill($model_data);
if (in_array($model, $this->synchronized))
$user->{$model::$connectColumnId} = $model_data['id'];
$user_data = $this->getUserData($connect_data['access_token']);
$user = $this->sync('create', $user_data);
$this->updateUserConnectData($user, $connect_data);
$user->save();
if (in_array($model, $this->synchronized))
$user = $model::findConnectResource($model_data['id']);
$this->updateUserConnectData($user, $connect_data);
// Login
auth()->login($user, true);
auth()->login($user, config('bconnect.login_remember', true));
return redirect($redirect_to);
}
// OAuth methods
public function getAccessTokenFromAuthorizationCode($code)
{
$data = $this->request('post', 'oauth/token', [
return $this->request('post', 'oauth/token', [
'grant_type' => 'authorization_code',
'client_id' => config('bconnect.client_id'),
'client_secret' => config('bconnect.client_secret'),
'scope' => config('bconnect.user_scopes'),
'redirect_uri' => config('bconnect.redirect_url'),
'code' => $code
], false);
return $data;
]);
}
public function getAccessTokenFromRefreshToken($refresh_token)
{
$data = $this->request('post', 'oauth/token', [
return $this->request('post', 'oauth/token', [
'grant_type' => 'refresh_token',
'client_id' => config('bconnect.client_id'),
'client_secret' => config('bconnect.client_secret'),
'scope' => config('bconnect.user_scopes'),
'redirect_uri' => config('bconnect.redirect_url'),
'refresh_token' => $refresh_token
], false);
return $data;
]);
}
public function getUserData($access_token)
@ -244,164 +174,98 @@ class Connect
return $this->request('get', 'api/user', null, $access_token);
}
public function updateUserConnectData($user, $data)
{
if (!in_array(HasConnectTokens::class, class_uses(get_class($user))))
return false;
$user->connect_access_token = $data['access_token'];
$user->connect_refresh_token = $data['refresh_token'];
$user->connect_expires_at = $data['expires_at'];
return $user->save();
}
public function getUserAccessToken($user)
public function getUserAccessToken($model)
{
$has_fields = in_array(HasConnectTokens::class, class_uses(get_class($user)));
$class = get_class($model);
$has_fields = in_array(HasConnectTokens::class, class_uses($class));
if (!$has_fields) {
throw new ConnectException("User class does not implement HasConnectTokens");
if (! $has_fields) {
throw new ConnectException("$class does not implement HasConnectTokens");
}
if ($user->connect_expires_at <= now()) {
$connect_data = $this->getAccessTokenFromRefreshToken($user->connect_refresh_token);
$this->updateUserConnectData($user, $connect_data);
if ($model->connect_expires_at <= now()->addHour()) {
$connect_data = $this->getAccessTokenFromRefreshToken($model->connect_refresh_token);
$this->updateUserConnectData($model, $connect_data);
return $connect_data['access_token'];
}
return $user->connect_access_token;
return $model->connect_access_token;
}
// OAuth (client)
// Sync
public function getAccessToken()
public function sync(string $event, array $data)
{
$access_token = cache()->get('bconnect.access_token');
$access_token_expiration = cache()->get('bconnect.access_token_expiration');
$class = config('bconnect.model');
if ($access_token && $access_token_expiration > time() + 60) {
return $access_token;
}
$data = $this->request('post', '/oauth/token', [
'grant_type' => 'client_credentials',
'client_id' => config('bconnect.client_id'),
'client_secret' => config('bconnect.client_secret'),
'scope' => config('bconnect.client_scopes')
], false);
cache()->set('bconnect.access_token', $data['access_token']);
cache()->set('bconnect.access_token_expiration', time() + $data['expires_in']);
return $data['access_token'];
}
if (in_array($event, ['update', 'delete'])) {
$model = $this->resolveUser($data);
public function deleteAccessToken()
{
cache()->delete('bconnect.access_token');
cache()->delete('bconnect.access_token_expiration');
}
// Webhook handler
/**
* @param Request $request
* @return bool
*/
public function handleWebhook(Request $request)
{
$data = $request->validate([
'connectEventType' => 'required|in:created,updated,deleted',
'connectResourceType' => 'required',
'connectResourceTable' => 'required',
'connectResourceData' => 'required|array',
'connectResourceData.id' => 'required'
]);
if (!array_key_exists($data['connectResourceType'], $this->synchronized))
return false;
$model = $this->synchronized[$data['connectResourceType']];
$method = $this->getEventMethod($data['connectEventType']);
$data = $data['connectResourceData'];
try {
$data = $this->get($data['connectResourceType'], $data['connectResourceData']['id']);
if ($data['connectEventType'] == 'deleted') {
abort(403, "This resource still exists.");
}
} catch (\Exception $e) {
if ($data['connectEventType'] != 'deleted') {
abort(404, "Could not retrieve this resource.");
if (! $model->exists() && $event === 'delete')
return $model;
}
else {
$hasSoftDeletes = in_array(\Illuminate\Database\Eloquent\SoftDeletes::class, class_uses($class));
$model = $this->resolveUser($data, $hasSoftDeletes);
if ($model->exists()) {
if ($hasSoftDeletes && $model->trashed()) {
$event = 'restore';
} else {
$event = 'update';
}
}
}
$data = $this->convertForeignKeys($data);
$model::$method($data['id'], $data);
if (in_array(HasConnectWebhook::class, class_uses($class))) {
$method = 'onConnect' . ucfirst($event);
$model->$method($data);
} else {
$this->updateUserData($model, $data);
$model->save();
}
return true;
return $model;
}
// Resources getters
public function getAll($resourceType)
public function updateUserConnectData($user, $data)
{
return $this->request('get', "api/resources/$resourceType");
if (in_array(HasConnectTokens::class, class_uses(get_class($user))))
$user->fillConnectTokens($data);
}
public function get($resourceType, $resourceId)
public function updateUserData($user, $data)
{
return $this->request('get', "api/resources/$resourceType/$resourceId");
if (in_array(HasConnectData::class, class_uses(get_class($user))))
$user->fillConnectData($data);
}
// Resources syncing
public function syncAll($resourceTypes = null)
protected function resolveUser($data, $withTrashed = false)
{
$resourceTypes = $resourceTypes ?? $this->synchronized;
$class = config('bconnect.model');
$query = $class::query();
foreach ($resourceTypes as $resourceType)
{
$resourceType = $this->resolveResourceType($resourceType);
if ($withTrashed)
$query->withTrashed();
if (!array_key_exists($resourceType, $this->synchronized))
throw new ConnectException("Resource $resourceType not declared as synchronized.");
$model = new $class;
$resources = $this->getAll($resourceType);
$model = $this->synchronized[$resourceType];
$identifiers = [];
if (in_array(HasConnectData::class, class_uses($class))) {
$id = $model->getConnectIdentifier();
foreach ($resources as $data)
{
$identifiers[] = intval($data['id']);
$this->sync($resourceType, $data['id'], $data);
}
$origin = is_array($id) ? $id[0] : $id;
$target = is_array($id) ? $id[1] : $id;
foreach ($model::all() as $item)
{
if (!in_array(intval($item->{$model::$connectColumnId}), $identifiers))
$model::onConnectResourceDoesNotExist($item);
}
}
}
public function sync($resourceType, $resourceId, $resourceData = null)
{
$resourceType = $this->resolveResourceType($resourceType);
$model = $query->where($target, $data[$origin])->first() ?? $model;
$model->$target = $data[$origin];
} else {
$model = $query->where('email', $data['email'])->first() ?? $model;
if (is_null($resourceData)) {
$resourceData = $this->get($resourceType, $resourceId);
if (! $model->exists())
$model->email = $data['email'];
}
$model = $this->synchronized[$resourceType];
$item = $model::findConnectResource($resourceId);
$method = $this->getEventMethod($item ? 'updated' : 'created');
$data = $this->convertForeignKeys($resourceData);
$model::$method($resourceId, $data);
return $model;
}
// Routing
@ -425,44 +289,14 @@ class Connect
// Misc
protected function resolveResourceType($class)
protected function flushTokens()
{
if (in_array($class, $this->synchronized))
return array_flip($this->synchronized)[$class];
return $class;
}
protected function resolveResourceModel($class)
{
if (array_key_exists($class, $this->synchronized))
return $this->synchronized[$class];
return $class;
}
protected function getEventMethod($event)
{
return 'onConnectResource' . ucfirst($event);
session()->forget('bconnect.access_token');
session()->forget('bconnect.access_token_expiration');
}
protected function getUrl()
{
return config('bconnect.url') ?? 'https://connect.bluesquare.io';
}
protected function convertForeignKeys($data)
{
foreach (self::$foreignKeys as $key => $resourceType)
{
if (!array_key_exists($key, $data)) continue;
if (!array_key_exists($resourceType, $this->synchronized)) continue;
$model = $this->resolveResourceModel($resourceType);
$record = $model::findConnectResource($data[$key]);
$data[$key] = $record ? $record->id : null;
}
return $data;
}
}

56
src/ConnectServiceProvider.php

@ -2,70 +2,54 @@
namespace Bluesquare\Connect;
use Bluesquare\Connect\Commands\RefreshTokens;
use Bluesquare\Connect\Commands\Sync;
use Illuminate\Support\ServiceProvider;
class ConnectServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
// Config
$this->mergeConfigFrom(
__DIR__ . '/../config/bconnect.php',
'bconnect'
);
// Singletons
$this->mergeConfigFrom($this->path('config/bconnect.php'), 'bconnect');
$this->app->singleton(Connect::class, function ($app) {
return new Connect($app);
});
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// Config
$config_path = $this->path('config/bconnect.php');
$views_path = $this->path('resources/views/connect');
$this->publishes([
__DIR__ . '/../config/bconnect.php' => config_path('bconnect.php')
$config_path => config_path('bconnect.php'),
$views_path => resource_path('views/vendor/connect'),
]);
// Translations
$this->loadTranslationsFrom(__DIR__.'/../resources/translations', 'connect');
// Views
$this->loadTranslationsFrom($this->path('resources/translations'), 'connect');
$this->loadViewsFrom(__DIR__.'/../resources/views/connect', 'connect');
$this->loadViewsFrom($this->path('resources/views/connect'), 'connect');
$this->publishes([
__DIR__.'/../resources/views/connect' => resource_path('views/vendor/connect'),
]);
if ($this->app->runningInConsole()) {
$this->commands([
RefreshTokens::class,
Sync::class,
]);
}
// Laravel 7+
if (method_exists($this, 'loadViewComponentsAs')) {
// Laravel 7+
$this->loadViewComponentsAs('connect', [
\Bluesquare\Connect\View\Components\Button::class
]);
}
}
// Commands
// Misc
if ($this->app->runningInConsole()) {
$this->commands([
Sync::class
]);
}
private function path($path = '')
{
return __DIR__ . "/../$path";
}
}

15
src/Controllers/ConnectController.php

@ -20,6 +20,19 @@ class ConnectController extends Controller
public function webhook(Request $request, Connect $connect)
{
return $connect->handleWebhook($request);
$hash = sha1(config('bconnect.client_secret') . date('Y-m-d'));
if ($request->header('x-connect-hash') !== $hash)
abort(403);
$data = $request->validate([
'event_type' => 'required|in:create,update,delete',
'connect_data' => 'required|array',
'connect_data.*' => 'nullable',
'connect_data.id' => 'required',
'connect_data.email' => 'required_if:event_type,create|required_if:event_type,update',
]);
$connect->sync($data['event_type'], $data['connect_data']);
}
}

47
src/Traits/HasConnectData.php

@ -0,0 +1,47 @@
<?php
namespace Bluesquare\Connect\Traits;
use Illuminate\Support\Facades\Log;
trait HasConnectData
{
public function getConnectIdentifier()
{
return $this->connectIdentifier ?? 'connect_id';
}
public function fillConnectData(array $data)
{
$touched = [];
$fillable = $this->connectFillable ?? [];
foreach ($fillable as $origin => $targets) {
$value = is_string($origin) ? $data[$origin] : $data[$targets];
$targets = is_string($origin) && is_array($targets) ? $targets : [$targets];
foreach ($targets as $target) {
$parts = explode('|', $target);
$target = $parts[0];
$currentValue = $value ?? ($parts[1] ?? null);
$target_model = $this;
$parts = explode('.', $target);
foreach ($parts as $i => $property) {
if ($i < count($parts) - 1) {
$target_model = $target_model->$property;
continue;
}
if ($target_model !== $this)
$touched[] = $target_model;
$target_model->$property = $currentValue;
}
}
}
foreach ($touched as $model)
$model->save();
}
}

54
src/Traits/HasConnectSync.php

@ -1,54 +0,0 @@
<?php
namespace Bluesquare\Connect\Traits;
trait HasConnectSync
{
abstract function fill(array $attributes);
abstract function save();
abstract function delete();
public static $connectResource;
public static $connectColumnId = 'connect_resource_id';
public static function findConnectResource($id)
{
return self::query()->where(self::$connectColumnId, $id)->first();
}
public static function onConnectResourceCreated($id, $data)
{
$record = self::findConnectResource($id) ?? new self;
$attributes = $record->getConnectFillableAttributes();
foreach ($data as $key => $value) {
if (in_array($key, $attributes))
$record->$key = $value;
}
$record->{self::$connectColumnId} = $id;
return $record->save();
}
public static function onConnectResourceUpdated($id, $data)
{
return self::onConnectResourceCreated($id, $data);
}
public static function onConnectResourceDeleted($id, $data = null)
{
$record = self::findConnectResource($id);
return $record ? $record->forceDelete() : false;
}
public static function onConnectResourceDoesNotExist($record)
{
return $record->forceDelete();
}
public function getConnectFillableAttributes()
{
return $this->fillable;
}
}

7
src/Traits/HasConnectTokens.php

@ -4,5 +4,10 @@ namespace Bluesquare\Connect\Traits;
trait HasConnectTokens
{
//
public function fillConnectTokens(array $data)
{
$this->connect_access_token = $data['access_token'];
$this->connect_refresh_token = $data['refresh_token'];
$this->connect_expires_at = $data['expires_at'];
}
}

41
src/Traits/HasConnectWebhook.php

@ -0,0 +1,41 @@
<?php
namespace Bluesquare\Connect\Traits;
trait HasConnectWebhook
{
public function onConnectCreate(array $data)
{
$this->onConnectUpdate($data);
}
public function onConnectUpdate(array $data)
{
if (in_array(HasConnectData::class, class_uses(self::class))) {
$this->fillConnectData($data);
} else {
$this->email = $data['email'];
}
$this->save();
}
public function onConnectDelete(array $data)
{
$this->onConnectUpdate($data);
if (in_array(\Illuminate\Database\Eloquent\SoftDeletes::class, class_uses(self::class))) {
$this->delete();
} elseif (array_key_exists('remember_token', $this->attributes)) {
$this->remember_token = null;
$this->save();
}
}
public function onConnectRestore(array $data)
{
$this->restore();
$this->onConnectUpdate($data);
}
}
Loading…
Cancel
Save