/** * Performs an OAuth authentication */ public function execute() { /** @var \Grav\Common\Language\Language */ $t = $this->grav['language']; $provider = strtolower($this->action); $config = $this->grav['config']->get('plugins.login.oauth.providers.' . $this->action, []); if (isset($config['credentials'])) { // Setup the credentials for the requests $credentials = new Credentials($config['credentials']['key'], $config['credentials']['secret'], $this->grav['uri']->url(true)); // Instantiate service using the credentials, http client // and storage mechanism for the token $scope = isset($this->scopes[$provider]) ? $this->scopes[$provider] : []; $this->service = $this->factory->createService($this->action, $credentials, $this->storage, $scope); } if (!$this->service || empty($config)) { $this->setMessage($t->translate(['LOGIN_PLUGIN.OAUTH_PROVIDER_NOT_SUPPORTED', $this->action])); return true; } // Check OAuth authentication status $authenticated = parent::execute(); if (is_bool($authenticated)) { $this->reset(); if ($authenticated) { $this->setMessage($t->translate('LOGIN_PLUGIN.LOGIN_SUCCESSFUL')); } else { $this->setMessage($t->translate('LOGIN_PLUGIN.ACCESS_DENIED')); } // Redirect to current URI $referrer = $this->grav['uri']->url(true); $this->setRedirect($referrer); } elseif (!$this->grav['session']->oauth) { $this->setMessage($t->translate(['LOGIN_PLUGIN.OAUTH_PROVIDER_NOT_SUPPORTED', $this->action])); } return true; }
public static function create(string $service) : AbstractProvider { // persistent storage to save the token $storage = new SessionStorage(); // Setup the credentials for the requests $credentials = new Credentials(DI::config()->get('socials/' . $service . '/key'), DI::config()->get('socials/' . $service . '/secret'), self::uri('oauth/end', ['service' => $service])->get(false)); // Oauth Service $serviceFactory = new ServiceFactory(); $serviceFactory->setHttpClient(new HttpClient()); $class = 'Cawa\\Oauth\\Providers\\' . ucfirst($service); /** @var AbstractProvider $provider */ $provider = new $class(); $provider->type = $service; // scope $scopes = DI::config()->getIfExists('socials/' . $service . '/scopes'); if (!$scopes && defined($class . '::DEFAULT_SCOPES')) { $scopes = constant($class . '::DEFAULT_SCOPES'); } if (!$scopes) { $scopes = []; } // version $version = null; if (defined($class . '::API_VERSION')) { $version = constant($class . '::API_VERSION'); } $service = $serviceFactory->createService($service, $credentials, $storage, $scopes, null, $version); $provider->service = $service; return $provider; }
/** * Constructor * * @param $url */ public function __construct($url) { $this->hlp = plugin_load('helper', 'oauth'); $credentials = new Credentials($this->hlp->getKey($this->getAdapterName()), $this->hlp->getSecret($this->getAdapterName()), $url); $this->storage = new oAuthStorage(); $serviceFactory = new ServiceFactory(); $serviceFactory->setHttpClient(new oAuthHTTPClient()); $this->oAuth = $serviceFactory->createService($this->getServiceName(), $credentials, $this->storage, $this->getScope()); }
protected function buildDefaultAuthenticator($clientID, $clientSecret, $callbackUrl) { $credentials = new Credentials($clientID, $clientSecret, $callbackUrl); $facotry = new ServiceFactory(); $session = new Session(); $service = $facotry->createService('wunderlist', $credentials, $session); $request = Request::createFromGlobals(); return new OAuthLibAuthentication($service, $request); }
/** * Get the GitHub service instance * * @access public * @return \OAuth\OAuth2\Service\GitHub */ public function getService() { $uriFactory = new UriFactory(); $currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER); $currentUri->setQuery('controller=user&action=gitHub'); $storage = new Session(false); $credentials = new Credentials(GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, $currentUri->getAbsoluteUri()); $serviceFactory = new ServiceFactory(); return $serviceFactory->createService('gitHub', $credentials, $storage, array('')); }
/** * Get the Google service instance * * @access public * @return \OAuth\OAuth2\Service\Google */ public function getService() { $uriFactory = new UriFactory(); $currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER); $currentUri->setQuery('controller=user&action=google'); $storage = new Session(false); $credentials = new Credentials(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, $currentUri->getAbsoluteUri()); $serviceFactory = new ServiceFactory(); return $serviceFactory->createService('google', $credentials, $storage, array('userinfo_email', 'userinfo_profile')); }
/** * @param $id * @return \OAuth\OAuth2\Service\AbstractService */ protected function getService($id) { $credential = $this->getCredentials($id); // Setup the credentials for the requests $credentials = new Credentials($credential['id'], $credential['secret'], $this->getRootUri() . $this->getCallbackPath($id)); $serviceFactory = new ServiceFactory(); $serviceFactory->registerService('IsseHom', '\\Paliari\\Oauth2ClientFacade\\IsseHom'); $serviceFactory->registerService('IssePro', '\\Paliari\\Oauth2ClientFacade\\IssePro'); $service = $serviceFactory->createService($id, $credentials, $this->getStorage(), $credential['scopes']); return $service; }
public function init() { if (isset($this->service)) { return; } $serviceFactory = new ServiceFactory(); // Session storage $storage = new Session(); // Setup the credentials for the requests $credentials = new Credentials($this->clientId, $this->clientSecret, Url::modify($this->redirectUrl, Url::ABS)); $this->service = $serviceFactory->createService('facebook', $credentials, $storage, $this->scopes); }
public function getContent() { $serviceFactory = new ServiceFactory(); $storage = new OauThSession(); $credentials = new Credentials(Config::get('google.key'), Config::get('google.secret'), URLSITE . 'google/auth'); $googleService = $serviceFactory->createService('google', $credentials, $storage, array('userinfo_email', 'userinfo_profile')); $state = isset($_GET['state']) ? $_GET['state'] : null; // This was a callback request from google, get the token $googleService->requestAccessToken($_GET['code'], $state); // Send a request with it return json_decode($googleService->request('userinfo'), true); }
public function init() { if (isset($this->service)) { return; } $serviceFactory = new ServiceFactory(); // Session storage $storage = new Session(false); // Setup the credentials for the requests $credentials = new Credentials($this->clientId, $this->clientSecret, Url::modify($this->redirectUrl, Url::ABS)); // Instantiate the Google service using the credentials, http client and storage mechanism for the token $this->service = $serviceFactory->createService('google', $credentials, $storage, $this->scopes); }
/** * @param Application $app * @param Request $request * @param string $service * * @return string */ public function auth(Application $app, Request $request, $service) { // Construir los servicios $serviceFactory = new ServiceFactory(); // Almacenamiento en session $storage = new Session(); // Obtener credenciales $servicesCredentials = SocialsCredentials::getArrayCredentials(); $url = $app['url_generator']->generate('auth_service', array('service' => $service), UrlGenerator::ABSOLUTE_URL); if ($service == 'facebook') { // Credenciales de facebook $facebookCredentials = new Credentials($servicesCredentials['facebook']['key'], $servicesCredentials['facebook']['secret'], $url); // Servicio de auth de facebook $serviceAuth = $serviceFactory->createService('facebook', $facebookCredentials, $storage, array()); } else { if ($service == 'google') { // Credenciales de google $googleCredentials = new Credentials($servicesCredentials['google']['key'], $servicesCredentials['google']['secret'], $url); // Servicio de auth de google $serviceAuth = $serviceFactory->createService('google', $googleCredentials, $storage, array('userinfo_email', 'userinfo_profile')); } } $menuModelo = new Menu($app['db']); $menuItems = $menuModelo->getItems(); if ($request->get('code') && $service == 'facebook') { try { // Callback de facebook para obtener el access token $serviceAuth->requestAccessToken($request->get('code')); } catch (TokenResponseException $ex) { } // Se adquiere la informacion del usuario $usuario = json_decode($serviceAuth->request('/me'), true); $usuario['service'] = 'facebook'; return $app['twig']->render('frontend/usuario/signup.html.twig', array('menu_items' => $menuItems, 'usuario' => $usuario)); } else { if ($request->get('code') && $service == 'google') { try { // Callback de google para obtener el access token $serviceAuth->requestAccessToken($request->get('code')); } catch (TokenResponseException $ex) { } // Se adquiere la informacion del usuario $usuario = json_decode($serviceAuth->request('https://www.googleapis.com/oauth2/v1/userinfo'), true); $usuario['service'] = 'google'; return $app['twig']->render('frontend/usuario/signup.html.twig', array('menu_items' => $menuItems, 'usuario' => $usuario)); } else { return "<script> location.href = '{$serviceAuth->getAuthorizationUri()}'; </script>"; } } }
/** * Return an instance of the requested service. * * @param string $provider * @param string $url * @param array $scope * * @return \OAuth\Common\Service\AbstractService * @throws \Exception */ public function service($provider, $url = null, $scope = null) { $info = Config::get('laravel-social::providers.' . strtolower($provider)); if (empty($info) || !is_array($info)) { throw new Exception('Missing configuration details for Social service: ' . $provider); } $client_id = array_get($info, 'client_id'); $client_secret = array_get($info, 'client_secret'); $scope = is_null($scope) ? array_get($info, 'scope') : $scope; if (empty($client_id) || empty($client_secret)) { throw new Exception('Missing client id/secret for Social service: ' . $provider); } return $this->factory->createService(ucfirst($provider), new Credentials($client_id, $client_secret, $url ?: URL::current()), $this->storage, $scope); }
function it_allows_for_dynamic_calls_to_providers_methods_with_the_given_decorator(Repository $config, ServiceFactory $serviceFactory) { $serviceFactory->createService('Foo', Argument::type(self::INTERFACE_CREDENTIALS), Argument::type(self::INTERFACE_STORAGE))->shouldBeCalledTimes(1)->willReturn(new Foo()); $config->has('oauth.providers.Foo')->willReturn(true); $config->has('oauth.providers.Foo.class')->willReturn(false); $config->has('oauth.providers.Foo.decorators')->willReturn(true); $config->get('oauth.providers.Foo.decorators')->willReturn(['tests\\Pasadinhas\\LaravelOAuth\\Decorator1', 'tests\\Pasadinhas\\LaravelOAuth\\Decorator2']); $config->get('oauth.providers.Foo.consumer_key')->willReturn('foo'); $config->get('oauth.providers.Foo.consumer_secret')->willReturn('bar'); $config->get('oauth.providers.Foo.callback_url')->willReturn('http://baz.com/login'); $foo = $this->make('Foo'); $foo->testDynamicMethods1()->shouldReturn('1'); $foo->testDynamicMethods2()->shouldReturn('2'); }
public function register() { $this->app->bind('oauth/factory/service', function ($app, $params = array()) { $factory = new ServiceFactory(); $factory->setHttpClient($client = new CurlClient()); $client->setCurlParameters((array) $params); return $factory; }); $this->app->bindShared('oauth/factory/extractor', function () { return new ExtractorFactory(); }); $this->app->bind('oauth_extractor', function ($app, $params = array()) { if (!is_array($params)) { $params = array($params); } if (!($service = head($params))) { throw new \InvalidArgumentException('No Service given.'); } $extractor_factory = $app->make('oauth/factory/extractor'); return $extractor_factory->get($service); }); \Route::register('/ccm/system/authentication/oauth2/{type}/{action}', function ($type, $action) { try { $type = \AuthenticationType::getByHandle($type); if ($type && is_object($type) && !$type->isError()) { /** @var GenericOauthTypeController $controller */ $controller = $type->getController(); if ($controller instanceof GenericOauthTypeController) { switch ($action) { case 'attempt_auth': return $controller->handle_authentication_attempt(); break; case 'callback': return $controller->handle_authentication_callback(); break; case 'attempt_attach': return $controller->handle_attach_attempt(); break; case 'attach_callback': return $controller->handle_attach_callback(); break; } } } } catch (\Exception $e) { \Log::addNotice('OAUTH ERROR: ' . $e->getMessage()); } }); }
/** * Get the Flickr service. * @return AbstractService */ public function getService() { // if ( $this->flickrService instanceof ServiceInterface ) { // return $this->flickrService; // } $credentials = new Credentials($this->apiKey, $this->apiSecret, 'oob'); $storage = new Memory(); $accessToken = $this->getStoredCredentials(); if ($accessToken instanceof TokenInterface) { $storage->storeAccessToken('Flickr', $accessToken); } $serviceFactory = new ServiceFactory(); $this->flickrService = $serviceFactory->createService('Flickr', $credentials, $storage); return $this->flickrService; }
/** * @param $resourceOwnerName * @return \OAuth\Common\Service\ServiceInterface * @throws Exception */ public function createService($resourceOwnerName) { if (!isset(ResourceOwners::$all[$resourceOwnerName])) { throw new Exception('Resource owner ' . $resourceOwnerName . ' is not available'); } if (isset($this->serviceCache[$resourceOwnerName])) { return $this->serviceCache[$resourceOwnerName]; } $lowerResourceOwnerName = $string = strtolower(preg_replace('/(?<=\\w)(?=[A-Z])/', "_\$1", $resourceOwnerName)); $paramName = 'apinnecke_oauth.resource_owners.' . $lowerResourceOwnerName . '.callback_url'; if (!$this->container->hasParameter($paramName) || !($callbackUrl = $this->container->getParameter($paramName)) || null === $callbackUrl) { $callbackUrl = $this->container->get('router')->getContext()->getBaseUrl(); } $credentials = new Credentials($this->container->getParameter('apinnecke_oauth.resource_owners.' . $lowerResourceOwnerName . '.client_id'), $this->container->getParameter('apinnecke_oauth.resource_owners.' . $lowerResourceOwnerName . '.client_secret'), $callbackUrl); return $this->serviceCache[$resourceOwnerName] = $this->factory->createService($resourceOwnerName, $credentials, $this->storage); }
protected function init($callbackUrl = null) { if (!$this->init) { if (!$this->storage) { $this->storage = new Session(); } $uriFactory = new UriFactory(); $this->currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER); $credentials = new Credentials($this->apiKey, $this->apiSecret, $callbackUrl ? $callbackUrl : $this->currentUri->getAbsoluteUri()); $serviceFactory = new ServiceFactory(); $serviceFactory->setHttpClient(new CurlClient()); $serviceFactory->registerService('DoYouBuzz', 'DoYouBuzz\\ApiHelper\\DoYouBuzzService'); $this->service = $serviceFactory->createService('DoYouBuzz', $credentials, $this->storage); $this->init = true; } }
/** * Set the HTTP client. * * @param string $client */ public function setHttpClient($client) { if (!in_array($client, ['StreamClient', 'CurlClient'])) { throw new \InvalidArgumentException('Invalid HTTP client'); } $class = '\\OAuth\\Common\\Http\\Client\\' . $client; $this->factory->setHttpClient(new $class()); }
/** * Check the authentication. Will be called two times : first to request a token, and redirect * to the Twitter api url, then to authenticate the user. * * @param [type] $request [description] * @param array $options [description] * @return [type] [description] */ public function check($request, array $options = array()) { $here = new Uri($request->to('url')); $here->setQuery(''); $credentials = new Credentials($this->_config['key'], $this->_config['secret'], $here->getAbsoluteUri()); $serviceFactory = new ServiceFactory(); $service = $serviceFactory->createService(static::NAME, $credentials, $this->_storage, $this->_config['scope']); if (empty($request->query['code'])) { $url = $service->getAuthorizationUri(); header('Location: ' . $url); exit(0); } else { $service->requestAccessToken($request->query['code']); $result = json_decode($service->request(static::USER_INFO), true); return $result; } }
/** * Check the authentication. Will be called two times : first to request a token, and redirect * to the Twitter api url, then to authenticate the user. * * @param [type] $request [description] * @param array $options [description] * @return [type] [description] */ public function check($request, array $options = array()) { $credentials = new Credentials($this->_config['key'], $this->_config['secret'], $request->to('url')); $serviceFactory = new ServiceFactory(); $service = $serviceFactory->createService('twitter', $credentials, $this->_storage); if (!empty($request->query['denied'])) { return false; } elseif (empty($request->query['oauth_token'])) { $token = $service->requestRequestToken(); $url = $service->getAuthorizationUri(array('oauth_token' => $token->getRequestToken())); header('Location: ' . $url); } else { $token = $this->_storage->retrieveAccessToken('Twitter'); $service->requestAccessToken($request->query['oauth_token'], $request->query['oauth_verifier'], $token->getRequestTokenSecret()); $result = json_decode($service->request('account/verify_credentials.json'), true); return $result; } }
/** * Create a service object given a ServiceFactory object * * @param \OAuth\ServiceFactory $factory * @return \OAuth\Common\Service\ServiceInterface */ public function createService(ServiceFactory $factory) { $appId = $this->config->get('auth.community.appid'); $appSecret = $this->config->get('auth.community.secret'); // Get the callback url /** @var Url $callbackUrl */ $callbackUrl = $this->urlResolver->resolve(['/ccm/system/authentication/oauth2/community/callback/']); if ($callbackUrl->getHost() == '') { $callbackUrl = $callbackUrl->setHost($this->request->getHost()); $callbackUrl = $callbackUrl->setScheme($this->request->getScheme()); } // Create a credential object with our ID, Secret, and callback url $credentials = new Credentials($appId, $appSecret, (string) $callbackUrl); // Create a new session storage object and pass it the active session $storage = new SymfonySession($this->session, false); // Create the service using the oauth service factory return $factory->createService('community', $credentials, $storage); }
/** * Set extra providers based on the configuration settings */ protected function setExtraProviders() { $providers = Config::get('oauth::extra_providers'); if (!$providers) { return; } foreach ($providers as $name => $class) { $this->serviceFactory->registerService($name, $class); } }
/** * @param string $service * @param array $credentials * @param string $url * @param array $scope * * @return \OAuth\Common\Service\AbstractService */ protected function consumer($service, $credentials = array(), $url = null, $scope = null) { if (!empty($this->oauth)) { return $this->oauth; } $scope = array_get($credentials, "scope", []); // get storage object $storage = $this->createStorageInstance($this->storageClass); // return the service consumer object $this->oauth = $this->serviceFactory->createService($service, $this->getCredentials($credentials, $url), $storage, $scope); return $this->oauth; }
/** * Creates a Connector object for the given provider type. The $id parameter * may be null but should only be used like that when getting * * @param string $provider The provider type you want. * @param TokenStorageInterface $storage The storage for PHPoAuthLib. * @param array $options * @param string $id The ID we're connecting to. * @param null|ClientInterface $http_client The HTTP client for PHPoAuthLib. * @param null|ServiceFactory $service_factory The PHPoAuthLib service factory. * @param null|CredentialsInterface $credentials The credentials for PHPoAuthLib. * @return ConnectorInterface An instance of the requested connector type. * @throws InvalidProviderException */ public function createConnector($provider, TokenStorageInterface $storage, array $options = [], $id = null, ClientInterface $http_client = null, ServiceFactory $service_factory = null, CredentialsInterface $credentials = null) { // Only allow configured providers. if (!array_key_exists($provider, $this->config['providers'])) { throw new InvalidProviderException($provider); } // Default to CurlClient (why isn't this the default? :( ) if (is_null($http_client)) { $http_client = new CurlClient(); } // Just if we want to be lazy and not pass this as an argument. if (is_null($service_factory)) { $service_factory = new ServiceFactory(); } // Simplify config access for this provider. $config = $this->getFlatConfig($provider); // We're already getting the credentials via $this->config, we might not // want to always pass them as an argument. if (is_null($credentials)) { $credentials = new Credentials($config['consumer_key'], $config['consumer_secret'], $config['callback']); } // Let's make use of CurlClient. $service_factory->setHttpClient($http_client); // Temporary (or so I hope) hack to overcome PHPoAuthLib not being ready // for Facebook's Graph API 1.0 deprecation. // If this is Facebook, let's specify we want API v2.2 // $api_version = null; // if (strtolower($provider) == 'facebook') { // $api_version = '2.2'; // } $uri = null; if (in_array($provider, ['Facebook', 'FacebookGroup', 'FacebookPage'])) { $uri = new Uri('https://graph.facebook.com/v2.2/'); } // Finally, create the service already! $service = $service_factory->createService($config['service'], $credentials, $storage, $config['scopes'], $uri); $connector_class = '\\Borfast\\Socializr\\Connectors\\' . $provider; $connector = new $connector_class($config, $service, $options, $id); return $connector; }
/** * Create and configure OAuth service object. * * @param array $ini_data * @param object $payload * @throws ErrorException */ public function __construct($ini_data, $payload) { $payload = $this->parsePayload($payload); $this->environment = $payload->env; $this->ini_data = $ini_data; if (!isset($this->ini_data[$this->environment])) { throw new ErrorException("No configuration data found for this environment: {$this->environment}\n"); } if (isset($payload->authorization_code)) { $this->authorization_code = $payload->authorization_code; } $service_factory = new \OAuth\ServiceFactory(); $session_storage = new Session(); // Iron.io callback URL. // That will be used to pass authorization code back to the worker. $webhook_url = 'https://worker-aws-us-east-1.iron.io/2/projects/' . $this->getIniData('project_id') . '/tasks/webhook?code_name=' . $this->getIniData('worker_name') . '&oauth=' . $this->getIniData('token') . '&env=' . $this->environment; // Setup credentials for OAuth requests. $credentials = new Credentials($this->getIniData('username'), $this->getIniData('password'), $webhook_url); $api_uri = new Uri\Uri($this->getIniData('api_uri')); $this->service = $service_factory->createService('IronIoOAuthService', $credentials, $session_storage, array(), $api_uri); $this->service->setAuthorizationEndpoint($this->getIniData('oauth_auth_endpoint')); $this->service->setAccessTokenEndpoint($this->getIniData('oauth_token_endpoint')); }
/** * @param string $service * @param string $url * @param array $scope * * @return \OAuth\Common\Service\AbstractService */ public function consumer($service, $url = null, $scope = null) { // get config $this->setConfig($service); // get storage object $storage = $this->createStorageInstance($this->_storage_name); // create credentials object $credentials = new Credentials($this->_client_id, $this->_client_secret, $url ?: URL::current()); // check if scopes were provided if (is_null($scope)) { // get scope from config (default to empty array) $scope = $this->_scope; } // return the service consumer object return $this->_serviceFactory->createService($service, $credentials, $storage, $scope); }
/** * @param string $service * @param string $url * @param array $scope * @return \OAuth\Common\Service\AbstractService */ public function consumer($service, $url = null, $scope = null, $uri = null, $client_id = null, $client_secret = null) { // get config $this->loadConfig($service); // create credentials object $credentials = new Credentials($client_id ?: $this->_client_id, $client_secret ?: $this->_client_secret, $url ?: URL::current()); // check if scopes were provided if (is_null($scope)) { $scope = $this->_scope ? $this->_scope : array(); } // check if uri were provided if (is_null($uri)) { $uri = $this->_uri ? $this->_uri : array(); } $uri = new Uri($uri); // dd($uri); // return the service consumer object return $this->_serviceFactory->createService($service, $credentials, $this->_storage, $scope, $uri); }
/** * @param string $service * @param string $url * @param array $scope * @return \OAuth\Common\Service\AbstractService */ public function consumer($service, $baseUri = null, $user, $key = 'oauth_access_token', $stateKey = 'oauth_authorization_state', $url = null, $scope = null) { // get config $this->setConfig($service); // get storage object $storage = $this->createStorageInstance($this->_storage_name, $user, $key, $stateKey); // create credentials object $credentials = new Credentials($this->_client_id, $this->_client_secret, $url ?: URL::current()); // check if scopes were provided if (is_null($scope)) { // get scope from config (default to empty array) $scope = $this->_scope; } if (!is_null($baseUri)) { $baseUri = new Uri($baseUri); } // return the service consumer object return $this->_serviceFactory->createService($service, $credentials, $storage, $scope, $baseUri); }
/** * Retrieve a user by the given credentials. * * @param array $credentials * @return \Illuminate\Auth\UserInterface|null */ public function retrieveByCredentials(array $credentials) { require_once base_path() . '/vendor/lusitanian/OAuth/bootstrap.php'; $url = url('/'); if (!empty($this->auth->oauthGoogleId) and !empty($this->auth->oauthGoogleSecret)) { // Setup the credentials for the requests $credentials = new Credentials($this->auth->oauthGoogleId, $this->auth->oauthGoogleSecret, url('user/login')); // Session storage $storage = new Session(); // Instantiate the Google service using the credentials, http client and storage mechanism for the token $service = new ServiceFactory(); $google = $service->createService('google', $credentials, $storage, array('userinfo_email', 'groups_provisioning')); // Google responded with a code if (Input::has('code')) { // This was a callback request from google, get the token $google->requestAccessToken(Input::get('code')); // Send a request with it $result = json_decode($google->request(Site::config('services')->googleUrlOAuth), TRUE); // Process user if (is_string($result['id']) and is_string($result['email']) and isset($result['verified_email'])) { if ($result['verified_email']) { // First we will add each credential element to the query as a where clause. // Then we can execute the query and, if we found a user, return it in a // Eloquent User "model" that will be utilized by the Guard instances. $query = $this->createModel()->newQuery(); // We search by email and user type. A filter for type=oauth is added to avoid // getting users created by other auth methods $query->where('email', $result['email'])->where('type', 'oauth'); // If a user is not found, we need to create one automagically // Thats why even if count is 0, we return a new model instance $user = $query->count() > 0 ? $query->first() : $this->createModel(); // Determine if user is an admin $googleAdmins = explode("\n", $this->auth->oauthGoogleAdmins); $isAdmin = in_array($result['email'], $googleAdmins); // We extract the username from the email address of the user $parts = explode('@', $result['email']); // Insert/Update user info $user->username = $parts[0]; $user->password = ''; $user->salt = ''; $user->email = $result['email']; $user->type = 'oauth'; $user->active = 1; $user->admin = $isAdmin; $user->save(); // Log the user in. We need to do it manually because we don't have an username // that we can 'attempt' to log in. Auth::login($user); return $user; } } App::abort(401); // Unauthorized } else { $url = $google->getAuthorizationUri()->getAbsoluteUri(); } } App::after(function ($request, $response) use($url) { $response->headers->set('Location', $url); }); return NULL; }
/** * @covers OAuth\Common\Service\AbstractService::__construct * @covers OAuth\Common\Service\AbstractService::determineRequestUriFromPath */ public function testDetermineRequestUriFromPathWithLeadingSlashInPath() { $service = new Mock($this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), ServiceFactory::construct()->getHttpTransporter(), $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), 'https://example.com'); $uri = $service->testDetermineRequestUriFromPath('/path'); $this->assertInstanceOf('\\OAuth\\Common\\Http\\Url', $uri); $this->assertSame('https://example.com/path', (string) $uri); }