Compare commits
12 Commits
Author | SHA1 | Date |
---|---|---|
|
1201ef254e | |
|
abce313193 | |
|
9d17dacae2 | |
|
0d1885bead | |
|
887d5239fd | |
|
de0f263a46 | |
|
830ebbcdd3 | |
|
4156db2cdc | |
|
7b3a698daa | |
|
3b79a880ae | |
|
14b47b6f6e | |
|
eda52c3d65 |
309
README.md
309
README.md
|
@ -1,216 +1,217 @@
|
|||
# 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 les sources de `composer.json` avec :
|
||||
|
||||
```
|
||||
"require": {
|
||||
"bluesquare/laravel-connect": "dev-master"
|
||||
}
|
||||
"repositories": [
|
||||
{
|
||||
"type": "vcs",
|
||||
"url": "https://git.bluesquare.io/bluesquare/laravel-connect"
|
||||
}
|
||||
]
|
||||
composer config repositories.connect vcs https://git.bluesquare.io/bluesquare/laravel-connect.git -n
|
||||
```
|
||||
|
||||
Install the package:
|
||||
Puis installer le package :
|
||||
|
||||
```bash
|
||||
composer update bluesquare/laravel-connect
|
||||
composer require bluesquare/laravel-connect "2.3"
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
# Données demandées (scopes)
|
||||
BCONNECT_USER_SCOPES=profile
|
||||
```
|
||||
|
||||
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`)
|
||||
|
||||
Pour cela, il suffit de modifier le fichier `config/bconnect.php` généré via la commande `php artisan vendor:publish`.
|
||||
|
||||
### Configuration minimale de `User`
|
||||
|
||||
À 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.
|
||||
|
||||
### Connexion
|
||||
|
||||
Pour activer la connexion via Bluesquare Connect, il faut mettre à jour `web.php` en y ajoutant :
|
||||
|
||||
```php
|
||||
use Bluesquare\Connect\Facades\Connect;
|
||||
|
||||
Connect::routes();
|
||||
```
|
||||
|
||||
Add the "Sign in with Bluesquare Connect" button in your blade login page:
|
||||
Si Blade est utilisé, un bouton "Connexion via Bluesquare Connect" peut être ajouté ainsi :
|
||||
|
||||
```blade
|
||||
<x-connect-button/>
|
||||
```
|
||||
|
||||
Make sure that the `password` column of users table is nullable.
|
||||
Sinon il suffit de rediriger vers `/connect/authorize` pour déclencher le flux.
|
||||
|
||||
#### Keep user tokens (optional)
|
||||
### Configuration personnalisée de `User`
|
||||
|
||||
First, make sure that your model implements `HasConnectTokens` trait.
|
||||
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`
|
||||
|
||||
Then, add the following columns to your table:
|
||||
Pour utiliser l'identifiant par défaut, il convient d'ajouter cette colonne à `User` :
|
||||
|
||||
```php
|
||||
$table->string('connect_id')->nullable();
|
||||
```
|
||||
|
||||
Ou alors, et pour revenir à l'utilisation de `email` comme identifiant :
|
||||
|
||||
```php
|
||||
use HasConnectData;
|
||||
|
||||
protected $connectIdentifier = 'email';
|
||||
```
|
||||
|
||||
Ensuite, pour injecter automatiquement les données fournies par Bluesquare Connect (liste indicative ci-dessous) :
|
||||
|
||||
```php
|
||||
protected $connectFillable = [
|
||||
'name',
|
||||
'email'
|
||||
];
|
||||
```
|
||||
|
||||
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 :
|
||||
|
||||
```php
|
||||
protected $connectIdentifier = ['connect_id' => 'oauth_id'];
|
||||
|
||||
protected $connectFillable = [
|
||||
'name' => 'fullname|Anonymous',
|
||||
'firstname' => ['firstname', 'nickname'],
|
||||
'email' => 'email_address',
|
||||
'group' => 'role|user'
|
||||
];
|
||||
```
|
||||
|
||||
Un hook est disponible pour un post-traitement des données Connect (après création / mise à jour de l'utilisateur) ce qui peut être utile pour mettre à jour des relations :
|
||||
|
||||
```php
|
||||
use HasConnectData;
|
||||
|
||||
public function postFillConnectData(array $data)
|
||||
{
|
||||
// Exemple
|
||||
$this->roles()->sync(
|
||||
Role::whereIn('name', $data['groups'])->pluck('id')
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Synchronisation des données _(optionnel)_
|
||||
|
||||
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.
|
||||
|
||||
### 1. Synchronisation passive
|
||||
|
||||
Le trait `HasConnectTokens` permet de conserver les tokens OAuth pour une utilisation future (par exemple, pour synchroniser les utilisateurs périodiquement).
|
||||
|
||||
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();
|
||||
$table->datetime('connect_expires_at')->nullable();
|
||||
```
|
||||
|
||||
### Database syncing
|
||||
|
||||
Follow these instructions to sync your database with Bluesquare Connect.
|
||||
|
||||
In your `AppServiceProvider`, specify in the `boot()` function which entities you want to sync:
|
||||
|
||||
```
|
||||
$connect->setSynchronized([
|
||||
Role::class,
|
||||
Company::class,
|
||||
Team::class,
|
||||
User::class,
|
||||
UserTeam::class
|
||||
]);
|
||||
```
|
||||
|
||||
Your models must use `HasConnectSync` trait. This trait allows you to customize the syncing behavior.
|
||||
|
||||
You also need to add this column to your synced tables:
|
||||
|
||||
```
|
||||
$table->unsignedBigInteger('connect_resource_id')->unique();
|
||||
```
|
||||
|
||||
_You can customize this column name and the syncing behavior in your model. Take a look at `HasConnectSync`._
|
||||
|
||||
Finally, use this command to sync everything:
|
||||
Il est ensuite possible de mettre à jour les utilisateurs avec cette commande :
|
||||
|
||||
```bash
|
||||
php artisan connect:sync
|
||||
```
|
||||
|
||||
#### Live updates (optional)
|
||||
Mais aussi de seulement mettre à jour les tokens avant expiration avec cette commande :
|
||||
|
||||
First, configure a webhook on Bluesquare Connect :
|
||||
```bash
|
||||
php artisan connect:refresh
|
||||
```
|
||||
|
||||
Il est conseillé d'appeler ces commandes périodiquement via une tâche CRON dans `Console/Kernel.php`.
|
||||
|
||||
### 2. Synchronisation active (webhook)
|
||||
|
||||
Avant tout, il est requis de créer une `App` liée au client utilisé sur Bluesquare Connect, et d'en activer le webhook.
|
||||
|
||||
Ensuite, pour pouvoir utiliser le webhook, il faut ajouter ceci à `routes/api.php`:
|
||||
|
||||
```
|
||||
use Bluesquare\Connect\Facades\Connect;
|
||||
|
||||
Connect::apiRoutes();
|
||||
```
|
||||
|
||||
Cela va permettre à Bluesquare Connect d'appeler cette URL à chaque modification d'un utilisateur :
|
||||
|
||||
```
|
||||
https://your-app.com/api/connect/webhook
|
||||
```
|
||||
|
||||
Then, update your `routes/api.php`:
|
||||
Pour terminer, il suffit d'ajouter le trait `HasConnectWebhook` à `User`.
|
||||
|
||||
```
|
||||
Connect::apiRoutes();
|
||||
```
|
||||
#### Configurer le comportement du webhook
|
||||
|
||||
## Advanced usage
|
||||
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).
|
||||
|
||||
### OAuth (sign in)
|
||||
Il est recommandé de personnaliser le cas de la suppression en ajoutant la fonction suivante à `User.php` :
|
||||
|
||||
#### Authorization
|
||||
|
||||
Redirect to Bluesquare Connect authorization page:
|
||||
|
||||
```
|
||||
public function authorize(Connect $connect)
|
||||
```php
|
||||
public function onConnectDelete(array $data)
|
||||
{
|
||||
return $connect->redirect($optional_custom_state);
|
||||
// Optionnel : avec cette fonction on met à jour une dernière fois l'utilisateur
|
||||
$this->onConnectUpdate($data);
|
||||
|
||||
//...supprimer l'utilisateur comme souhaité...
|
||||
}
|
||||
```
|
||||
|
||||
#### Authorization callback
|
||||
Les autres cas peuvent être personnalisés avec ces différentes fonctions :
|
||||
|
||||
Auto: check state, login and redirect
|
||||
|
||||
```
|
||||
public function callback(Request $request, Connect $connect)
|
||||
{
|
||||
return $connect->loginFromCallback($request, $optional_redirect_to);
|
||||
}
|
||||
```php
|
||||
public function onConnectCreate(array $data);
|
||||
public function onConnectUpdate(array $data);
|
||||
public function onConnectRestore(array $data);
|
||||
```
|
||||
|
||||
Manual: check state
|
||||
## Données fournies par Bluesquare Connect
|
||||
|
||||
```
|
||||
public function callback(Request $request, Connect $connect)
|
||||
{
|
||||
$valid = $connect->checkState($request);
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
#### Tokens management
|
||||
|
||||
```
|
||||
// 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']);
|
||||
|
||||
// With HasConnectTokens trait: get your local user tokens
|
||||
$connect->getUserAccessToken($user);
|
||||
```
|
||||
|
||||
#### User data
|
||||
|
||||
```
|
||||
// Retrieve user data from an access token
|
||||
$user_data = $connect->getUserData($connect_data['access_token']);
|
||||
|
||||
// Example: find the corresponding user in your database
|
||||
$user = User::where('email', $user_data['email'])->first();
|
||||
```
|
||||
|
||||
### OAuth (client)
|
||||
|
||||
#### Token management
|
||||
|
||||
```
|
||||
// Get an access token
|
||||
$connect->getAccessToken();
|
||||
|
||||
// Delete the current access token from cache
|
||||
$connect->deleteAccessToken();
|
||||
```
|
||||
|
||||
#### API resources
|
||||
|
||||
```
|
||||
// Fetch all users
|
||||
$connect->getAll('User');
|
||||
|
||||
// Fetch an user
|
||||
$connect->get('User', 1);
|
||||
```
|
||||
|
||||
#### Syncing
|
||||
|
||||
```
|
||||
// Sync everything
|
||||
$optional_resource_types = ['User', ...];
|
||||
$connect->syncAll($optional_resource_types);
|
||||
|
||||
// Sync a specific resource
|
||||
$connect->sync('User', 1);
|
||||
```
|
||||
|
||||
### Webhook
|
||||
|
||||
```
|
||||
// Handle a webhook request
|
||||
$connect->handleWebhook($request);
|
||||
```
|
||||
|
||||
### Configuration
|
||||
|
||||
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
|
|
@ -35,8 +35,8 @@
|
|||
}
|
||||
},
|
||||
"require": {
|
||||
"guzzlehttp/guzzle": "^7.2",
|
||||
"php": "^7.2"
|
||||
"guzzlehttp/guzzle": "^7.3",
|
||||
"php": "^7.3|^8.0"
|
||||
},
|
||||
"prefer-stable": true
|
||||
}
|
||||
|
|
|
@ -5,7 +5,7 @@ return [
|
|||
/**
|
||||
* OAuth model
|
||||
*/
|
||||
'model' => \App\User::class,
|
||||
'model' => \App\Models\User::class,
|
||||
|
||||
/**
|
||||
* Route that redirects to Bluesquare Connect
|
||||
|
@ -13,18 +13,19 @@ return [
|
|||
'login_url' => '/connect/authorize',
|
||||
|
||||
/**
|
||||
* Use post-login remember cookie
|
||||
*/
|
||||
'login_remember' => true,
|
||||
|
||||
/**
|
||||
* OAuth callback URL
|
||||
*/
|
||||
'redirect_url' => env('BCONNECT_REDIRECT', 'http://localhost:8000/connect/callback'),
|
||||
|
||||
/**
|
||||
* OAuth client id
|
||||
* OAuth client identifiers
|
||||
*/
|
||||
'client_id' => env('BCONNECT_CLIENT_ID', null),
|
||||
|
||||
/**
|
||||
* OAuth client secret
|
||||
*/
|
||||
'client_secret' => env('BCONNECT_CLIENT_SECRET', null),
|
||||
|
||||
/**
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -3,41 +3,50 @@
|
|||
namespace Bluesquare\Connect\Commands;
|
||||
|
||||
use Bluesquare\Connect\Connect;
|
||||
use Bluesquare\Connect\ConnectException;
|
||||
use Bluesquare\Connect\Traits\HasConnectData;
|
||||
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';
|
||||
protected $description = 'Sync Bluesquare Connect users';
|
||||
|
||||
/**
|
||||
* Create a new command instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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();
|
||||
|
||||
if (in_array(HasConnectData::class, class_uses($model))) {
|
||||
$model->postFillConnectData($data);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (\Exception $exception) {
|
||||
$this->warn("Failed to sync model data", $model->toArray());
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$this->info("Models synced");
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
|
379
src/Connect.php
379
src/Connect.php
|
@ -2,9 +2,11 @@
|
|||
|
||||
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\Contracts\Foundation\Application;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Router;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
@ -14,59 +16,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)
|
||||
public function __construct(Application $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 +32,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 +45,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 +63,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 +77,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 +94,80 @@ class Connect
|
|||
]);
|
||||
|
||||
$url = $this->getUrl() . '/oauth/authorize?' . $query;
|
||||
return redirect()->to($url);
|
||||
|
||||
return redirect($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))
|
||||
if (! $this->checkState($request) || ! $request->has('code'))
|
||||
return redirect('/');
|
||||
|
||||
// Code check
|
||||
|
||||
if (!$request->has('code')) {
|
||||
Log::debug("Missing authorization 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']);
|
||||
// Login
|
||||
|
||||
$this->updateUserConnectData($user, $connect_data);
|
||||
|
||||
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 +175,102 @@ class Connect
|
|||
return $this->request('get', 'api/user', null, $access_token);
|
||||
}
|
||||
|
||||
public function updateUserConnectData($user, $data)
|
||||
public function getUserAccessToken($model)
|
||||
{
|
||||
if (!in_array(HasConnectTokens::class, class_uses(get_class($user))))
|
||||
return false;
|
||||
$class = get_class($model);
|
||||
$has_fields = in_array(HasConnectTokens::class, class_uses($class));
|
||||
|
||||
$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)
|
||||
{
|
||||
$has_fields = in_array(HasConnectTokens::class, class_uses(get_class($user)));
|
||||
|
||||
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;
|
||||
if (in_array($event, ['update', 'delete'])) {
|
||||
$model = $this->resolveUser($data);
|
||||
|
||||
if (! $model->exists() && $event === 'delete')
|
||||
return $model;
|
||||
}
|
||||
else {
|
||||
$hasSoftDeletes = in_array(\Illuminate\Database\Eloquent\SoftDeletes::class, class_uses($class));
|
||||
$model = $this->resolveUser($data, $hasSoftDeletes);
|
||||
|
||||
$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'];
|
||||
}
|
||||
|
||||
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()) {
|
||||
if ($hasSoftDeletes && $model->trashed()) {
|
||||
$event = 'restore';
|
||||
} else {
|
||||
$event = 'update';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$data = $this->convertForeignKeys($data);
|
||||
if (in_array(HasConnectWebhook::class, class_uses($class))) {
|
||||
$method = 'onConnect' . ucfirst($event);
|
||||
$model->$method($data);
|
||||
} else {
|
||||
$this->updateUserData($model, $data);
|
||||
$model->save();
|
||||
|
||||
$model::$method($data['id'], $data);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Resources getters
|
||||
|
||||
public function getAll($resourceType)
|
||||
{
|
||||
return $this->request('get', "api/resources/$resourceType");
|
||||
}
|
||||
|
||||
public function get($resourceType, $resourceId)
|
||||
{
|
||||
return $this->request('get', "api/resources/$resourceType/$resourceId");
|
||||
}
|
||||
|
||||
// Resources syncing
|
||||
|
||||
public function syncAll($resourceTypes = null)
|
||||
{
|
||||
$resourceTypes = $resourceTypes ?? $this->synchronized;
|
||||
|
||||
foreach ($resourceTypes as $resourceType)
|
||||
{
|
||||
$resourceType = $this->resolveResourceType($resourceType);
|
||||
|
||||
if (!array_key_exists($resourceType, $this->synchronized))
|
||||
throw new ConnectException("Resource $resourceType not declared as synchronized.");
|
||||
|
||||
$resources = $this->getAll($resourceType);
|
||||
$model = $this->synchronized[$resourceType];
|
||||
$identifiers = [];
|
||||
|
||||
foreach ($resources as $data)
|
||||
{
|
||||
$identifiers[] = intval($data['id']);
|
||||
$this->sync($resourceType, $data['id'], $data);
|
||||
}
|
||||
|
||||
foreach ($model::all() as $item)
|
||||
{
|
||||
if (!in_array(intval($item->{$model::$connectColumnId}), $identifiers))
|
||||
$model::onConnectResourceDoesNotExist($item);
|
||||
if (in_array(HasConnectData::class, class_uses($model))) {
|
||||
$model->postFillConnectData($data);
|
||||
}
|
||||
}
|
||||
|
||||
return $model;
|
||||
}
|
||||
|
||||
public function sync($resourceType, $resourceId, $resourceData = null)
|
||||
public function updateUserConnectData($user, $data)
|
||||
{
|
||||
$resourceType = $this->resolveResourceType($resourceType);
|
||||
if (in_array(HasConnectTokens::class, class_uses(get_class($user))))
|
||||
$user->fillConnectTokens($data);
|
||||
}
|
||||
|
||||
if (is_null($resourceData)) {
|
||||
$resourceData = $this->get($resourceType, $resourceId);
|
||||
public function updateUserData($user, $data)
|
||||
{
|
||||
if (in_array(HasConnectData::class, class_uses(get_class($user))))
|
||||
$user->fillConnectData($data);
|
||||
}
|
||||
|
||||
protected function resolveUser($data, $withTrashed = false)
|
||||
{
|
||||
$class = config('bconnect.model');
|
||||
$query = $class::query();
|
||||
|
||||
if ($withTrashed)
|
||||
$query->withTrashed();
|
||||
|
||||
$model = new $class;
|
||||
|
||||
if (in_array(HasConnectData::class, class_uses($class))) {
|
||||
$id = $model->getConnectIdentifier();
|
||||
|
||||
$origin = is_array($id) ? $id[0] : $id;
|
||||
$target = is_array($id) ? $id[1] : $id;
|
||||
|
||||
$model = $query->where($target, $data[$origin])->first() ?? $model;
|
||||
$model->$target = $data[$origin];
|
||||
} else {
|
||||
$model = $query->where('email', $data['email'])->first() ?? $model;
|
||||
|
||||
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 +294,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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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($this->path('resources/translations'), 'connect');
|
||||
|
||||
$this->loadTranslationsFrom(__DIR__.'/../resources/translations', 'connect');
|
||||
$this->loadViewsFrom($this->path('resources/views/connect'), 'connect');
|
||||
|
||||
// Views
|
||||
|
||||
$this->loadViewsFrom(__DIR__.'/../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";
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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']);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,52 @@
|
|||
<?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();
|
||||
}
|
||||
|
||||
public function postFillConnectData(array $data)
|
||||
{
|
||||
// Intended for post-processing / relationship handling
|
||||
}
|
||||
}
|
|
@ -1,43 +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;
|
||||
$record->fill($data); // TODO
|
||||
$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();
|
||||
}
|
||||
}
|
|
@ -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'];
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,45 @@
|
|||
<?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();
|
||||
|
||||
if (in_array(HasConnectData::class, class_uses(self::class))) {
|
||||
$this->postFillConnectData($data);
|
||||
}
|
||||
}
|
||||
|
||||
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…
Reference in New Issue