artdarek / oauth-4-laravel

OAuth Service Provider for Laravel 4
683 stars 215 forks source link

Dynamic Key & Secret #178

Closed andreuramos closed 7 years ago

andreuramos commented 7 years ago

Is there any way to create a consumer with dynamic client key & secret? Nothing found on the docummentation nor in the code itself. Tha would be a great feature to add to this package if its not already included

Thanks!

akaramires commented 7 years ago

Here is my solution:

Default client:

$service = ServiceHelper::getService( 'facebook');
$service->setClient();

return redirect( $service->getAuthorizationUri() );

Login client:

$service = ServiceHelper::getService( 'facebook' );
$service->setLoginClient();

return redirect( $service->getAuthorizationUri() );

Facebook class:

namespace App\Helpers\Services;

class FacebookHelper extends ServiceHelper
{
    const PROVIDER = 'facebook';
}

Main class

namespace App\Helpers\Services;

class ServiceHelper
{
    const PROVIDER = null;

    private function __construct()
    {
    }

    public static function getService( $provider): ServiceHelper
    {
        if ( !isset( self::$instance ) ) {
            $consumer = ucfirst( strtolower( static::PROVIDER ) );

            $service_name = "\App\Helpers\Services\\" . $consumer . "Helper";

            /** @var self $service */
            $service = new $service_name;

            self::$instance = $service;
        }

        return self::$instance;
    }

    public function setClient(): void
    {
        $consumer = ucfirst( strtolower( static::PROVIDER ) );

        $this->client = \OAuth::consumer( $consumer, $this->getConfig( 'redirect_uri' ) );
    }

    public function setLoginClient()
    {
        $consumer = ucfirst( strtolower( static::PROVIDER ) );

        $config_key = 'oauth-5-laravel.consumers.' . $consumer;

        config()->set( $config_key . '.client_id', $this->getConfig( 'login.client_id' ) );
        config()->set( $config_key . '.client_secret', $this->getConfig( 'login.client_secret' ) );
        config()->set( $config_key . '.scope', $this->getConfig( 'login.scope' ) );
        config()->set( $config_key . '.redirect_uri', $this->getConfig( 'login.redirect_uri' ) );

        $this->setClient();
    }

    public function getAuthorizationUri()
    {
        return (string)$this->client->getAuthorizationUri();
    }

    protected function getConfig( $config = '' )
    {
        $consumer = ucfirst( strtolower( static::PROVIDER ) );

        return config( 'oauth-5-laravel.consumers.' . $consumer . ( $config ? '.' . ltrim( $config, '.' ) : '' ) );
    }
}
andreuramos commented 7 years ago

well, its a good workaroud. Thanks!