Wednesday, 10 August 2016

Add custom validation into the Laravel 5.2’s php artisan make:auth

In namespace App\Services\Auth (you will need to make a directory for this if none preexisting), use Illuminate\Auth\SessionGuard to get the parent and create class CustomSessionGuard extends SessionGuard.

Create the overriding method protected function hasValidCredentials($user, $credentials).
You can return the parent::hasValidCredentials function for normal validation against your own user database as necessary.

In App\Providers\AuthServiceProvider.php add the trait use \Illuminate\Auth\CreatesUserProviders inside the class.

Within the boot function, after registerPolicies($gate) paste the following (adapted from Stack Overflow):

\Illuminate\Support\Facades\Auth::extend('customsession', function($app, $name, array $config) {
    $provider = $this->createUserProvider($config['provider']);

    $guard = new \App\Services\Auth\CustomSessionGuard($name, $provider, $app['session.store']);      

    // When using the remember me functionality of the authentication services we
    // will need to be set the encryption instance of the guard, which allows
    // secure, encrypted cookie values to get generated for those cookies.
    if (method_exists($guard, 'setCookieJar')) {
        $guard->setCookieJar($app['cookie']);
    }
    if (method_exists($guard, 'setDispatcher')) {
        $guard->setDispatcher($app['events']);
    }
    if (method_exists($guard, 'setRequest')) {
        $guard->setRequest($app->refresh('request', $guard, 'setRequest'));
    }

    return $guard;
});

Back out of App and into \config\auth.php, under Authentication Guards, replace the driver in the 'web' guard from 'session' to 'customsession'.


On a side note, need to find a better way to format code on this site.

No comments:

 
Register your domains here!