If the user is already connected we just return and instance of provider adapter,
ELSE, try to authenticate and authorize the user with the provider.
$params is generally an array with required info in order for this provider and HybridAuth to work,
like :
hauth_return_to: URL to call back after authentication is done
openid_identifier: The OpenID identity provider identifier
google_service: can be "Users" for Google user accounts service or "Apps" for Google hosted Apps
public static authenticate ( string $providerId, array $params = null ) | ||
$providerId | string | ID of the provider |
$params | array | Params |
public function getGoogleLogin($auth = NULL) { if ($auth == 'auth') { Hybrid_Endpoint::process(); } try { $oauth = new Hybrid_Auth(app_path() . '/config/google_auth.php'); $provider = $oauth->authenticate('Google'); $profile = $provider->getUserProfile(); } catch (exception $e) { return $e->getMessage(); } if ($user = User::where('email', '=', $profile->email)->first()) { Auth::login($user, true); return Redirect::intended('/'); } return App::make('frontend\\UserController')->doSignUp(array('email' => $profile->email, 'login' => $profile->identifier, 'password' => "pass1234", 'f_name' => $profile->firstName, 'l_name' => $profile->lastName)); }
/** * @return LoginProviderEntity */ protected function createLoginProviderEntity() { $type = $this->getHybridType(); //dump($this->getCallbackUrl());die($this->getCallbackUrl()); $params = array('base_url' => $this->getCallbackUrl(), 'providers' => array($type => $this->getConfig() + array('enabled' => TRUE))); $hybridauth = new \Hybrid_Auth($params); if (isset($_REQUEST['hauth_start']) || isset($_REQUEST['hauth_done'])) { \Hybrid_Endpoint::process(); } /** @var \Hybrid_User_Profile $user */ $user = $hybridauth->authenticate($this->getHybridType(), $this->authenticationParameters)->getUserProfile(); $ret = new LoginProviderEntity($user->identifier, static::getType()); return $ret; }
public function loginWithSocial($social_provider, $action = "") { // check URL segment if ($action == "auth") { // process authentication try { Session::set('provider', $social_provider); Hybrid_Endpoint::process(); } catch (Exception $e) { // redirect back to http://URL/social/ return Redirect::route('loginWith'); } return; } try { // create a HybridAuth object $socialAuth = new Hybrid_Auth(app_path() . '/config/hybridauth.php'); // authenticate with Provider $provider = $socialAuth->authenticate($social_provider); // fetch user profile $userProfile = $provider->getUserProfile(); } catch (Exception $e) { // exception codes can be found on HybBridAuth's web site Session::flash('error_msg', $e->getMessage()); return Redirect::to('/login'); } $this->createOAuthProfile($userProfile); return Redirect::to('/'); }
public function getLoginFacebook($auth = NULL) { if ($auth == 'auth') { try { \Hybrid_Endpoint::process(); } catch (Exception $e) { return Redirect::to("home"); } return; } $config = array("base_url" => "http://laravel/public/", "providers" => array("Facebook" => array("enabled" => true, "keys" => array("id" => "488919314589569", "secret" => "2b8ab46fece7bef72c48abe0eaa664d0"), "scope" => "public_profile,email", "display" => "popup"))); $oauth = new \Hybrid_Auth($config); $provider = $oauth->authenticate("Facebook"); $profile = $provider->getUserProfile(); var_dump($profile); echo "FirstName:" . $profile->firstName . "<br>"; echo "Email:" . $profile->email; echo "<br><a href='logout'>Logout</a> "; }
/** * Login using hybrid auth. */ function hybridlogin($provider) { if (isset($_REQUEST['hauth_start']) || isset($_REQUEST['hauth_done'])) { Hybrid_Endpoint::process(); exit; } $config = array("base_url" => RewriteUtil::getBaseUrl() . "main/hybridlogin?provider=" . $provider, "providers" => array()); if (isset($this->config["facebookAppId"])) { $config["providers"]["Facebook"] = array("enabled" => true, "trustForwarded" => false, "scope" => "email", "keys" => array("id" => $this->config["facebookAppId"], "secret" => $this->config["facebookSecret"])); } $hybridauth = new Hybrid_Auth($config); try { $auth = $hybridauth->authenticate($provider); $profile = $auth->getUserProfile(); $_SESSION["email"] = $profile->email; $this->redirect(); } catch (Exception $e) { $this->showLoginForm($e->getMessage()); } }
public function login(\Hybrid_Auth $hybridAuth, $action = '') { try { switch ($action) { case 'auth': \Hybrid_Endpoint::process(); return; case 'openid-google': $hybridAuthProvider = $hybridAuth->authenticate('openid', ['openid_identifier' => 'http://www.google.com/accounts/o8/id']); $hybridAuthUserProfile = $hybridAuthProvider->getUserProfile(); $user = User::firstOrCreate(['authenticator' => 'openid', 'authenticator_credential' => $hybridAuthUserProfile->identifier]); break; case 'openid-yahoo': $hybridAuthProvider = $hybridAuth->authenticate('openid', ['openid_identifier' => 'http://my.yahoo.com']); $hybridAuthUserProfile = $hybridAuthProvider->getUserProfile(); $user = User::firstOrCreate(['authenticator' => 'openid', 'authenticator_credential' => $hybridAuthUserProfile->identifier]); break; case 'google': $hybridAuthProvider = $hybridAuth->authenticate('google'); $hybridAuthUserProfile = $hybridAuthProvider->getUserProfile(); $user = User::firstOrCreate(['authenticator' => 'openid', 'authenticator_credential' => $hybridAuthUserProfile->identifier]); break; case 'facebook': $hybridAuthProvider = $hybridAuth->authenticate('facebook'); $hybridAuthUserProfile = $hybridAuthProvider->getUserProfile(); $user = User::firstOrCreate(['authenticator' => 'facebook', 'authenticator_credential' => $hybridAuthUserProfile->identifier]); break; case 'twitter': $hybridAuthProvider = $hybridAuth->authenticate('twitter'); $hybridAuthUserProfile = $hybridAuthProvider->getUserProfile(); $user = User::firstOrCreate(['authenticator' => 'twitter', 'authenticator_credential' => $hybridAuthUserProfile->identifier]); break; default: $hybridAuthProvider = $hybridAuth->authenticate('openid', ['openid_identifier' => $action]); $hybridAuthUserProfile = $hybridAuthProvider->getUserProfile(); $user = User::firstOrCreate(['authenticator' => 'openid', 'authenticator_credential' => $hybridAuthUserProfile->identifier]); break; } \Session::put('userid', $user->id); // TODO: Return to the index page } catch (Exception $ex) { // TODO: Return error to the login form } }
/** * Prompt the User to authenticate with a social-auth provider * * @param $provider_name * @param null $profile * @return null */ public function auth($provider_name, &$profile = null) { $identifier = null; try { $provider = $this->hybrid_auth->authenticate($provider_name); $userProfile = $provider->getUserProfile(); $identifier = $userProfile->identifier; $profile = $userProfile; } catch (\Exception $e) { dd($e->getMessage()); } return $identifier; }
public function provider_login() { $setting = $this->session->data['social_login_free']; $server = isset($_SERVER['HTTPS']) ? HTTPS_SERVER : HTTP_SERVER; if (!isset($setting['base_url_index'])) { $setting['base_url_index'] = false; } if ($setting['base_url_index']) { $setting['base_url'] = $this->url->link('module/social_login_free/hybridauth', '', 'SSL'); } else { $setting['base_url'] = $server . 'catalog/model/social_login_free/hybridauth.php'; } $setting['debug_file'] = DIR_SYSTEM . "logs/social_login_free.txt"; if (isset($this->request->get['provider'])) { $this->session->data['provider'] = $this->request->get['provider']; } $profile = array(); require_once DIR_APPLICATION . "model/social_login_free/hybrid/auth.php"; try { $hybridauth = new Hybrid_Auth($setting); $provider = $hybridauth->authenticate($this->session->data['provider']); //get the user profile $profile = $provider->getUserProfile(); $this->register($this->session->data['provider'], (array) $profile); $provider->logout(); } catch (Exception $e) { switch ($e->getCode()) { case 0: $json['error'] = "Unspecified error."; break; case 1: $json['error'] = "Hybriauth configuration error."; break; case 2: $json['error'] = "Provider not properly configured."; break; case 3: $json['error'] = "Unknown or disabled provider."; break; case 4: $json['error'] = "Missing provider application credentials."; break; case 5: $json['error'] = "Authentification failed. " . "The user has canceled the authentication or the provider refused the connection."; break; case 6: $json['error'] = "User profile request failed. Most likely the user is not connected " . "to the provider and he should authenticate again."; $provider->logout(); case 7: $json['error'] = "User not connected to the provider."; $provider->logout(); case 8: $json['error'] = "Provider does not support this feature."; break; } //echo "Ooophs, we got an error: " . $e->getMessage(); $this->session->data['success'] = $json['error'] . " Ooophs, we got an error: " . $e->getMessage(); $this->response->redirect(urldecode($this->url->link('account/login', ''))); } }
function _init() { require_once "Hybrid/Auth.php"; if (isset($_GET['_login'])) { switch ($_GET['_login']) { case 'tw': break; case 'fb': break; case 'gp': break; } } $config = dirname(__FILE__) . '/config.php'; try { $hybridauth = new Hybrid_Auth($config); $twitter = $hybridauth->authenticate("Google"); $user_profile = $twitter->getUserProfile(); echo "Hi there! " . $user_profile->displayName; $twitter->setUserStatus("Hello world!"); $user_contacts = $twitter->getUserContacts(); } catch (Exception $e) { echo "Ooophs, we got an error: " . $e->getMessage(); } }
/** * Authenticate a user based on the request information. * * @param Request $request Request to get authentication information from. * @param Response $response A response object that can have headers added. * @return array|bool User array on success, false on failure. */ public function authenticate(Request $request, Response $response) { $fields = $this->_config['fields']; if (!$request->data($fields['provider'])) { return $this->getUser($request); } $provider = $this->_checkFields($request, $fields); if (!$provider) { return false; } if ($this->_config['hauth_return_to']) { $returnTo = Router::url($this->_config['hauth_return_to'], true); } else { $returnTo = Router::url(['plugin' => 'ADmad/HybridAuth', 'controller' => 'HybridAuth', 'action' => 'authenticated'], true); } $params = ['hauth_return_to' => $returnTo]; if ($provider === 'OpenID') { $params['openid_identifier'] = $request->data[$fields['openid_identifier']]; } $this->_init($request); $adapter = $this->hybridAuth->authenticate($provider, $params); if ($adapter) { return $this->_getUser($provider, $adapter); } return false; }
public function action_login() { //if user loged in redirect home if (Auth::instance()->logged_in()) { Auth::instance()->login_redirect(); } Social::include_vendor(); $user = FALSE; $config = Social::get(); if ($this->request->query('hauth_start') or $this->request->query('hauth_done')) { try { Hybrid_Endpoint::process($this->request->query()); } catch (Exception $e) { Alert::set(Alert::ERROR, $e->getMessage()); $this->redirect(Route::url('default')); } } else { $provider_name = $this->request->param('id'); try { // initialize Hybrid_Auth with a given file $hybridauth = new Hybrid_Auth($config); // try to authenticate with the selected provider if ($provider_name == 'openid') { $params = array('openid_identifier' => 'https://openid.stackexchange.com/'); } else { $params = NULL; } $adapter = $hybridauth->authenticate($provider_name, $params); if ($hybridauth->isConnectedWith($provider_name)) { //var_dump($adapter->getUserProfile()); $user_profile = $adapter->getUserProfile(); } } catch (Exception $e) { Alert::set(Alert::ERROR, __('Error: please try again!') . " " . $e->getMessage()); $this->redirect(Route::url('default')); } //try to login the user with same provider and identifier $user = Auth::instance()->social_login($provider_name, $user_profile->identifier); //we couldnt login create account if ($user == FALSE) { $email = $user_profile->emailVerified != NULL ? $user_profile->emailVerified : $user_profile->email; $name = $user_profile->firstName != NULL ? $user_profile->firstName . ' ' . $user_profile->lastName : $user_profile->displayName; //if not email provided if (!Valid::email($email, TRUE)) { Alert::set(Alert::INFO, __('We need your email address to complete')); //redirect him to select the email to register $this->redirect(Route::url('default', array('controller' => 'social', 'action' => 'register', 'id' => $provider_name)) . '?uid=' . $user_profile->identifier . '&name=' . $name); } else { //register the user in DB Model_User::create_social($email, $name, $provider_name, $user_profile->identifier); //log him in Auth::instance()->social_login($provider_name, $user_profile->identifier); } } else { Alert::set(Alert::SUCCESS, __('Welcome!')); } $this->redirect(Session::instance()->get_once('auth_redirect', Route::url('default'))); } }
public function login() { $hybridauth = new Hybrid_Auth($this->config->item('social')); $provider = ucfirst($this->uri->segment(3)); $adapter = $hybridauth->authenticate('Facebook'); $user_profile = $adapter->getUserProfile(); echo "<pre>"; print_r($user_profile); echo "</pre>"; }
public function login($network = '') { $this->network = $network; $this->setContentType("text/plain"); $this->setRedirectUrl(); $this->setPopupCallback(); $config = $this->get_hybrid_auth_config(); $hybridauth = new Hybrid_Auth($config); if ($this->network == 'facebook') { $this->auth = $hybridauth->authenticate("Facebook"); } elseif ($this->network == 'linkedin') { $this->auth = $hybridauth->authenticate("LinkedIn"); } elseif ($this->network == 'twitter') { $this->auth = $hybridauth->authenticate("Twitter"); } elseif ($this->network == 'google') { $this->auth = $hybridauth->authenticate("Google"); } else { $this->redirect('/'); } $is_user_logged_in = $this->auth->isUserConnected(); $this->user = $this->auth->getUserProfile(); $u = new User(); if ($u->checkLogin()) { $this->setProfile(); } else { if (!$this->do_login()) { if ($this->do_register()) { if ($this->do_login()) { $this->setProfile(); } } } } if ($popupCallback = $this->getPopupCallback()) { $this->setContentType('text/html'); $this->set('popupCallback', $popupCallback); } else { $this->externalRedirect($this->getRedirectUrl()); } }
private function getUser($provider) { try { $oauth = new \Hybrid_Auth(app_path('../config/hybridauth.php')); $providerAuth = $oauth->authenticate($provider); $profile = $providerAuth->getUserProfile(); $user = User::loginWithSocialNetwork($providerAuth, $profile, $oauth->getSessionData(), true); $token = $user->setHidden($user->loginHidden); return ['user' => $user]; } catch (\Exception $e) { return ['error' => $e->getMessage()]; } }
/** * @param string $provider * @param array|null $params * @return \Hybrid_Provider_Adapter */ public static function authenticate($provider, $params = null) { self::init(); $adapter = null; try { static::initializeHybridAuth(); $provider = @trim(strip_tags($provider)); $adapter = \Hybrid_Auth::authenticate($provider, $params); } catch (\Exception $e) { Logger::info($e); } return $adapter; }
/** * @param $provider * @return \Hybrid_Provider_Adapter */ public static function authenticate($provider) { self::init(); $adapter = null; try { $hybridauth = new \Hybrid_Auth(self::getConfiguration()); $provider = @trim(strip_tags($provider)); $adapter = $hybridauth->authenticate($provider); } catch (\Exception $e) { \Logger::info($e); } return $adapter; }
public function process() { $user_profile = array(); //if( !empty( $_GET["action"] ) && $_GET["action"] == 'auth' && !empty($_GET["service"]) ) { if ($provider = $this->getProperty('provider', false)) { try { $config = $this->modx->modHybridAuth->getProvidersConfig(); $hybridauth = new Hybrid_Auth($config); $adapter = $hybridauth->authenticate($provider); $user_profile = $adapter->getUserProfile(); } catch (Exception $e) { $error = "<b>got an error!</b> " . $e->getMessage(); $this->modx->log(xPDO::LOG_LEVEL_ERROR, '[modHybridAuth] ' . $error); $url = $this->modx->makeUrl($this->getProperty('failure_page'), null, null, 'full'); $this->modx->sendRedirect($url); } // Check is loggedin if ($this->modx->user->hasSessionContext($this->modx->context->key)) { $redirectTo = $this->modx->getOption('site_url'); $this->modx->sendRedirect($redirectTo); return; } // else // Try to get user by social profile $q = $this->modx->newQuery('modUser'); $q->innerJoin('modUserProfile', 'Profile'); $q->innerJoin('modHybridAuthUserProfile', 'SocialProfile'); $q->innerJoin('modHybridAuthProvider', 'Provider', "Provider.id=SocialProfile.provider"); $q->where(array("SocialProfile.identifier" => $user_profile->identifier, "Provider.name" => $provider, "modUser.active" => 1, "Profile.blocked" => 0)); $q->limit(1); //$q->prepare(); //$this->modx->log(1, $q->toSQL()); if ($user = $this->modx->getObject('modUser', $q)) { $user->addSessionContext($this->modx->context->key); $redirectTo = $this->modx->getOption('site_url'); $this->modx->sendRedirect($redirectTo); return; } // else return to redirect if ($redirect_id = $this->getProperty('redirect_id') and $redirect_url = $this->modx->makeUrl($redirect_id)) { $this->modx->sendRedirect($redirect_url); return; } } else { $response = $this->modx->runProcessor('web/endpoint', $this->getProperties(), array('processors_path' => $this->modx->modHybridAuth->getOption('processorsPath'))); return $response->getResponse(); } return ''; }
public function getFacebook($auth = null) { if ($auth = 'auth') { try { Hybri_Endpoint::process(); } catch (Exception $e) { return Redirect::to('fbauth'); } return; } $oauth = new Hybrid_Auth(app_path() . '/config/fbauth.php'); $provider = $oauth->authenticate('Facebook'); $profile = $provider->getUserProfile(); return var_dump($profile) . '<a href="logout">Logout</a>'; }
/** * Authenticates a user. * @return boolean whether authentication succeeds. */ public function authenticate($provider = NULL) { Yii::import('application.modules.hybridauth.Hybrid.Hybrid_Auth'); if (strtolower($provider) == 'openid') { if (!isset($_GET['openid-identity'])) { throw new CException(Yii::t('Hybridauth.main', "You chose OpenID but didn't provide an OpenID identifier")); } else { $params = array("openid_identifier" => $_GET['openid-identity']); } } else { $params = array(); } $hybridauth = new Hybrid_Auth($this->_getConfig()); $adapter = $hybridauth->authenticate($provider, $params); if ($adapter->isUserConnected()) { $this->userData = (array) $adapter->getUserProfile(); $this->userData['id'] = $this->userData['identifier']; // Map an email address if we aren't given one if ($this->userData['email'] == NULL) { $this->userData['email'] = $this->userData['id'] . '@' . $provider . '.com'; } // Attempt to find the user by the email address $user = Users::model()->findByAttributes(array('email' => $this->userData['email'])); $meta = false; // If we didn't find a match via email, check to see if they have logged in before by their provider id if ($user === NULL) { $meta = true; $user = UserMetadata::model()->findByAttributes(array('key' => $provider . 'Provider', 'value' => $this->userData['id'])); } // Set a default error code $this->errorCode = self::ERROR_UNKNOWN_IDENTITY; // Check to see if the email binding worked if ($user === NULL) { // If the user doesn't exist $this->errorCode = self::ERROR_USERNAME_INVALID; } else { // If the user does exist $this->id = $meta ? $user->user_id : $user->id; $this->errorCode = self::ERROR_NONE; } return !$this->errorCode; } }
public function actionLogin($service) { if (empty($service)) { throw new CHttpException(404, 'Incorrect login query'); } $serviceName = Yii::t('userProfile', $service); require_once __DIR__ . "/../../../../myphp/hybridauth/Hybrid/Auth.php"; $config = (require __DIR__ . "/../../../../myphp/hybridauth/config.php"); $config['base_url'] = Yii::app()->getBaseUrl(true) . $config['base_url']; try { $hybridauth = new Hybrid_Auth($config); $adapter = $hybridauth->authenticate($service); $user_profile = $adapter->getUserProfile(); } catch (Exception $ex) { $errorMessage = $ex->getMessage(); Yii::log($errorMessage, CLogger::LEVEL_WARNING, 'hybridAuth'); Yii::app()->user->setFlash('warning', 'Вход с учетной записью ' . $serviceName . ' не был выполнен.'); AuthCommon::renderExternalLoginCloseJS(Yii::app()->createUrl(Yii::app()->params['errorLoginPage'])); exit; } try { $user = $this->getUserByServiceProfile($user_profile, $service); } catch (Exception $ex) { $errorMessage = $ex->getMessage(); Yii::log($errorMessage, 'error', 'Login with account' . $service); Yii::app()->user->setFlash('error', $errorMessage); AuthCommon::renderExternalLoginCloseJS(Yii::app()->createUrl('')); exit; } //login user $username = $user->username; $password = $user->password_hash; $identity = new UserIdentity($username, $password); $identity->authenticate(true); if ($identity->errorCode === UserIdentity::ERROR_NONE) { Yii::app()->user->login($identity, 0); } else { echo 'Error loging in'; exit; } AuthCommon::renderExternalLoginCloseJS(Yii::app()->createUrl(Yii::app()->params['successLoginPage'])); }
public function socialAction() { $preferencesService = \Zend_Registry::get('container')->getService('system_preferences_service'); $userService = \Zend_Registry::get('container')->getService('user'); $session = \Zend_Registry::get('container')->getService('session'); $config = array('base_url' => $this->view->serverUrl($this->view->url(array('action' => 'socialendpoint'))), 'debug_mode' => false, 'providers' => array('Facebook' => array('enabled' => true, 'keys' => array('id' => $preferencesService->facebook_appid, 'secret' => $preferencesService->facebook_appsecret)))); try { $hauth = new Hybrid_Auth($config); $adapter = $hauth->authenticate($this->_getParam('provider')); $userData = $adapter->getUserProfile(); $socialAdapter = $this->_helper->service('auth.adapter.social'); $socialAdapter->setProvider($adapter->id)->setProviderUserId($userData->identifier); $result = $this->auth->authenticate($socialAdapter); if ($result->getCode() !== Zend_Auth_Result::SUCCESS) { $user = $this->_helper->service('user')->findOneBy(array('email' => $userData->email)); if (!$user) { $publicationService = \Zend_Registry::get('container')->getService('newscoop_newscoop.publication_service'); $user = $this->_helper->service('user')->createPending($userData->email, $userData->firstName, $userData->lastName, null, $publicationService->getPublication()->getId()); } $this->_helper->service('auth.adapter.social')->addIdentity($user, $adapter->id, $userData->identifier); $this->auth->authenticate($socialAdapter); } else { $user = $this->_helper->service('user')->getCurrentUser(); $token = $userService->loginUser($user, 'frontend_area'); $session->set('_security_frontend_area', serialize($token)); $OAuthtoken = $userService->loginUser($user, 'oauth_authorize'); $session->set('_security_oauth_authorize', serialize($OAuthtoken)); } setcookie('NO_CACHE', '1', null, '/', '.' . $this->extractDomain($_SERVER['HTTP_HOST'])); if ($user->isPending()) { $this->_forward('confirm', 'register', 'default', array('social' => true)); } else { $request = $this->getRequest(); if ($request->getParam('_target_path')) { $this->_helper->redirector->gotoUrl($request->getParam('_target_path')); } $this->_helper->redirector('index', 'dashboard'); } } catch (\Exception $e) { throw new \Exception($e->getMessage()); } }
/** * @param string $provider * @param string $returnTo * * @return \Hybrid_User_Profile|FALSE */ public function authenticate($provider) { try { $hybridauth = new \Hybrid_Auth($this->config); $service = $hybridauth->authenticate($provider); $socialUser = $service->getUserProfile(); } catch (\Exception $exception) { switch ($exception->getCode()) { case 0: $error = 'Unspecified error.'; break; case 1: $error = 'Hybriauth configuration error.'; break; case 2: $error = 'Provider not properly configured.'; break; case 3: $error = 'Unknown or disabled provider.'; break; case 4: $error = 'Missing provider application credentials.'; break; case 5: $error = 'User has cancelled the authentication or the provider refused the connection.'; break; case 6: $error = 'User profile request failed. Most likely the user is not connected to the provider and he should to authenticate again.'; break; case 7: $error = 'User not connected to the provider.'; break; } HttpUtility::redirect(GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . '?tx_socialauth_pi1[error]=' . $exception->getCode()); } if ($socialUser) { return $socialUser; } else { return false; } }
/** * @param string $provider * @param string $returnTo * * @return \Hybrid_User_Profile|\PxHybridAuth_Hybrid_User|FALSE */ public function authenticate($provider, $returnTo) { try { $hybridauth = new \Hybrid_Auth($this->config); $service = $hybridauth->authenticate($provider, array('hauth_return_to' => $returnTo)); $socialUser = $service->getUserProfile(); } catch (\Exception $exception) { switch ($exception->getCode()) { case 0: $error = 'Unspecified error.'; break; case 1: $error = 'Hybriauth configuration error.'; break; case 2: $error = 'Provider not properly configured.'; break; case 3: $error = 'Unknown or disabled provider.'; break; break; case 4: $error = 'Missing provider application credentials.'; break; break; case 5: $error = 'User has cancelled the authentication or the provider refused the connection.'; case 6: $error = 'User profile request failed. Most likely the user is not connected to the provider and he should to authenticate again.'; case 7: $error = 'User not connected to the provider.'; break; } } if ($socialUser) { return $socialUser; } else { return FALSE; } }
public function signin_with_hybridauth($provider) { global $config; $authConfig=ROOT."configHybrid.php"; include ROOT."./../vendor/hybridauth/hybridauth/hybridauth/Hybrid/Auth.php"; $hybridauth=new Hybrid_Auth($authConfig); $adapter=$hybridauth->authenticate($provider[0]); $user_profile=$adapter->getUserProfile(); $dbProvider=DAO::getOne("AuthProvider", array ( "name" => $provider[0] )); if ($dbProvider!=NULL) { $user=DAO::getOne("User", array ( "login" => $user_profile->displayName,"idAuthProvider" => $dbProvider->getId() )); if ($user===null) { $user=new User(); $user->setLogin($user_profile->displayName); $user->setMail($user_profile->email); $user->setGroupe(DAO::getOne("Groupe", "id=2")); $user->setAuthProvider($dbProvider); $user->setKey($user_profile->identifier); DAO::insert($user); } $_SESSION["user"]=$user; setcookie("autoConnect", $provider[0], time()+3600, "/"); if (array_key_exists("action", $_SESSION)) { Startup::runAction($_SESSION["action"], false, false); unset($_SESSION["action"]); } else { echo '<h3>Connecté à '.$dbProvider->getName().'</h3>'; echo '<h4>'.$user->getLogin().'</h4>'; echo '<div class="row"><div class="col-xs-6 col-md-3"><img style="width: 230px;height:230px;border-radius: 6px;" src="'.$user_profile->photoURL.'&s=460" alt="avatar" width="230" height="230"></div></div>'; } echo "<div id='divInfoUser'></div>"; echo Jquery::get("Indexx/getInfoUser/", "#divInfoUser"); header("Location: ".$config['siteUrl']."/Indexx"); } }
<?php $config = "config.php"; // ライブラリを読み込む require_once "Hybrid/Auth.php"; require_once "Hybrid/Endpoint.php"; try { // 初期化 $hybridauth = new Hybrid_Auth($config); // 認証処理 $twitter = $hybridauth->authenticate("Twitter"); // 認証した $twitterインスタンスからユーザー情報を取得 $user_profile = $twitter->getUserProfile(); //var_dump($user_profile); echo "ようこそ! " . $user_profile->displayName . " さん", "<br>", "ギークに嬉しいWIFIと電源が使えるレストラン検索サイトです", "<br>", '<a href="http://127.0.0.1/kadai/11/guru.php">ぐるめやん</a>'; } catch (Exception $e) { echo "正常にログイン認証できませんでした: " . $e->getMessage(); header("Location:index.php"); exit; }
public function socialAuthLink() { if (!empty($_GET['link'])) { // change the following paths if necessary $config = SYSTEM_PATH . '/hybridauth/config.php'; require_once SYSTEM_PATH . '/hybridauth/Hybrid/Auth.php'; // the selected provider $provider_name = $this->sanitize($_GET['link'], 'string'); try { // initialize Hybrid_Auth with a given file $hybridauth = new Hybrid_Auth($config); // try to authenticate with the selected provider $adapter = $hybridauth->authenticate($provider_name); $user_profile = $adapter->getUserProfile(); if (!empty($user_profile->photoURL)) { //Guardamos la foto del usuario $pf_data = array($user_profile->photoURL, $this->uid); $stmt = $this->sql->prepare('UPDATE members SET avatar = ? WHERE id = ?'); $stmt->execute($pf_data); $stmt->closeCursor(); } //prepare the sql query $social_login = $this->sql->prepare('INSERT INTO social_connect VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE provider_uid = ?'); $social_login->execute(array($this->uid, $provider_name, $user_profile->identifier, $this->uid . $provider_name, $user_profile->identifier)); $this->queries++; return true; } catch (Exception $e) { return false; } } }
$error = ""; if (isset($_GET["error"])) { $error = '<b style="color:red">' . trim(strip_tags($_GET["error"])) . '</b><br /><br />'; } // if user select a provider to login with // then inlcude hybridauth config and main class // then try to authenticate te current user // finally redirect him to his profile page if (isset($_GET["provider"]) && $_GET["provider"]) { try { // create an instance for Hybridauth with the configuration file path as parameter $hybridauth = new Hybrid_Auth($config); // set selected provider name $provider = @trim(strip_tags($_GET["provider"])); // try to authenticate the selected $provider $adapter = $hybridauth->authenticate($provider); // if okey, we will redirect to user profile page $hybridauth->redirect("profile.php?provider={$provider}"); } catch (Exception $e) { // In case we have errors 6 or 7, then we have to use Hybrid_Provider_Adapter::logout() to // let hybridauth forget all about the user so we can try to authenticate again. // Display the recived error, // to know more please refer to Exceptions handling section on the userguide switch ($e->getCode()) { case 0: $error = "Unspecified error."; break; case 1: $error = "Hybriauth configuration error."; break; case 2:
<?php // note: in your application you probably have to include these only when required. $hybridauth_config = '../hybridauth/config.php'; require_once "../hybridauth/Hybrid/Auth.php"; require_once "../db.class.php"; if (isset($_GET['provider'])) { try { // create an instance for Hybridauth with the configuration file path as parameter $hybridauth = new Hybrid_Auth($hybridauth_config); $provider = $_GET['provider']; // try to authenticate the selected $provider $adapter = $hybridauth->authenticate('google'); print_r($adapter); // grab the user profile $user_profile = $adapter->getUserProfile(); print_r($user_profile); } catch (Exception $e) { // Display the recived error switch ($e->getCode()) { case 0: $error = "Unspecified error."; break; case 1: $error = "Hybriauth configuration error."; break; case 2: $error = "Provider not properly configured."; break; case 3: $error = "Unknown or disabled provider.";
* How to load your template file ? * * You can load your smarty tpl file for eg. my_blog.tpl using * \CODOF\Plugin::tpl('my_blog') * do not include .tpl at the end * */ dispatch_get('uni_login/login/:name', function ($name) { // config and includes $config = SYSPATH . 'Ext/hybridauth/config.php'; require_once SYSPATH . "Ext/hybridauth/Hybrid/Auth.php"; try { // hybridauth EP $hybridauth = new Hybrid_Auth($config); // automatically try to login with Twitter $adapter = $hybridauth->authenticate($name); // get the user profile $user_profile = $adapter->getUserProfile(); // var_dump($user_profile); //oauth identifier $oauth_id = md5($name . $user_profile->identifier); $db = \DB::getPDO(); $qry = 'SELECT id, username, avatar FROM ' . PREFIX . 'codo_users WHERE oauth_id=:oauth_id'; $stmt = $db->prepare($qry); $stmt->execute(array(":oauth_id" => $oauth_id)); $username = CODOF\Filter::clean_username($user_profile->displayName); $profile = $stmt->fetch(); if (!empty($profile)) { if ($username != $profile['username'] || $user_profile->photoURL != $profile['avatar']) { //profile has been updated remotely $qry = 'UPDATE ' . PREFIX . 'codo_users SET username=:name,avatar=:avatar WHERE oauth_id=:id';
public function login($redirectUrl = true) { if (!e107::getPref('social_login_active', false)) { throw new Exception("Signup failed! This feature is disabled.", 100); // TODO lan } if (!$this->getProvider()) { throw new Exception("Login failed! Wrong provider.", 22); // TODO lan } if ($redirectUrl) { if (true === $redirectUrl) { $redirectUrl = SITEURL; } elseif (strpos($redirectUrl, 'http://') !== 0 && strpos($redirectUrl, 'https://') !== 0) { $redirectUrl = e107::getUrl()->create($redirectUrl); } } if (e107::getUser()->isUser()) { if ($redirectUrl) { e107::getRedirect()->redirect($redirectUrl); } return true; } $this->adapter = $this->hybridauth->authenticate($this->getProvider()); $check = e107::getUser()->setProvider($this)->loginProvider($this->userId(), false); if ($redirectUrl) { e107::getRedirect()->redirect($redirectUrl); } return $check; }