24slides/auth-connector


README

Latest Stable Version Software License Build Status Quality Score Code Coverage Total Downloads

Simplifies integration with third-party services including ready-to-use solutions like HTTP Client, Auth Guard, synchronization, encryption etc.

Getting Started

Installation

  • Define the following environment variables, obtain them from the server admin:
JWT_SECRET=

SERVICE_AUTH_ENALBED=true
SERVICE_AUTH_URL=
SERVICE_AUTH_PUBLIC=
SERVICE_AUTH_SECRET=
  • Install a dependency via Composer: composer require 24slides/auth-connector
  • Add a package provider to config/app.php:
'providers' => [
    ...
    Slides\Connector\Auth\ServiceProvider::class,

The provider must be defined after AuthServiceProvider.

  • Define auth guards at config/auth.php:
'guards' => [
    ...
    
    'authService' => [
        'driver' => 'authServiceToken',
        'provider' => 'users',
    ],
    
    'fallback' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
],

Fallback is your default authentication guard which activates when remote service is disabled

  • Replace default guard to authService:
'defaults' => [
    'guard' => 'authService',
    'passwords' => 'users',
],

If you want to enable IDE features like hints, you need to install barryvdh/laravel-ide-helper.

  • Publish config and migrations:
php artisan vendor:publish --provider Slides\Connector\Auth\ServiceProvider
  • Run the published migration: php artisan migrate

The migration adds remote_id column to your User model which is supposed to be an identificator of synced users.

  • Disable encryption for the auth cookie which identifies a user:

app/Http/Middleware/EncryptCookies:

/**
 * The names of the cookies that should not be encrypted.
 *
 * @var array
 */
protected $except = [
    'authKey'
];
  • Disable verifying CSRF token for incoming webhooks:

app/Http/Middleware/VerifyCsrfToken:

/**
 * The URIs that should be excluded from CSRF verification.
 *
 * @var array
 */
protected $except = [
    'connector/webhook/*'
];

Syncing users

To allow syncing users, implement the Slides\Connector\Auth\Sync\Syncable interface on your User model.

There is a trait helper Slides\Connector\Auth\Concerns\UserHelper which covers almost all the methods, except retrieveCountry, which requires 2-digit country code (ISO 3166-1 alpha-2). If you have custom attributes just override methods from there.

Authentication handlers

Handlers implement authentication operation and wrapped into database transactions. It's just a layer to keep logic in one place.

To generate a handler, you should use the following command:

php artisan make:auth-handlers

It'll create you a file AuthHandlers.php under the namespace App\Services\Auth.

Once file has created, you should add to the boot in the app/Services/AuthServiceProvider.php:

$this->app['authService']->loadHandlers($this->app[\App\Services\Auth\AuthHandlers::class]);

You can find an example of handlers implementations here.

Fallbacks

Connector provides the possibility to disable the remote service by setting SERVICE_AUTH_ENALBED=false. It means authentication operations like login, logout, password reset will be processed only locally.

Authentication-related logic

The following parts of your application should be replaced with the functionality provided by package.

  • Registration
  • Login
  • Password reset

Registration

  • In a case if you follow default Laravel implementation of user registration, you should replace the trait Illuminate\Foundation\Auth\RegistersUsers with Slides\Connector\Auth\Concerns\RegistersUsers at the controller App\Http\Controllers\Auth\RegistrationController.`

If you have customized registration logic, you can override trait's methods.

  • Delete the create() method since it implements by RegistersUsers trait.

Login

In a case if you follow default Laravel implementation of user registration, you should replace the trait Illuminate\Foundation\Auth\AuthenticatesUsers with Slides\Connector\Auth\Concerns\AuthenticatesUsers at the controller App\Http\Controllers\Auth\LoginController.

If you have customized login logic, you can override trait's methods.

Password reset

  • In a case if you follow default Laravel implementation of user registration, you should replace the traits on the following files:
    • App\Http\Controllers\Auth\ForgotPasswordController: replace Illuminate\Foundation\Auth\SendsPasswordResetEmails with Slides\Connector\Auth\Concerns\SendsPasswordResetEmails
    • App\Http\Controllers\Auth\ResetPasswordController: replace Illuminate\Foundation\Auth\ResetsPasswords with Slides\Connector\Auth\Concerns\ResetsPasswords

If you have customized password resetting logic, you can override trait's methods.

  • If your User model doesn't implement UserHelpers trait, define the following method there:
/**
 * Send the password reset notification.
 *
 * @param string $token
 *
 * @return void
 */
public function sendPasswordResetNotification(string $token)
{
    $this->notify(new \Slides\Connector\Auth\Notifications\ResetPasswordNotification($token));
}
  • Override the reset form route by adding to routes/web.php:
Route::get('password/reset/{token}/{email}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');

Shared cache between services

Configuration

Step 1. Configure Redis connection

Add the following to your config/database.php:

'redis' => 
    ...
    
    'authService' => [
        'host' => env('SERVICE_AUTH_REDIS_HOST', '127.0.0.1'),
        'password' => env('SERVICE_AUTH_REDIS_PASSWORD', null),
        'port' => env('SERVICE_AUTH_REDIS_PORT', 6379),
        'database' => env('SERVICE_AUTH_REDIS_CACHE_DB', 1),
    ]
],
Step 2. Add environment variables

Add the following environment variables. Ask vendor for their values.

SERVICE_AUTH_REDIS_HOST=
SERVICE_AUTH_REDIS_PASSWORD=
SERVICE_AUTH_REDIS_PORT=
SERVICE_AUTH_REDIS_CACHE_DB=1

Usage

The API behind this feature is pretty straightforward as you would work with the Laravel Cache facade.

Global key-value parameters:

AuthService::cache('the-global-param', 'the-param-value');
AuthService::cache()->set('the-global-param', 'the-param-value');

AuthService::cache('the-global-param'); // the-param-value
AuthService::cache()->get('the-param-param'); // the-global-value

Store / retrieve object parameters and values.

AuthService::cache()->set('emailing', 'sendOffers', true);
AuthService::cache()->get('emailing', 'sendOffers'); // true

Store / retrieve user-related parameters.

AuthService::userCache($user->retrieveRemoteId(), 'receiveOffers', true);
AuthService::userCache($user->retrieveRemoteId(), 'receiveOffers'); // true

// Get all user's parameters
AuthService::userCache($user->retrieveRemoteId()); // ['receiveOffers' => true]