begin() публичный Метод

Start the OpenID authentication process. See steps 1-2 in the overview at the top of this file.
public begin ( string $user_url, boolean $anonymous = false ) : Auth_OpenID_AuthRequest
$user_url string Identity URL given by the user. This method performs a textual transformation of the URL to try and make sure it is normalized. For example, a user_url of example.com will be normalized to http://example.com/ normalizing and resolving any redirects the server might issue.
$anonymous boolean True if the OpenID request is to be sent to the server without any identifier information. Use this when you want to transport data but don't want to do OpenID authentication with identifiers.
Результат Auth_OpenID_AuthRequest $auth_request An object containing the discovered information will be returned, with a method for building a redirect URL to the server, as described in step 3 of the overview. This object may also be used to add extension arguments to the request, using its 'addExtensionArg' method.
Пример #1
0
 static function redir_openidserver($openid_url, $store_path, $wfFlag = 1)
 {
     global $serendipity;
     $path_extra = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'PHP-openid/';
     $path = ini_get('include_path');
     $path = $path_extra . PATH_SEPARATOR . $path;
     ini_set('include_path', $path);
     require_once "Auth/OpenID/Consumer.php";
     require_once "Auth/OpenID/FileStore.php";
     $store = new Auth_OpenID_FileStore($store_path);
     $consumer = new Auth_OpenID_Consumer($store);
     $trust_root = $serendipity['baseURL'];
     switch ($wfFlag) {
         case 1:
             $process_url = $trust_root . 'serendipity_admin.php?serendipity[openidflag]=1';
             break;
         case 3:
             $process_url = $trust_root . 'serendipity_admin.php?serendipity[openidflag]=3' . '&serendipity[adminModule]=event_display&serendipity[adminAction]=profiles';
             break;
         default:
             $process_url = $trust_root . $serendipity['indexFile'] . '?serendipity[subpage]=addopenid&serendipity[openidflag]=2';
     }
     $auth_request = $consumer->begin($openid_url);
     if (!$auth_request) {
         return FALSE;
     }
     $auth_request->addExtensionArg('sreg', 'required', 'fullname');
     $auth_request->addExtensionArg('sreg', 'required', 'email');
     $redirect_url = $auth_request->redirectURL($trust_root, $process_url);
     header('Status: 302 Found');
     header("Location: " . $redirect_url);
     exit;
 }
Пример #2
0
 /**
  * Method to authenticate an user
  *
  * @param array $RAW_data Raw data to authenticate the user
  * @param Form $form Optional: If passed, better error messages can be
  *                             produced by using
  *                             {@link Form::sessionMessage()}
  * @return bool Returns FALSE if authentication fails, otherwise the
  *              method will not return at all because the browser will be
  *              redirected to some other server.
  *
  * @todo Check if we can send the POST request for OpenID 2 directly
  *       (without rendering a form and using javascript)
  */
 public static function authenticate($RAW_data, Form $form = null)
 {
     $openid = trim($RAW_data['OpenIDURL']);
     if (strlen($openid) == 0) {
         if (!is_null($form)) {
             $form->sessionMessage(_t('OpenIDAuthenticator.ERRORCRED', 'Please enter your OpenID URL or your i-name.'), 'bad');
         }
         return false;
     }
     $trust_root = Director::absoluteBaseURL();
     $return_to_url = $trust_root . 'OpenIDAuthenticator_Controller';
     $consumer = new Auth_OpenID_Consumer(new OpenIDStorage(), new SessionWrapper());
     // No auth request means we can't begin OpenID
     $auth_request = $consumer->begin($openid);
     if (!$auth_request) {
         if (!is_null($form)) {
             $form->sessionMessage(_t('OpenIDAuthenticator.ERRORNOVALID', "That doesn't seem to be a valid OpenID " . "or i-name identifier. Please try again."), "bad");
         }
         return false;
     }
     $SQL_identity = Convert::raw2sql($auth_request->endpoint->claimed_id);
     if (!($member = DataObject::get_one("Member", "Member.IdentityURL = '{$SQL_identity}'"))) {
         if (!is_null($form)) {
             $form->sessionMessage(_t('OpenIDAuthenticator.ERRORNOTENABLED', "Either your account is not enabled for " . "OpenID/i-name authentication " . "or the entered identifier is wrong. " . "Please try again."), "bad");
         }
         return false;
     }
     if ($auth_request->shouldSendRedirect()) {
         // For OpenID 1, send a redirect.
         $redirect_url = $auth_request->redirectURL($trust_root, $return_to_url);
         if (Auth_OpenID::isFailure($redirect_url)) {
             displayError("Could not redirect to server: " . $redirect_url->message);
         } else {
             Session::save();
             header('Location: ' . $redirect_url);
             exit;
         }
     } else {
         // For OpenID 2, use a javascript form to send a POST request to the
         // server.
         $form_id = 'openid_message';
         $form_html = $auth_request->formMarkup($trust_root, $return_to_url, false, array('id' => $form_id));
         if (Auth_OpenID::isFailure($form_html)) {
             displayError("Could not redirect to server: " . $form_html->message);
         } else {
             $page_contents = array("<html><head><title>", _t('OpenIDAuthenticator.TRANSACTIONINPROGRESS', 'OpenID transaction in progress'), "</title></head>", "<body onload='document.getElementById(\"" . $form_id . "\").submit()'>", $form_html, _t('OpenIDAuthenticator.TRANSACTIONNOTE', "<p>Click &quot;Continue&quot; to login. You are only seeing " . "this because you appear to have JavaScript disabled.</p>"), "</body></html>");
             print implode("\n", $page_contents);
         }
     }
     Session::save();
     // Stop the script execution! This method should return only on error
     exit;
 }
Пример #3
0
function openid_authenticate() {
  global $openid_response;
  global $db;

  if($_REQUEST[openid_id]) {
    require_once "Auth/OpenID/Consumer.php";
    require_once "Auth/OpenID/FileStore.php";

    // create file storage area for OpenID data
    $store = new Auth_OpenID_FileStore('./oid_store');

    // create OpenID consumer
    $consumer = new Auth_OpenID_Consumer($store);

    // begin sign-in process
    // create an authentication request to the OpenID provider
    $auth = $consumer->begin($_REQUEST['openid_id']);
    if (!$auth) {
      die("ERROR: Please enter a valid OpenID.");
    }

    // redirect to OpenID provider for authentication
    $_SESSION[openid_saveurl]=$_SERVER[REQUEST_URI];
    $url = $auth->redirectURL("http://$_SERVER[HTTP_HOST]$web_path", "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
    header('Location: ' . $url);
  }
  elseif($_REQUEST[openid_identity]) {
    // include files
    require_once "Auth/OpenID/Consumer.php";
    require_once "Auth/OpenID/FileStore.php";

    // create file storage area for OpenID data
    $store = new Auth_OpenID_FileStore('./oid_store');

    // create OpenID consumer
    // read response from OpenID provider
    $consumer = new Auth_OpenID_Consumer($store);
    $openid_response = $consumer->complete("http://$_SERVER[HTTP_HOST]$_SESSION[openid_saveurl]");

    // set session variable depending on authentication result
    if ($openid_response->status == Auth_OpenID_SUCCESS) {
      $_SESSION[current_user]=get_user($_REQUEST[openid_identity]);
      session_register("current_user");
      $db->query("insert or replace into openid_user values ( '$_REQUEST[openid_identity]' )");
    } else {
      print "OpenID-Authentication failed";
      print_r($openid_response);
    }

    header("Location: http://$_SERVER[HTTP_HOST]$_SESSION[openid_saveurl]");
  }
}
 /**
  * @Route("/login", name="progrupa_3dwarehouse_auth_init")
  * @Template
  */
 public function authInitAction(Request $request)
 {
     if ($request->getMethod() == Request::METHOD_POST) {
         $openid = $request->get('sketchup_openid');
         $consumer = new \Auth_OpenID_Consumer(new \Auth_OpenID_FileStore(sys_get_temp_dir()));
         // Begin the OpenID authentication process.
         $auth_request = $consumer->begin($openid);
         // No auth request means we can't begin OpenID.
         if (!$auth_request) {
             return ['error' => "Authentication error; not a valid OpenID."];
         }
         $sreg_request = \Auth_OpenID_SRegRequest::build(['email'], []);
         if ($sreg_request) {
             $auth_request->addExtension($sreg_request);
         }
         $policy_uris = null;
         $pape_request = new \Auth_OpenID_PAPE_Request($policy_uris);
         if ($pape_request) {
             $auth_request->addExtension($pape_request);
         }
         // Redirect the user to the OpenID server for authentication.
         // Store the token for this authentication so we can verify the
         // response.
         // For OpenID 1, send a redirect.  For OpenID 2, use a Javascript
         // form to send a POST request to the server.
         if ($auth_request->shouldSendRedirect()) {
             $redirect_url = $auth_request->redirectURL(getTrustRoot(), getReturnTo());
             // If the redirect URL can't be built, display an erro message.
             if (\Auth_OpenID::isFailure($redirect_url)) {
                 return ['error' => "Could not redirect to server: " . $redirect_url->message];
             } else {
                 // Send redirect.
                 return new RedirectResponse($redirect_url);
             }
         } else {
             // Generate form markup and render it.
             $form_id = 'openid_message';
             $form_html = $auth_request->htmlMarkup(getTrustRoot(), getReturnTo(), false, array('id' => $form_id));
             // Display an error if the form markup couldn't be generated otherwise, render the HTML.
             if (\Auth_OpenID::isFailure($form_html)) {
                 return ['error' => "Could not redirect to server: " . $form_html->message];
             } else {
                 return new Response($form_html);
             }
         }
     }
     return [];
 }
 /**
  * @throws InvalidOpenIDException if an invalid OpenID was provided
  */
 public function authenticate($aOpenIdUrl, $aReturnTo, $aRealm, $aRequired = array('nickname'), $aOptional = array('fullname', 'email'))
 {
     $openID = $aOpenIdUrl;
     $OpenIDConsumer = new Auth_OpenID_Consumer($this->OpenIDStorage, $this->OpenIDSessionInterface);
     // Check whether the openID is valid
     if (trim($openID) != '') {
         $authRequest = $OpenIDConsumer->begin($openID);
     }
     // Check whether we have a valid auth_request
     if (is_null($authRequest)) {
         var_dump($openID);
         throw new InvalidOpenIDException($openID);
     }
     $simpleAuthRequest = Auth_OpenID_SRegRequest::build($aRequired, $aOptional);
     if (!is_null($simpleAuthRequest)) {
         $authRequest->addExtension($simpleAuthRequest);
     }
     // todo : determine what to do with policies
     // Redirect the user to the OpenID server for authentication.
     // Store the token for this authentication so we can verify the
     // response.
     // For OpenID 1, send a redirect.  For OpenID 2, use a Javascript
     // form to send a POST request to the server.
     if ($authRequest->shouldSendRedirect()) {
         $redirectURL = $authRequest->redirectURL($aRealm, $aReturnTo);
         // If the redirect URL can't be built, display an error
         // message.
         if (Auth_OpenID::isFailure($redirectURL)) {
             displayError("Could not redirect to server: " . $redirectURL->message);
         } else {
             // Send redirect.
             header("Location: " . $redirectURL);
         }
     } else {
         // Generate form markup and render it.
         $form_id = 'openid_message';
         $form_html = $authRequest->htmlMarkup($aRealm, $aReturnTo, false, array('id' => $form_id));
         // Display an error if the form markup couldn't be generated;
         // otherwise, render the HTML.
         if (Auth_OpenID::isFailure($form_html)) {
             displayError("Could not redirect to server: " . $form_html->message);
         } else {
             print $form_html;
         }
     }
     exit(0);
     // Make sure we do a clean exit.
 }
Пример #6
0
 public static function login(Request &$request)
 {
     Pea::begin_loose_syntax();
     require_once 'Auth/OpenID/Consumer.php';
     require_once 'Auth/OpenID/FileStore.php';
     require_once 'Auth/OpenID/SReg.php';
     require_once 'Auth/OpenID/PAPE.php';
     if ($request->in_vars('openid_url') != "" || $request->in_vars('openid_verify')) {
         Log::debug("begin openid auth: " . $request->in_vars('openid_url'));
         // OpenID Auth
         $consumer = new Auth_OpenID_Consumer(new Auth_OpenID_FileStore(work_path('openid')));
         if ($request->is_vars('openid_verify')) {
             $response = $consumer->complete($request->request_url());
             if ($response->status == Auth_OpenID_SUCCESS) {
                 return $response->getDisplayIdentifier();
             }
         } else {
             $auth_request = $consumer->begin($request->in_vars('openid_url'));
             if (!$auth_request) {
                 throw new RuntimeException('invalid openid url');
             }
             $sreg_request = Auth_OpenID_SRegRequest::build(array('nickname'), array('fullname', 'email'));
             if ($sreg_request) {
                 $auth_request->addExtension($sreg_request);
             }
             if ($auth_request->shouldSendRedirect()) {
                 $redirect_url = $auth_request->redirectURL(url(), $request->request_url(false) . '?openid_verify=true');
                 if (Auth_OpenID::isFailure($redirect_url)) {
                     throw new RuntimeException("Could not redirect to server: {$redirect_url->message}");
                 } else {
                     $request->redirect($redirect_url);
                 }
             } else {
                 $form_html = $auth_request->htmlMarkup(url(), $request->request_url(false) . '?openid_verify=true', false, array('id' => 'openid_message'));
                 if (Auth_OpenID::isFailure($form_html)) {
                     throw new RuntimeException("Could not redirect to server: {$form_html->message}");
                 } else {
                     echo $form_html;
                     exit;
                 }
             }
         }
     }
     Pea::end_loose_syntax();
     return null;
 }
Пример #7
0
function openid_try($url)
{
    $store = new Auth_OpenID_MySQLStore(theDb());
    $store->createTables();
    $consumer = new Auth_OpenID_Consumer($store);
    $auth_request = $consumer->begin($url);
    if (!$auth_request) {
        $_SESSION["auth_error"] = "Error: not a valid OpenID.";
        header("Location: ./");
    }
    $sreg_request = Auth_OpenID_SRegRequest::build(array('email'), array('nickname', 'fullname'));
    if ($sreg_request) {
        $auth_request->addExtension($sreg_request);
    }
    // Attribute Exchange (Google ignores Simple Registration)
    // See http://code.google.com/apis/accounts/docs/OpenID.html#Parameters for parameters
    $ax = new Auth_OpenID_AX_FetchRequest();
    $ax->add(Auth_OpenID_AX_AttrInfo::make('http://axschema.org/contact/email', 2, 1, 'email'));
    $ax->add(Auth_OpenID_AX_AttrInfo::make('http://axschema.org/namePerson/first', 1, 1, 'firstname'));
    $ax->add(Auth_OpenID_AX_AttrInfo::make('http://axschema.org/namePerson/last', 1, 1, 'lastname'));
    $auth_request->addExtension($ax);
    if ($auth_request->shouldSendRedirect()) {
        $redirect_url = $auth_request->redirectURL(getTrustRoot(), getReturnTo());
        // If the redirect URL can't be built, display an error
        // message.
        if (Auth_OpenID::isFailure($redirect_url)) {
            die("Could not redirect to server: " . $redirect_url->message);
        } else {
            // Send redirect.
            header("Location: " . $redirect_url);
        }
    } else {
        // Generate form markup and render it.
        $form_id = 'openid_message';
        $form_html = $auth_request->htmlMarkup(getTrustRoot(), getReturnTo(), false, array('id' => $form_id));
        // Display an error if the form markup couldn't be generated;
        // otherwise, render the HTML.
        if (Auth_OpenID::isFailure($form_html)) {
            displayError("Could not redirect to server: " . $form_html->message);
        } else {
            print $form_html;
        }
    }
}
Пример #8
0
Файл: Do.php Проект: riaf/pastit
 /**
  *  login_do action implementation.
  *
  *  @access public
  *  @return string  forward name.
  */
 public function perform()
 {
     require_once 'Auth/OpenID.php';
     require_once "Auth/OpenID/Consumer.php";
     require_once "Auth/OpenID/FileStore.php";
     require_once "Auth/OpenID/SReg.php";
     require_once "Auth/OpenID/PAPE.php";
     $store_path = $this->backend->getController()->getDirectory('tmp') . "/openid_filestore";
     $consumer = new Auth_OpenID_Consumer(new Auth_OpenID_FileStore($store_path));
     $auth_request = $consumer->begin($this->af->get('url'));
     if (!$auth_request) {
         $this->ae->add(null, "OpenID が不正です");
         return 'login';
     }
     $sreg_request = Auth_OpenID_SRegRequest::build(array('nickname'), array());
     if ($sreg_request) {
         $auth_request->addExtension($sreg_request);
     }
     if ($auth_request->shouldSendRedirect()) {
         $redirect_url = $auth_request->redirectURL($this->config->get('url'), $this->config->get('url') . "login_finish");
         // If the redirect URL can't be built, display an error
         // message.
         if (Auth_OpenID::isFailure($redirect_url)) {
             $this->ae->add(null, "Could not redirect to server: " . $redirect_url->message);
             return 'login';
         } else {
             return array('redirect', $redirect_url);
         }
     } else {
         // Generate form markup and render it.
         $form_html = $auth_request->formMarkup($this->config->get('url'), $this->config->get('url') . "login_finish", false, array('id' => 'openid_form'));
         // Display an error if the form markup couldn't be generated;
         // otherwise, render the HTML.
         if (Auth_OpenID::isFailure($form_html)) {
             $this->ae->add(null, "Could not redirect to server: " . $form_html->message);
             return 'login';
         } else {
             return array('login_do', $form_html);
         }
     }
     return 'login_do';
 }
Пример #9
0
 private function begin($openid = NULL)
 {
     $store = new Auth_OpenID_FileStore($this->store_path);
     $consumer = new Auth_OpenID_Consumer($store);
     $auth_request = $consumer->begin($openid);
     if (!$auth_request) {
         throw new Exception(__('Authentication error: not a valid OpenID.'));
     }
     $sreg_request = Auth_OpenID_SRegRequest::build(array('email'), array('nickname', 'fullname'));
     if ($sreg_request) {
         $auth_request->addExtension($sreg_request);
     }
     $pape_request = new Auth_OpenID_PAPE_Request();
     if ($pape_request) {
         $auth_request->addExtension($pape_request);
     }
     // Build the redirect URL with the return page included
     $redirect_url = URL::site('openid/finish?return_to=' . Arr::get($_REQUEST, 'return_to', ''), TRUE);
     // Redirect the user to the OpenID server for authentication.
     // Store the token for this authentication so we can verify the response.
     // For OpenID 1, send a redirect:
     if ($auth_request->shouldSendRedirect()) {
         $redirect_url = $auth_request->redirectURL(URL::base(TRUE, TRUE), $redirect_url);
         if (Auth_OpenID::isFailure($redirect_url)) {
             throw new Exception(__('Could not redirect to server:') . ' ' . $redirect_url->message);
         }
         $this->request->redirect($redirect_url);
     } else {
         // the OpenID library will return a full html document
         // Auth_OpenID::autoSubmitHTML will wrap the form in body and html tags
         // see: mobules/openid/vendor/Auth/OpenID/Consumer.php
         $form_html = $auth_request->htmlMarkup(URL::base(TRUE, TRUE), $redirect_url, false, array('id' => 'openid_message'));
         // We just want the form HTML, so strip out the form
         $form_html = preg_replace('/^.*<html.*<form/im', '<form', $form_html);
         $form_html = preg_replace('/<\\/body>.*/im', '', $form_html);
         if (Auth_OpenID::isFailure($form_html)) {
             throw new Exception(__('Could not redirect to server:') . ' ' . $form_html->message);
         }
         $this->template->content->form = $form_html;
     }
 }
Пример #10
0
 public function getConsumer()
 {
     $store_path = $_ENV["basepath"] . "/app/cache/openid_store";
     if (!file_exists($store_path) && !mkdir($store_path, true)) {
         die("Verzeichnis kann nicht erstellt werden");
     }
     $store = new Auth_OpenID_FileStore($store_path);
     $consumer = new Auth_OpenID_Consumer($store);
     $response = $consumer->complete($_ENV["baseurl"] . "/account/signin?action=login_yahoo");
     if ($response->status == "failure" and $response->endpoint . "" == "") {
         //Authentifizieren
         $auth_request = $consumer->begin("https://me.yahoo.com/");
         if (!$auth_request) {
             die("Authentication error; not a valid OpenID.");
         }
         $sreg_request = Auth_OpenID_SRegRequest::build(array('nickname'), array('fullname', 'email'));
         $auth_request->addExtension($sreg_request);
         $redirect_url = $auth_request->redirectURL($ENV["baseurl"], $_ENV["baseurl"] . "/account/signin?action=login_yahoo");
         print_r($redirect_url);
     }
     return $consumer;
 }
 public function send()
 {
     $oidIdentifier = $this->providerEndPoint;
     // Starts session (needed for YADIS)
     session_start();
     // Create file storage area for OpenID data
     $store = new Auth_OpenID_FileStore(self::OID_STORE_DIRECTORY);
     // Create OpenID consumer
     $consumer = new Auth_OpenID_Consumer($store);
     // Create an authentication request to the OpenID provider
     $auth = $consumer->begin($oidIdentifier);
     $attribute = array();
     if ($this->mode == self::MODE_REGISTRATION) {
         // Create attribute request object
         // See http://code.google.com/apis/accounts/docs/OpenID.html#Parameters for parameters
         // Usage: make($type_uri, $count=1, $required=false, $alias=null)
         $attribute[] = Auth_OpenID_AX_AttrInfo::make('http://axschema.org/contact/email', 2, 1, 'email');
         $attribute[] = Auth_OpenID_AX_AttrInfo::make('http://axschema.org/pref/language', 1, 1, 'language');
         //$attribute[] = Auth_OpenID_AX_AttrInfo::make('http://axschema.org/contact/country/home', 1, 1, 'country');
         //$attribute[] = Auth_OpenID_AX_AttrInfo::make('http://axschema.org/namePerson/first', 1, 1, 'firstname');
         //$attribute[] = Auth_OpenID_AX_AttrInfo::make('http://axschema.org/namePerson/last', 1, 1, 'lastname');
     } else {
         $attribute[] = Auth_OpenID_AX_AttrInfo::make('http://axschema.org/contact/email', 1, 1, 'email');
     }
     // Create AX fetch request
     $ax = new Auth_OpenID_AX_FetchRequest();
     // Add attributes to AX fetch request
     foreach ($attribute as $attr) {
         $ax->add($attr);
     }
     // Add AX fetch request to authentication request
     $auth->addExtension($ax);
     // Redirect to OpenID provider for authentication
     $url = $auth->redirectURL('http://' . sfConfig::get('app_site_url') . '/', $this->returnToUrl);
     header('Location: ' . $url);
 }
Пример #12
0
 /**
  * This method should handle any authentication and report back to the subject
  *
  * @access	public
  * @param   array 	$credentials Array holding the user credentials
  * @param 	array   $options     Array of extra options (return, entry_url)
  * @param	object	$response	Authentication response object
  * @return	boolean
  * @since 1.5
  */
 function onAuthenticate($credentials, $options, &$response)
 {
     $mainframe =& JFactory::getApplication();
     if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
         define('Auth_OpenID_RAND_SOURCE', null);
     } else {
         $f = @fopen('/dev/urandom', 'r');
         if ($f !== false) {
             define('Auth_OpenID_RAND_SOURCE', '/dev/urandom');
             fclose($f);
         } else {
             $f = @fopen('/dev/random', 'r');
             if ($f !== false) {
                 define('Auth_OpenID_RAND_SOURCE', '/dev/urandom');
                 fclose($f);
             } else {
                 define('Auth_OpenID_RAND_SOURCE', null);
             }
         }
     }
     jimport('openid.consumer');
     jimport('joomla.filesystem.folder');
     // Access the session data
     $session =& JFactory::getSession();
     // Create and/or start using the data store
     $store_path = JPATH_ROOT . '/tmp/_joomla_openid_store';
     if (!JFolder::exists($store_path) && !JFolder::create($store_path)) {
         $response->type = JAUTHENTICATE_STATUS_FAILURE;
         $response->error_message = "Could not create the FileStore directory '{$store_path}'. " . " Please check the effective permissions.";
         return false;
     }
     // Create store object
     $store = new Auth_OpenID_FileStore($store_path);
     // Create a consumer object
     $consumer = new Auth_OpenID_Consumer($store);
     if (!isset($_SESSION['_openid_consumer_last_token'])) {
         // Begin the OpenID authentication process.
         if (!($auth_request = $consumer->begin($credentials['username']))) {
             $response->type = JAUTHENTICATE_STATUS_FAILURE;
             $response->error_message = 'Authentication error : could not connect to the openid server';
             return false;
         }
         $sreg_request = Auth_OpenID_SRegRequest::build(array('email'), array('fullname', 'language', 'timezone'));
         if ($sreg_request) {
             $auth_request->addExtension($sreg_request);
         }
         $policy_uris = array();
         if ($this->params->get('phishing-resistant', 0)) {
             $policy_uris[] = 'http://schemas.openid.net/pape/policies/2007/06/phishing-resistant';
         }
         if ($this->params->get('multi-factor', 0)) {
             $policy_uris[] = 'http://schemas.openid.net/pape/policies/2007/06/multi-factor';
         }
         if ($this->params->get('multi-factor-physical', 0)) {
             $policy_uris[] = 'http://schemas.openid.net/pape/policies/2007/06/multi-factor-physical';
         }
         $pape_request = new Auth_OpenID_PAPE_Request($policy_uris);
         if ($pape_request) {
             $auth_request->addExtension($pape_request);
         }
         //Create the entry url
         $entry_url = isset($options['entry_url']) ? $options['entry_url'] : JURI::base();
         $entry_url = JURI::getInstance($entry_url);
         unset($options['entry_url']);
         //We don't need this anymore
         //Create the url query information
         $options['return'] = isset($options['return']) ? base64_encode($options['return']) : base64_encode(JURI::base());
         $options[JUtility::getToken()] = 1;
         $process_url = sprintf($entry_url->toString() . "?option=com_user&task=login&username=%s", $credentials['username']);
         $process_url .= '&' . JURI::buildQuery($options);
         $session->set('return_url', $process_url);
         $trust_url = $entry_url->toString(array('path', 'host', 'port', 'scheme'));
         $session->set('trust_url', $trust_url);
         // For OpenID 1, send a redirect.  For OpenID 2, use a Javascript
         // form to send a POST request to the server.
         if ($auth_request->shouldSendRedirect()) {
             $redirect_url = $auth_request->redirectURL($trust_url, $process_url);
             // If the redirect URL can't be built, display an error
             // message.
             if (Auth_OpenID::isFailure($redirect_url)) {
                 displayError("Could not redirect to server: " . $redirect_url->message);
             } else {
                 // Send redirect.
                 $mainframe->redirect($redirect_url);
                 return false;
             }
         } else {
             // Generate form markup and render it.
             $form_id = 'openid_message';
             $form_html = $auth_request->htmlMarkup($trust_url, $process_url, false, array('id' => $form_id));
             // Display an error if the form markup couldn't be generated;
             // otherwise, render the HTML.
             if (Auth_OpenID::isFailure($form_html)) {
                 //displayError("Could not redirect to server: " . $form_html->message);
             } else {
                 JResponse::setBody($form_html);
                 echo JResponse::toString($mainframe->getCfg('gzip'));
                 $mainframe->close();
                 return false;
             }
         }
     }
     $result = $consumer->complete($session->get('return_url'));
     switch ($result->status) {
         case Auth_OpenID_SUCCESS:
             $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($result);
             $sreg = $sreg_resp->contents();
             $usermode = $this->params->get('usermode', 2);
             /* in the following code, we deal with the transition from the old openid version to the new openid version
                In the old version, the username was always taken straight from the login form.  In the new version, we get a
                username back from the openid provider.  This is necessary for a number of reasons.  First, providers such as
                yahoo.com allow you to enter only the provider name in the username field (i.e. yahoo.com or flickr.com).  Taking
                this as the username would obviously cause problems because everybody who had an id from yahoo.com would have username
                yahoo.com.  Second, it is necessary because with the old way, we rely on the user entering the id the same every time.
                This is bad because if the user enters the http:// one time and not the second time, they end up as two different users.
                There are two possible settings here - the first setting, is to always use the new way, which is to get the username from
                the provider after authentication.  The second setting is to check if the username exists that we got from the provider.  If it
                doesn't, then we check if the entered username exists.  If it does, then we update the database with the username from the provider
                and continue happily along with the new username.
                We had talked about a third option, which would be to always used the old way, but that seems insecure in the case of somebody using
                a yahoo.com ID.
             */
             if ($usermode && $usermode == 1) {
                 $response->username = $result->getDisplayIdentifier();
             } else {
                 // first, check if the provider provided username exists in the database
                 $db =& JFactory::getDBO();
                 $query = 'SELECT username FROM #__users' . ' WHERE username='******' AND password=\'\'';
                 $db->setQuery($query);
                 $dbresult = $db->loadObject();
                 if ($dbresult) {
                     // if so, we set our username value to the provided value
                     $response->username = $result->getDisplayIdentifier();
                 } else {
                     // if it doesn't, we check if the username from the from exists in the database
                     $query = 'SELECT username FROM #__users' . ' WHERE username='******'username']) . ' AND password=\'\'';
                     $db->setQuery($query);
                     $dbresult = $db->loadObject();
                     if ($dbresult) {
                         // if it does, we update the database
                         $query = 'UPDATE #__users SET username='******' WHERE username='******'username']);
                         $db->setQuery($query);
                         $db->query();
                         if (!$db->query()) {
                             $response->status = JAUTHENTICATE_STATUS_FAILURE;
                             $response->error_message = $db->getErrorMsg();
                             //break out of the switch if we hit an error with our query
                             break;
                         }
                     }
                     $response->username = $result->getDisplayIdentifier();
                     // we return the username provided by the openid provider
                 }
             }
             $response->status = JAUTHENTICATE_STATUS_SUCCESS;
             $response->error_message = '';
             if (!isset($sreg['email'])) {
                 $response->email = str_replace(array('http://', 'https://'), '', $response->username);
                 $response->email = str_replace('/', '-', $response->email);
                 $response->email .= '@openid.';
             } else {
                 $response->email = $sreg['email'];
             }
             $response->fullname = isset($sreg['fullname']) ? $sreg['fullname'] : $response->username;
             $response->language = isset($sreg['language']) ? $sreg['language'] : '';
             $response->timezone = isset($sreg['timezone']) ? $sreg['timezone'] : '';
             break;
         case Auth_OpenID_CANCEL:
             $response->status = JAUTHENTICATE_STATUS_CANCEL;
             $response->error_message = 'Authentication cancelled';
             break;
         case Auth_OpenID_FAILURE:
             $response->status = JAUTHENTICATE_STATUS_FAILURE;
             $response->error_message = 'Authentication failed';
             break;
     }
 }
Пример #13
0
	Janrain AX example

	modified from http://stackoverflow.com/questions/1183788/example-usage-of-ax-in-php-openid
	originally by http://stackoverflow.com/users/52888/glen
*/
$oid_identifier = 'https://www.paypal.com/webapps/auth/server';
require_once "Auth/OpenID/Consumer.php";
require_once "Auth/OpenID/Store/FileStore.php";
require_once "Auth/OpenID/Extension/AX.php";
require_once "Auth/OpenID/Extension/PAPE.php";
session_start();
// Create file storage area for OpenID data
// The Janrain library also supports databases, memcache, etc.
$store = new Auth_OpenID_Store_FileStore('./tmp');
$consumer = new Auth_OpenID_Consumer($store);
$auth = $consumer->begin($oid_identifier);
// add PAPE extensions
// request everything, see what we get back
$pape_policy_uris = array(PAPE_AUTH_PHISHING_RESISTANT, PAPE_AUTH_MULTI_FACTOR, PAPE_AUTH_MULTI_FACTOR_PHYSICAL);
$max_auth_age = 7200;
// 2 hours
$pape_request = new Auth_OpenID_PAPE_Request($policy_uris, $max_auth_age);
if ($pape_request) {
    $auth->addExtension($pape_request);
}
// Required AX attributes to request
// PayPal will not return attributes marked as optional
$attribute[] = Auth_OpenID_Extension_AX_AttrInfo::make('http://axschema.org/namePerson/first', 1, 1);
$attribute[] = Auth_OpenID_Extension_AX_AttrInfo::make('http://axschema.org/namePerson/last', 1, 1);
$attribute[] = Auth_OpenID_Extension_AX_AttrInfo::make('http://schema.openid.net/contact/fullname', 1, 1);
$attribute[] = Auth_OpenID_Extension_AX_AttrInfo::make('http://axschema.org/contact/email', 1, 1);
Пример #14
0
 function index()
 {
     // Enable SSL?
     maintain_ssl($this->config->item("ssl_enabled"));
     // Get OpenID store object
     $store = new Auth_OpenID_FileStore($this->config->item("openid_file_store_path"));
     // Get OpenID consumer object
     $consumer = new Auth_OpenID_Consumer($store);
     if ($this->input->get('janrain_nonce')) {
         // Complete authentication process using server response
         $response = $consumer->complete(site_url('account/connect_google'));
         // Check the response status
         if ($response->status == Auth_OpenID_SUCCESS) {
             // Check if user has connect google to a3m
             if ($user = $this->account_openid_model->get_by_openid($response->getDisplayIdentifier())) {
                 // Check if user is not signed in on a3m
                 if (!$this->authentication->is_signed_in()) {
                     // Run sign in routine
                     $this->authentication->sign_in($user->account_id);
                 }
                 $user->account_id === $this->session->userdata('account_id') ? $this->session->set_flashdata('linked_error', sprintf(lang('linked_linked_with_this_account'), lang('connect_google'))) : $this->session->set_flashdata('linked_error', sprintf(lang('linked_linked_with_another_account'), lang('connect_google')));
                 redirect('account/account_linked');
             } else {
                 // Check if user is signed in on a3m
                 if (!$this->authentication->is_signed_in()) {
                     $openid_google = array();
                     if ($ax_args = Auth_OpenID_AX_FetchResponse::fromSuccessResponse($response)) {
                         $ax_args = $ax_args->data;
                         if (isset($ax_args['http://axschema.org/namePerson/friendly'][0])) {
                             $openid_google['username'] = $ax_args['http://axschema.org/namePerson/friendly'][0];
                         }
                         if (isset($ax_args['http://axschema.org/contact/email'][0])) {
                             $email = $ax_args['http://axschema.org/contact/email'][0];
                         }
                         if (isset($ax_args['http://axschema.org/namePerson'][0])) {
                             $openid_google['fullname'] = $ax_args['http://axschema.org/namePerson'][0];
                         }
                         if (isset($ax_args['http://axschema.org/birthDate'][0])) {
                             $openid_google['dateofbirth'] = $ax_args['http://axschema.org/birthDate'][0];
                         }
                         if (isset($ax_args['http://axschema.org/person/gender'][0])) {
                             $openid_google['gender'] = $ax_args['http://axschema.org/person/gender'][0];
                         }
                         if (isset($ax_args['http://axschema.org/contact/postalCode/home'][0])) {
                             $openid_google['postalcode'] = $ax_args['http://axschema.org/contact/postalCode/home'][0];
                         }
                         if (isset($ax_args['http://axschema.org/contact/country/home'][0])) {
                             $openid_google['country'] = $ax_args['http://axschema.org/contact/country/home'][0];
                         }
                         if (isset($ax_args['http://axschema.org/pref/language'][0])) {
                             $openid_google['language'] = $ax_args['http://axschema.org/pref/language'][0];
                         }
                         if (isset($ax_args['http://axschema.org/pref/timezone'][0])) {
                             $openid_google['timezone'] = $ax_args['http://axschema.org/pref/timezone'][0];
                         }
                         if (isset($ax_args['http://axschema.org/namePerson/first'][0])) {
                             $openid_google['firstname'] = $ax_args['http://axschema.org/namePerson/first'][0];
                         }
                         // google only
                         if (isset($ax_args['http://axschema.org/namePerson/last'][0])) {
                             $openid_google['lastname'] = $ax_args['http://axschema.org/namePerson/last'][0];
                         }
                         // google only
                     }
                     // Store user's google data in session
                     $this->session->set_userdata('connect_create', array(array('provider' => 'openid', 'provider_id' => $response->getDisplayIdentifier(), 'email' => isset($email) ? $email : NULL), $openid_google));
                     // Create a3m account
                     redirect('account/connect_create');
                 } else {
                     // Connect google to a3m
                     $this->account_openid_model->insert($response->getDisplayIdentifier(), $this->session->userdata('account_id'));
                     $this->session->set_flashdata('linked_info', sprintf(lang('linked_linked_with_your_account'), lang('connect_google')));
                     redirect('account/account_linked');
                 }
             }
         } else {
             $this->authentication->is_signed_in() ? redirect('account/account_linked') : redirect('account/sign_up');
         }
     }
     // Begin OpenID authentication process
     $auth_request = $consumer->begin($this->config->item("openid_google_discovery_endpoint"));
     // Create ax request (Attribute Exchange)
     $ax_request = new Auth_OpenID_AX_FetchRequest();
     $ax_request->add(Auth_OpenID_AX_AttrInfo::make('http://axschema.org/namePerson/friendly', 1, TRUE, 'username'));
     $ax_request->add(Auth_OpenID_AX_AttrInfo::make('http://axschema.org/contact/email', 1, TRUE, 'email'));
     $ax_request->add(Auth_OpenID_AX_AttrInfo::make('http://axschema.org/namePerson', 1, TRUE, 'fullname'));
     $ax_request->add(Auth_OpenID_AX_AttrInfo::make('http://axschema.org/birthDate', 1, TRUE, 'dateofbirth'));
     $ax_request->add(Auth_OpenID_AX_AttrInfo::make('http://axschema.org/person/gender', 1, TRUE, 'gender'));
     $ax_request->add(Auth_OpenID_AX_AttrInfo::make('http://axschema.org/contact/postalCode/home', 1, TRUE, 'postalcode'));
     $ax_request->add(Auth_OpenID_AX_AttrInfo::make('http://axschema.org/contact/country/home', 1, TRUE, 'country'));
     $ax_request->add(Auth_OpenID_AX_AttrInfo::make('http://axschema.org/pref/language', 1, TRUE, 'language'));
     $ax_request->add(Auth_OpenID_AX_AttrInfo::make('http://axschema.org/pref/timezone', 1, TRUE, 'timezone'));
     $ax_request->add(Auth_OpenID_AX_AttrInfo::make('http://axschema.org/namePerson/first', 1, TRUE, 'firstname'));
     // google only
     $ax_request->add(Auth_OpenID_AX_AttrInfo::make('http://axschema.org/namePerson/last', 1, TRUE, 'lastname'));
     // google only
     $auth_request->addExtension($ax_request);
     // Redirect to authorizate URL
     header("Location: " . $auth_request->redirectURL(base_url(), site_url('account/connect_google')));
 }
Пример #15
0
 /**
  * This method should handle any authentication and report back to the subject
  *
  * @access	public
  * @param   array 	$credentials Array holding the user credentials
  * @param 	array   $options     Array of extra options (return, entry_url)
  * @param	object	$response	Authentication response object
  * @return	boolean
  * @since 1.5
  */
 function onAuthenticate($credentials, $options, &$response)
 {
     $mainframe =& JFactory::getApplication();
     ###########
     $db =& JFactory::getDBO();
     $this->logme($db, 'en el plugin openid');
     ################################################
     ## modificacion para que acepte gmail y yahoo ##
     ################################################
     ## asignar valor a $provider!!!!!!
     $provider = isset($credentials['provider']) && $credentials['provider'] != null ? $credentials['provider'] : 'OpenID';
     $selectProvider = 'select p.id, p.discovery_url, p.prefix, p.suffix from #__providers p where p.name = "' . $provider . '"';
     $db->setQuery($selectProvider);
     $dbprovider = $db->loadObject();
     $beginning = substr($credentials['username'], 0, strlen($dbprovider->prefix));
     $ending = substr($credentials['username'], strlen($credentials['username']) - strlen($dbprovider->suffix));
     if ($beginning != $dbprovider->prefix) {
         $credentials['username'] = $dbprovider->prefix . $credentials['username'];
     }
     if ($ending != $dbprovider->suffix) {
         $credentials['username'] = $credentials['username'] . $dbprovider->suffix;
     }
     $discovery_url = isset($dbprovider->discovery_url) ? $dbprovider->discovery_url : $credentials['username'];
     ################################################
     if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
         define('Auth_OpenID_RAND_SOURCE', null);
     } else {
         $f = @fopen('/dev/urandom', 'r');
         if ($f !== false) {
             define('Auth_OpenID_RAND_SOURCE', '/dev/urandom');
             fclose($f);
         } else {
             $f = @fopen('/dev/random', 'r');
             if ($f !== false) {
                 define('Auth_OpenID_RAND_SOURCE', '/dev/urandom');
                 fclose($f);
             } else {
                 define('Auth_OpenID_RAND_SOURCE', null);
             }
         }
     }
     jimport('openid.consumer');
     jimport('joomla.filesystem.folder');
     // Access the session data
     $session =& JFactory::getSession();
     // Create and/or start using the data store
     $store_path = JPATH_ROOT . '/tmp/_joomla_openid_store';
     if (!JFolder::exists($store_path) && !JFolder::create($store_path)) {
         $response->type = JAUTHENTICATE_STATUS_FAILURE;
         $response->error_message = "Could not create the FileStore directory '{$store_path}'. " . " Please check the effective permissions.";
         return false;
     }
     // Create store object
     $store = new Auth_OpenID_FileStore($store_path);
     // Create a consumer object
     $consumer = new Auth_OpenID_Consumer($store);
     if (!isset($_SESSION['_openid_consumer_last_token'])) {
         $this->logme($db, 'se va a iniciar el proceso');
         // Begin the OpenID authentication process.
         if (!($auth_request = $consumer->begin($discovery_url))) {
             $this->logme($db, 'no se pudo iniciar el proceso');
             $response->type = JAUTHENTICATE_STATUS_FAILURE;
             $response->error_message = 'Authentication error : could not connect to the openid server';
             return false;
         }
         $this->logme($db, 'continuamos');
         # armamos la peticion la informacion asociada al usuario
         //            $sreg_request = Auth_OpenID_SRegRequest::build(
         //                array ('email'),
         //                array ('fullname','language','timezone')
         //            );
         //
         //            if ($sreg_request) {
         //                $auth_request->addExtension($sreg_request);
         //            }
         $policy_uris = array();
         if ($this->params->get('phishing-resistant', 0)) {
             $policy_uris[] = 'http://schemas.openid.net/pape/policies/2007/06/phishing-resistant';
         }
         if ($this->params->get('multi-factor', 0)) {
             $policy_uris[] = 'http://schemas.openid.net/pape/policies/2007/06/multi-factor';
         }
         if ($this->params->get('multi-factor-physical', 0)) {
             $policy_uris[] = 'http://schemas.openid.net/pape/policies/2007/06/multi-factor-physical';
         }
         $pape_request = new Auth_OpenID_PAPE_Request($policy_uris);
         if ($pape_request) {
             $auth_request->addExtension($pape_request);
         }
         //Create the entry url
         $entry_url = isset($options['entry_url']) ? $options['entry_url'] : JURI::base();
         $entry_url = JURI::getInstance($entry_url);
         unset($options['entry_url']);
         //We don't need this anymore
         //Create the url query information
         $options['return'] = isset($options['return']) ? base64_encode($options['return']) : base64_encode(JURI::base());
         $options[JUtility::getToken()] = 1;
         $process_url = sprintf($entry_url->toString() . "?option=com_user&task=login&provider=%s", $provider);
         $process_url = isset($credentials['username']) && $credentials['username'] != '' ? sprintf("%s&username=%s", $process_url, $credentials['username']) : $process_url;
         $process_url .= '&' . JURI::buildQuery($options);
         $this->logme($db, 'la url de retorno es: ' . $process_url);
         $session->set('return_url', $process_url);
         $trust_url = $entry_url->toString(array('path', 'host', 'port', 'scheme'));
         $session->set('trust_url', $trust_url);
         $this->logme($db, 'tomando decisiones');
         // For OpenID 1, send a redirect.  For OpenID 2, use a Javascript
         // form to send a POST request to the server.
         if ($auth_request->shouldSendRedirect()) {
             $redirect_url = $auth_request->redirectURL($trust_url, $process_url);
             // If the redirect URL can't be built, display an error
             // message.
             if (Auth_OpenID::isFailure($redirect_url)) {
                 displayError("Could not redirect to server: " . $redirect_url->message);
             } else {
                 // Send redirect.
                 $mainframe->redirect($redirect_url);
                 return false;
             }
         } else {
             // Generate form markup and render it.
             $form_id = 'openid_message';
             $form_html = $auth_request->htmlMarkup($trust_url, $process_url, false, array('id' => $form_id));
             // Display an error if the form markup couldn't be generated;
             // otherwise, render the HTML.
             if (Auth_OpenID::isFailure($form_html)) {
                 //displayError("Could not redirect to server: " . $form_html->message);
             } else {
                 JResponse::setBody($form_html);
                 echo JResponse::toString($mainframe->getCfg('gzip'));
                 $mainframe->close();
                 return false;
             }
         }
     }
     $this->logme($db, 'voy a finalizar el proceso');
     $result = $consumer->complete($session->get('return_url'));
     $this->logme($db, 'se va a iniciar la interpretacion de los resultados');
     switch ($result->status) {
         case Auth_OpenID_SUCCESS:
             $usermode = $this->params->get('usermode', 2);
             $response->status = JAUTHENTICATE_STATUS_SUCCESS;
             $response->error_message = '';
             $session->set('externalidentifier', $result->getDisplayIdentifier());
             /* in the following code, we deal with the transition from the old openid version to the new openid version
                In the old version, the username was always taken straight from the login form.  In the new version, we get a
                username back from the openid provider.  This is necessary for a number of reasons.  First, providers such as
                yahoo.com allow you to enter only the provider name in the username field (i.e. yahoo.com or flickr.com).  Taking
                this as the username would obviously cause problems because everybody who had an id from yahoo.com would have username
                yahoo.com.  Second, it is necessary because with the old way, we rely on the user entering the id the same every time.
                This is bad because if the user enters the http:// one time and not the second time, they end up as two different users.
                There are two possible settings here - the first setting, is to always use the new way, which is to get the username from
                the provider after authentication.  The second setting is to check if the username exists that we got from the provider.  If it
                doesn't, then we check if the entered username exists.  If it does, then we update the database with the username from the provider
                and continue happily along with the new username.
                We had talked about a third option, which would be to always used the old way, but that seems insecure in the case of somebody using
                a yahoo.com ID.
             */
             if ($usermode && $usermode == 1) {
                 $response->username = $result->getDisplayIdentifier();
             } else {
                 $query = 'SELECT u.username, a.block as aliasblocked, u.block as userblocked' . ' FROM #__alias a, #__providers p, #__users u' . ' WHERE a.name=' . $db->Quote($result->getDisplayIdentifier()) . ' AND a.provider_id = p.id' . ' AND u.id = a.user_id' . ' AND p.name = ' . $db->Quote($provider);
                 $db->setQuery($query);
                 $dbresult = $db->loadObject();
                 $this->logme($db, 'realizo la consulta en busca del alias');
                 if ($dbresult) {
                     // if so, we set our username value to the provided value
                     $response->username = $dbresult->username;
                     $this->logme($db, 'el alias fue encontrado :D');
                     // si el alias o el usuario se encuentran bloqueados
                     // el acceso es cancelado
                     if ($dbresult->aliasblocked || $dbresult->userblocked) {
                         $response->status = JAUTHENTICATE_STATUS_FAILURE;
                         $response->error_message = 'The identifier is Blocked';
                         return false;
                     }
                 } else {
                     // si el alias no existe
                     $this->logme($db, 'el alias no existe :(');
                     $session->set('authenticationonprogress', 'true');
                     if ($credentials['userid'] == 0) {
                         $user =& JFactory::getUser();
                         if ($user->guest) {
                             $mainframe->redirect('index.php?option=com_user&view=userstatusrequest&externalid=' . $result->getDisplayIdentifier() . '&providerid=' . $dbprovider->id);
                         } else {
                             $token = JUtility::getToken();
                             $mainframe->redirect('index.php?option=com_user&task=aliasregister&externalid=' . urlencode($result->getDisplayIdentifier()) . '&providerid=' . $dbprovider->id . '&' . $token . '=1');
                         }
                     }
                 }
             }
             break;
         case Auth_OpenID_CANCEL:
             $response->status = JAUTHENTICATE_STATUS_CANCEL;
             $response->error_message = 'Authentication cancelled';
             break;
         case Auth_OpenID_FAILURE:
             $response->status = JAUTHENTICATE_STATUS_FAILURE;
             $response->error_message = 'Authentication failed';
             break;
     }
 }
Пример #16
0
 /**
  * Register a new member
  */
 function doregisterwithopenid($data, $form)
 {
     $openid = trim($data['OpenIDURL']);
     Session::set("FormInfo.Form_RegistrationWithOpenIDForm.data", $data);
     if (strlen($openid) == 0) {
         if (!is_null($form)) {
             $form->addErrorMessage("Blurb", "Please enter your OpenID or your i-name.", "bad");
         }
         Director::redirectBack();
         return;
     }
     $trust_root = Director::absoluteBaseURL();
     $return_to_url = $trust_root . $this->Link('processopenidresponse');
     $consumer = new Auth_OpenID_Consumer(new OpenIDStorage(), new SessionWrapper());
     // No auth request means we can't begin OpenID
     $auth_request = $consumer->begin($openid);
     if (!$auth_request) {
         if (!is_null($form)) {
             $form->addErrorMessage("Blurb", "That doesn't seem to be a valid OpenID or i-name identifier. " . "Please try again.", "bad");
         }
         Director::redirectBack();
         return;
     }
     $SQL_identity = Convert::raw2sql($auth_request->endpoint->claimed_id);
     if ($member = DataObject::get_one("Member", "\"Member\".\"IdentityURL\" = '{$SQL_identity}'")) {
         if (!is_null($form)) {
             $form->addErrorMessage("Blurb", "That OpenID or i-name is already registered. Use another one.", "bad");
         }
         Director::redirectBack();
         return;
     }
     // Add the fields for which we wish to get the profile data
     $sreg_request = Auth_OpenID_SRegRequest::build(null, array('nickname', 'fullname', 'email', 'country'));
     if ($sreg_request) {
         $auth_request->addExtension($sreg_request);
     }
     if ($auth_request->shouldSendRedirect()) {
         // For OpenID 1, send a redirect.
         $redirect_url = $auth_request->redirectURL($trust_root, $return_to_url);
         if (Auth_OpenID::isFailure($redirect_url)) {
             displayError("Could not redirect to server: " . $redirect_url->message);
         } else {
             Director::redirect($redirect_url);
         }
     } else {
         // For OpenID 2, use a javascript form to send a POST request to the
         // server.
         $form_id = 'openid_message';
         $form_html = $auth_request->formMarkup($trust_root, $return_to_url, false, array('id' => $form_id));
         if (Auth_OpenID::isFailure($form_html)) {
             displayError("Could not redirect to server: " . $form_html->message);
         } else {
             $page_contents = array("<html><head><title>", "OpenID transaction in progress", "</title></head>", "<body onload='document.getElementById(\"" . $form_id . "\").submit()'>", $form_html, "<p>Click &quot;Continue&quot; to login. You are only seeing " . "this because you appear to have JavaScript disabled.</p>", "</body></html>");
             print implode("\n", $page_contents);
         }
     }
 }
Пример #17
0
 public function action_openid_try()
 {
     $template_auth = new View('page/auth/auth_login');
     $openid = @$_GET['openid_identity'];
     if (!$openid) {
         Request::instance()->redirect('/');
     }
     $store = new Auth_OpenID_FileStore($this->store_path);
     $consumer = new Auth_OpenID_Consumer($store);
     // Begin the OpenID authentication process.
     $auth_request = $consumer->begin($openid);
     if (!$auth_request) {
         throw new Exception('Authentication error: not a valid OpenID.');
     }
     $sreg_request = Auth_OpenID_SRegRequest::build(array('nickname'), array('fullname', 'email'));
     if ($sreg_request) {
         $auth_request->addExtension($sreg_request);
     }
     $policy_uris = @$_GET['policies'];
     $pape_request = new Auth_OpenID_PAPE_Request($policy_uris);
     if ($pape_request) {
         $auth_request->addExtension($pape_request);
     }
     // Redirect the user to the OpenID server for authentication.
     // Store the token for this authentication so we can verify the
     // response.
     // For OpenID 1, send a redirect.  For OpenID 2, use a Javascript
     // form to send a POST request to the server.
     if ($auth_request->shouldSendRedirect()) {
         $redirect_url = $auth_request->redirectURL(URL::site(NULL, TRUE), URL::site('auth/openid_finish', TRUE));
         // If the redirect URL can't be built, display an error
         // message.
         if (Auth_OpenID::isFailure($redirect_url)) {
             throw new Exception('Could not redirect to server: ' . $redirect_url->message);
         }
         // Send redirect.
         Request::instance()->redirect($redirect_url);
     } else {
         $form_html = $auth_request->htmlMarkup(URL::site(NULL, TRUE), URL::site('auth/openid_finish', TRUE), false, array('id' => 'openid_message'));
         die(var_dump(htmlspecialchars($form_html)));
         // Display an error if the form markup couldn't be generated;
         // otherwise, render the HTML.
         if (Auth_OpenID::isFailure($form_html)) {
             throw new Exception('Could not redirect to server: ' . $form_html->message);
         }
         $template_auth->form = $form_html;
     }
     $this->template->show_footer = FALSE;
     $this->template->content = $template_auth;
 }
Пример #18
0
function openid($credentials, $options)
{
    $mainframe =& JFactory::getApplication();
    $provider = $credentials[PROVIDER];
    $db = JFactory::getDBO();
    $selectProvider = 'select p.id, p.discovery_url, p.prefix, p.suffix, p.use_email from #__providers p where p.name = "' . $provider . '"';
    $db->setQuery($selectProvider);
    $dbprovider = $db->loadObject();
    $prefix = trim($dbprovider->prefix);
    $suffix = trim($dbprovider->suffix);
    //$discovery = trim($dbprovider->discovery_url);
    //    $discovery = ($dbprovider->discovery_url == null) ? null : trim($dbprovider->discovery_url);
    $discovery = $dbprovider->discovery_url;
    $username = trim($credentials['username']);
    $beginning = substr($username, 0, strlen($prefix));
    $ending = substr($username, strlen($username) - strlen($suffix));
    if ($beginning != $prefix) {
        $username = $prefix . $username;
    }
    if ($ending != $suffix) {
        $username = $username . $suffix;
    }
    //$discovery_url = ($discovery) ? $discovery : $credentials['username'];
    $discovery_url = $discovery ? $discovery : $username;
    $username = $discovery ? '' : $username;
    ################################################
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        define('Auth_OpenID_RAND_SOURCE', null);
    } else {
        $f = @fopen('/dev/urandom', 'r');
        if ($f !== false) {
            define('Auth_OpenID_RAND_SOURCE', '/dev/urandom');
            fclose($f);
        } else {
            $f = @fopen('/dev/random', 'r');
            if ($f !== false) {
                define('Auth_OpenID_RAND_SOURCE', '/dev/urandom');
                fclose($f);
            } else {
                define('Auth_OpenID_RAND_SOURCE', null);
            }
        }
    }
    jimport('openid.consumer');
    jimport('joomla.filesystem.folder');
    // Access the session data
    $session =& JFactory::getSession();
    $info = array();
    // Create and/or start using the data store
    $store_path = JPATH_ROOT . '/tmp/_joomla_openid_store';
    if (!JFolder::exists($store_path) && !JFolder::create($store_path)) {
        $info[STATUS] = Auth_FAILURE;
        //$response->type = JAUTHENTICATE_STATUS_FAILURE;
        //$response->error_message = "Could not create the FileStore directory '$store_path'. " . " Please check the effective permissions.";
        return false;
    }
    // Create store object
    $store = new Auth_OpenID_FileStore($store_path);
    // Create a consumer object
    $consumer = new Auth_OpenID_Consumer($store);
    if (!isset($_SESSION['_openid_consumer_last_token'])) {
        // Begin the OpenID authentication process.
        if (!($auth_request = $consumer->begin($discovery_url))) {
            $info[STATUS] = Auth_FAILURE;
            //$response->type = JAUTHENTICATE_STATUS_FAILURE;
            //$response->error_message = 'Authentication error : could not connect to the openid server';
            return $info;
        }
        // if ($auth_request->endpoint->usesExtension(Auth_OpenID_AX_NS_URI)) {
        $ax_request = new Auth_OpenID_AX_FetchRequest();
        $ax_request->add(Auth_OpenID_AX_AttrInfo::make('http://axschema.org/contact/email', 1, true));
        //         }
        $sreg_request = Auth_OpenID_SRegRequest::build(array('email'));
        if ($ax_request) {
            $auth_request->addExtension($ax_request);
            $auth_request->addExtension($sreg_request);
        }
        //        $policy_uris = array();
        //        if ($this->params->get( 'phishing-resistant', 0)) {
        //            $policy_uris[] = 'http://schemas.openid.net/pape/policies/2007/06/phishing-resistant';
        //        }
        //
        //        if ($this->params->get( 'multi-factor', 0)) {
        //            $policy_uris[] = 'http://schemas.openid.net/pape/policies/2007/06/multi-factor';
        //        }
        //
        //        if ($this->params->get( 'multi-factor-physical', 0)) {
        //            $policy_uris[] = 'http://schemas.openid.net/pape/policies/2007/06/multi-factor-physical';
        //        }
        //
        //        $pape_request = new Auth_OpenID_PAPE_Request($policy_uris);
        //        if ($pape_request) {
        //            $auth_request->addExtension($pape_request);
        //        }
        //Create the entry url
        $entry_url = isset($options['entry_url']) ? $options['entry_url'] : JURI::base();
        $entry_url = JURI::getInstance($entry_url);
        unset($options['entry_url']);
        //We don't need this anymore
        //Create the url query information
        $options['return'] = isset($options['return']) ? base64_encode($options['return']) : base64_encode(JURI::base());
        $options[JUtility::getToken()] = 1;
        $process_url = sprintf($entry_url->toString() . "?option=com_user&task=login&provider=%s", $provider);
        $process_url = isset($username) && $username ? sprintf("%s&username=%s", $process_url, urlencode($username)) : $process_url;
        $process_url .= '&' . JURI::buildQuery($options);
        $session->set('return_url', $process_url);
        $trust_url = $entry_url->toString(array('path', 'host', 'port', 'scheme'));
        $session->set('trust_url', $trust_url);
        // For OpenID 1, send a redirect.  For OpenID 2, use a Javascript
        // form to send a POST request to the server.
        if ($auth_request->shouldSendRedirect()) {
            $redirect_url = $auth_request->redirectURL($trust_url, $process_url);
            // If the redirect URL can't be built, display an error
            // message.
            if (Auth_OpenID::isFailure($redirect_url)) {
                displayError("Could not redirect to server: " . $redirect_url->message);
            } else {
                // Send redirect.
                $mainframe->redirect($redirect_url);
                return false;
            }
        } else {
            // Generate form markup and render it.
            $form_id = 'openid_message';
            $form_html = $auth_request->htmlMarkup($trust_url, $process_url, false, array('id' => $form_id));
            // Display an error if the form markup couldn't be generated;
            // otherwise, render the HTML.
            if (Auth_OpenID::isFailure($form_html)) {
                //displayError("Could not redirect to server: " . $form_html->message);
            } else {
                JResponse::setBody($form_html);
                echo JResponse::toString($mainframe->getCfg('gzip'));
                $mainframe->close();
                return false;
            }
        }
    }
    $result = $consumer->complete($session->get('return_url'));
    // estandarizo el formato de salida de los datos necesarios
    $info[EXTERNAL_ID] = $result->getDisplayIdentifier();
    switch ($result->status) {
        case Auth_OpenID_SUCCESS:
            $info[STATUS] = Auth_SUCCESS;
            $ax_resp = Auth_OpenID_AX_FetchResponse::fromSuccessResponse($result);
            if ($ax_resp) {
                $email = $ax_resp->getSingle('http://axschema.org/contact/email');
                if ($email && !is_a($email, 'Auth_OpenID_AX_Error')) {
                    $info[EMAIL] = $email;
                }
            }
            $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($result);
            if (!isset($info[EMAIL]) && $sreg_resp) {
                $sreg = $sreg_resp->contents();
                if (isset($sreg['email'])) {
                    $info[EMAIL] = $sreg['email'];
                }
            }
            $info[EMAIL] = isset($info[EMAIL]) ? $info[EMAIL] : $info[EXTERNAL_ID];
            $info[LABEL] = $dbprovider->use_email ? $info[EMAIL] : $info[EXTERNAL_ID];
            break;
        case Auth_OpenID_CANCEL:
            $info[STATUS] = Auth_CANCEL;
            break;
        case Auth_OpenID_FAILURE:
            $info[STATUS] = Auth_FAILURE;
            break;
    }
    return $info;
}
 /**
  * This initiates openid connection. This method can also used for google/yahoo
  * signin, since those support openid.
  * @param type $auth_site 
  */
 function openIdConnect($auth_site)
 {
     //required includes
     //session_start();
     require_once "Auth/OpenID/Consumer.php";
     require_once "Auth/OpenID/FileStore.php";
     require_once "Auth/OpenID/SReg.php";
     require_once "Auth/OpenID/AX.php";
     $objAltConfig = $this->getObject('altconfig', 'config');
     $this->objDbSysconfig = $this->getObject('dbsysconfig', 'sysconfig');
     $modPath = $objAltConfig->getModulePath();
     $moduleUri = $objAltConfig->getModuleURI();
     $siteRoot = $objAltConfig->getSiteRoot();
     $DEFAULT_REDIRECT_ULR = $siteRoot . '?module=security&action=openidloginresult';
     $OPENID_AUTH_PAGE = $siteRoot . '?module=security&action=openidlogin';
     $OPENID_CALLBACK_PAGE = $siteRoot . '?module=security&action=openidlogin';
     $_SESSION['AUTH'] = false;
     switch ($auth_site) {
         case "google":
             $oid_identifier = 'https://www.google.com/accounts/o8/id';
             $_SESSION['auth_site'] = "Google";
             break;
         case "yahoo":
             $oid_identifier = 'https://yahoo.com';
             $_SESSION['auth_site'] = "Yahoo!";
             break;
         case "openid":
             if (!$_POST['openIDField']) {
                 header('Location: ' . $siteRoot . '?module=security&action=error&message=no_openidconnect&msg=' . $this->objLanguage->languageText("mod_security_invalidopenid", 'security'));
             } else {
                 $oid_identifier = $_POST['openIDField'];
                 $_SESSION['openid_user'] = $oid_identifier;
                 $_SESSION['auth_site'] = "OpenID";
             }
             break;
         default:
             header('Location: ' . $siteRoot . '?module=security&action=error&message=no_openidconnect&msg=' . $this->objLanguage->languageText("mod_security_invalidorunsupportedopenidprovider", 'security'));
     }
     //Here starts the authentication process
     // Create file storage area for OpenID data
     $openidPath = $this->objConfig->getcontentBasePath() . '/openid';
     $objMkDir = $this->getObject('mkdir', 'files');
     $objMkDir->mkdirs($openidPath);
     $store = new Auth_OpenID_FileStore($openidPath);
     // Create OpenID consumer
     $consumer = new Auth_OpenID_Consumer($store);
     // Create an authentication request to the OpenID provider
     $auth = $consumer->begin($oid_identifier);
     //checks for errors
     if (!$auth) {
         header('Location: ' . $siteRoot . '?module=security&action=error&message=no_openidconnect&msg=' . $this->objLanguage->languageText("mod_security_errorconnectingtoprovider", 'security') . ': ' . $auth_provider);
     }
     //configuring atributtes to be retrieved
     $attribute[] = Auth_OpenID_AX_AttrInfo::make('http://axschema.org/contact/email', 1, 1, 'email');
     // Create AX fetch request
     $ax = new Auth_OpenID_AX_FetchRequest();
     if (!$ax) {
         header('Location: ' . $siteRoot . '?module=security&action=error&message=no_openidconnect&msg=' . $this->objLanguage->languageText("mod_security_errorconnectingtoprovider", 'security') . ': ' . $auth_provider);
     }
     foreach ($attribute as $attr) {
         $ax->add($attr);
     }
     if (!$auth) {
         header('Location: ' . $siteRoot . '?module=security&action=error&message=no_openidconnect&msg=' . $this->objLanguage->languageText("mod_security_errorconnectingtoprovider", 'security') . ': ' . $auth_provider);
     }
     try {
         // Add AX fetch request to authentication request
         $auth->addExtension($ax);
     } catch (Exception $ex) {
         header('Location: ' . $siteRoot . '?module=security&action=error&message=no_openidconnect&msg=' . $this->objLanguage->languageText("mod_security_errorconnectingtoprovider", 'security') . ': ' . $auth_provider);
     }
     // redirect to the OpenID provider's website for authentication
     $url = $auth->redirectURL($siteRoot, $OPENID_CALLBACK_PAGE);
     header('Location: ' . $url);
 }
Пример #20
0
 /**
  * Initiate an OpenID request
  *
  * @param boolean $allow_sreg Default true
  * @param string $process_url Default empty (will use $CFG->wwwroot)
  * @param array $params Array of extra parameters to append to the request
  */
 function do_request($allow_sreg = true, $process_url = '', $params = array())
 {
     global $CFG;
     // Create the consumer instance
     $store = new Auth_OpenID_FileStore($CFG->dataroot . '/openid');
     $consumer = new Auth_OpenID_Consumer($store);
     $openid_url = optional_param('openid_url', null);
     //$openid_url = "http://hotdog.ccnmtl.columbia.edu:4444/" . $openid_url . "/";
     $authreq = $consumer->begin($openid_url);
     if (!$authreq) {
         error(get_string('auth_openid_login_error', 'auth_openid'));
     } else {
         // Add any simple registration fields to the request
         if ($allow_sreg === true) {
             $sreg_added = false;
             $req = array();
             $opt = array();
             $privacy_url = null;
             // Required fields
             if (!empty($this->config->openid_sreg_required)) {
                 $req = explode(',', $this->config->openid_sreg_required);
                 $sreg_added = true;
             }
             // Optional fields
             if (!empty($this->config->openid_sreg_optional)) {
                 $opt = explode(',', $this->config->openid_sreg_optional);
                 $sreg_added = true;
             }
             // Privacy statement
             if ($sreg_added && !empty($this->config->openid_privacy_url)) {
                 $privacy_url = $this->config->openid_privacy_url;
             }
             // We call the on_openid_do_request event handler function if it
             // exists. This is called before the simple registration (sreg)
             // extension is added to allow changes to be made to the sreg
             // data fields if required
             if (function_exists('on_openid_do_request')) {
                 on_openid_do_request($authreq);
             }
             // Finally, the simple registration data is added
             if ($sreg_added && !(sizeof($req) < 1 && sizeof($opt) < 1)) {
                 $sreg_request = Auth_OpenID_SRegRequest::build($req, $opt, $privacy_url);
                 if ($sreg_request) {
                     $authreq->addExtension($sreg_request);
                 }
             }
         }
         // Prepare the remaining components for the request
         if (empty($process_url)) {
             $process_url = $CFG->wwwroot . '/login/index.php';
         }
         if (is_array($params) && !empty($params)) {
             $query = '';
             foreach ($params as $key => $val) {
                 $query .= '&' . $key . '=' . $val;
             }
             $process_url .= '?' . substr($query, 1);
         }
         $trust_root = $CFG->wwwroot . '/';
         $_SESSION['openid_process_url'] = $process_url;
         // Finally, redirect to the OpenID provider
         // If the server is blacklisted
         if (openid_server_is_blacklisted($authreq->endpoint->server_url)) {
             error(get_string('auth_openid_server_blacklisted', 'auth_openid', $authreq->endpoint->server_url));
         } elseif ($authreq->shouldSendRedirect()) {
             $redirect_url = $authreq->redirectURL($trust_root, $process_url);
             // If the redirect URL can't be built, display an error message.
             if (Auth_OpenID::isFailure($redirect_url)) {
                 error($redirect_url->message);
             } else {
                 redirect($redirect_url);
             }
         } else {
             // Generate form markup and render it.
             $form_id = 'openid_message';
             $message = $authreq->getMessage($trust_root, $process_url, false);
             // Display an error if the form markup couldn't be generated;
             // otherwise, render the HTML.
             if (Auth_OpenID::isFailure($message)) {
                 error($message);
             } else {
                 $form_html = $message->toFormMarkup($authreq->endpoint->server_url, array('id' => $form_id), get_string('continue'));
                 echo '<html><head><title>OpenID request</title></head><body onload="document.getElementById(\'', $form_id, '\').submit();" style="text-align: center;"><div style="background: lightyellow; border: 1px solid black; margin: 30px 20%; padding: 5px 15px;"><p>', get_string('openid_redirecting', 'auth_openid'), '</p></div>', $form_html, '</body></html>';
                 exit;
             }
         }
     }
 }
Пример #21
0
 /**
  * Returns URL to which user can be directed for 
  * authentication via CS50 ID.
  *
  * @param trust_root  URL that CS50 ID should prompt user to trust
  * @param return_to   URL to which CS50 ID should return user
  * @param fields      Simple Registration fields to request from CS50 ID
  * @param attributes  Attribute Exchange attributes to request from CS50 ID
  *
  * @return URL for CS50 ID
  */
 public static function getLoginUrl($trust_root, $return_to, $fields = ["email", "fullname"], $attributes = [])
 {
     // ignore Janrain's use of deprecated functions
     $error_reporting = error_reporting();
     error_reporting($error_reporting & ~E_DEPRECATED);
     // load Janrain's libary
     set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . DIRECTORY_SEPARATOR . "share" . DIRECTORY_SEPARATOR . "php-openid-2.3.0");
     require_once "Auth/OpenID/AX.php";
     require_once "Auth/OpenID/Consumer.php";
     require_once "Auth/OpenID/FileStore.php";
     require_once "Auth/OpenID/SReg.php";
     // ensure $_SESSION exists for Yadis
     @session_start();
     // prepare filesystem-based store
     $path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . md5($return_to);
     @mkdir($path, 0700);
     if (!is_dir($path)) {
         trigger_error("Could not create {$path}", E_USER_ERROR);
     }
     if (!is_readable($path)) {
         trigger_error("Could not read from {$path}", E_USER_ERROR);
     }
     if (!is_writable($path)) {
         trigger_error("Could not write to {$path}", E_USER_ERROR);
     }
     $store = new Auth_OpenID_FileStore($path);
     // prepare request
     $consumer = new Auth_OpenID_Consumer($store);
     $auth_request = $consumer->begin("https://id.cs50.net/");
     // request Simple Registration fields
     if (is_array($fields) && count($fields) > 0) {
         $sreg_request = Auth_OpenID_SRegRequest::build(null, $fields);
         $auth_request->addExtension($sreg_request);
     }
     // request Attribute Exchange attributes
     if (is_array($attributes) && count($attributes) > 0) {
         $ax_request = new Auth_OpenID_AX_FetchRequest();
         foreach ($attributes as $attribute) {
             $ax_request->add(Auth_OpenID_AX_AttrInfo::make($attribute, 1, false));
         }
         $auth_request->addExtension($ax_request);
     }
     // generate URL for redirection
     $redirect_url = $auth_request->redirectURL($trust_root, $return_to);
     // restore error_reporting
     error_reporting($error_reporting);
     // return URL unless error
     if (Auth_OpenID::isFailure($redirect_url)) {
         trigger_error($redirect_url->message);
         return false;
     } else {
         return $redirect_url;
     }
 }
Пример #22
0
 function index()
 {
     // Enable SSL?
     maintain_ssl($this->config->item("ssl_enabled"));
     // Retrieve sign in user
     if ($this->authentication->is_signed_in()) {
         $data['account'] = $this->Account_model->get_by_id($this->session->userdata('account_id'));
     }
     //$data['account_details'] = $this->account_details_model->get_by_account_id($this->session->userdata('account_id'));
     // Get OpenID store object
     $store = new Auth_OpenID_FileStore($this->config->item("openid_file_store_path"));
     // Get OpenID consumer object
     $consumer = new Auth_OpenID_Consumer($store);
     if ($this->input->get('janrain_nonce')) {
         // Complete authentication process using server response
         $response = $consumer->complete(site_url('account/connect_openid'));
         // Check the response status
         if ($response->status == Auth_OpenID_SUCCESS) {
             // Check if user has connect the openid to a3m
             if ($user = $this->Account_openid_model->get_by_openid($response->getDisplayIdentifier())) {
                 // Check if user is not signed in on a3m
                 if (!$this->authentication->is_signed_in()) {
                     // Run sign in routine
                     $this->authentication->sign_in($user->account_id);
                 }
                 $user->account_id === $this->session->userdata('account_id') ? $this->session->set_flashdata('linked_error', sprintf(lang('linked_linked_with_this_account'), lang('connect_openid'))) : $this->session->set_flashdata('linked_error', sprintf(lang('linked_linked_with_another_account'), lang('connect_openid')));
                 redirect('account/account_linked');
             } else {
                 // Check if user is signed in on a3m
                 if (!$this->authentication->is_signed_in()) {
                     $openid_all = array();
                     // Extract Simple Registration data
                     if ($sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response)) {
                         $sreg = $sreg_resp->contents();
                         if (isset($sreg['nickname'])) {
                             $username = $sreg['nickname'];
                         }
                         if (isset($sreg['email'])) {
                             $email = $sreg['email'];
                         }
                         if (isset($sreg['fullname'])) {
                             $openid_all['fullname'] = $sreg['fullname'];
                         }
                         if (isset($sreg['gender'])) {
                             $openid_all['gender'] = $sreg['gender'];
                         }
                         if (isset($sreg['dob'])) {
                             $openid_all['dateofbirth'] = $sreg['dob'];
                         }
                         if (isset($sreg['postcode'])) {
                             $openid_all['postalcode'] = $sreg['postcode'];
                         }
                         if (isset($sreg['country'])) {
                             $openid_all['country'] = $sreg['country'];
                         }
                         if (isset($sreg['language'])) {
                             $openid_all['language'] = $sreg['language'];
                         }
                         if (isset($sreg['timezone'])) {
                             $openid_all['timezone'] = $sreg['timezone'];
                         }
                     }
                     // Store user's twitter data in session
                     $this->session->set_userdata('connect_create', array(array('provider' => 'openid', 'provider_id' => $response->getDisplayIdentifier(), 'username' => isset($username) ? $username : NULL, 'email' => isset($email) ? $email : NULL), $openid_all));
                     // Create a3m account
                     redirect('account/connect_create');
                 } else {
                     // Connect openid to a3m
                     $this->Account_openid_model->insert($response->getDisplayIdentifier(), $this->session->userdata('account_id'));
                     $this->session->set_flashdata('linked_info', sprintf(lang('linked_linked_with_your_account'), lang('connect_openid')));
                     redirect('account/account_linked');
                 }
             }
         } else {
             $this->authentication->is_signed_in() ? redirect('account/account_linked') : redirect('account/sign_up');
         }
     }
     $this->load->library('form_validation');
     // Setup form validation
     $this->form_validation->set_error_delimiters('<span class="field_error">', '</span>');
     $this->form_validation->set_rules(array(array('field' => 'connect_openid_url', 'label' => 'lang:connect_openid_url', 'rules' => 'trim|required')));
     // Run form validation
     if ($this->form_validation->run()) {
         // Get OpenID store object
         $store = new Auth_OpenID_FileStore($this->config->item("openid_file_store_path"));
         // Get OpenID consumer object
         $consumer = new Auth_OpenID_Consumer($store);
         // Begin OpenID authentication process
         if (!($auth_request = $consumer->begin($this->input->post('connect_openid_url')))) {
             $data['connect_openid_error'] = sprintf(lang('connect_invalid_openid'), lang('connect_openid'));
         } else {
             // Create sreg_request (Simple Registration)
             if ($sreg_request = Auth_OpenID_SRegRequest::build(array('nickname', 'email', 'fullname', 'gender', 'dob', 'postcode', 'country', 'language', 'timezone'))) {
                 $auth_request->addExtension($sreg_request);
             }
             // Redirect to authorizate URL
             header("Location: " . $auth_request->redirectURL(base_url(), site_url('account/connect_openid')));
         }
     }
     $this->load->view('account/connect_openid', isset($data) ? $data : NULL);
 }
Пример #23
0
 /**
  * This method should handle any authentication and report back to the subject
  *
  * @access	public
  * @param   array 	$credentials Array holding the user credentials
  * @param 	array   $options     Array of extra options (return, entry_url)
  * @param	object	$response	Authentication response object
  * @return	boolean
  * @since 1.5
  */
 function onAuthenticate($credentials, $options, &$response)
 {
     global $mainframe;
     if (!defined('Auth_OpenID_RAND_SOURCE')) {
         define("Auth_OpenID_RAND_SOURCE", null);
     }
     require_once JPATH_LIBRARIES . DS . 'openid' . DS . 'consumer.php';
     jimport('joomla.filesystem.folder');
     // Access the session data
     $session =& JFactory::getSession();
     // Need to check for bcmath or gmp - if not, use the dumb mode.
     // TODO: Should dump an error to debug saying we are dumb
     global $_Auth_OpenID_math_extensions;
     $ext = Auth_OpenID_detectMathLibrary($_Auth_OpenID_math_extensions);
     if (!isset($ext['extension']) || !isset($ext['class'])) {
         define("Auth_OpenID_NO_MATH_SUPPORT", true);
     }
     // Create and/or start using the data store
     $store_path = JPATH_ROOT . '/tmp/_joomla_openid_store';
     if (!JFolder::exists($store_path) && !JFolder::create($store_path)) {
         $response->type = JAUTHENTICATE_STATUS_FAILURE;
         $response->error_message = "Could not create the FileStore directory '{$store_path}'. " . " Please check the effective permissions.";
         return false;
     }
     // Create store object
     $store = new Auth_OpenID_FileStore($store_path);
     // Create a consumer object
     $consumer = new Auth_OpenID_Consumer($store);
     if (!isset($_SESSION['_openid_consumer_last_token'])) {
         // Begin the OpenID authentication process.
         if (!($request = $consumer->begin($credentials['username']))) {
             $response->type = JAUTHENTICATE_STATUS_FAILURE;
             $response->error_message = 'Authentication error : could not connect to the openid server';
             return false;
         }
         // Request simple registration information
         $request->addExtensionArg('sreg', 'required', 'email');
         $request->addExtensionArg('sreg', 'optional', 'fullname, language, timezone');
         //Create the entry url
         $entry_url = isset($options['entry_url']) ? $options['entry_url'] : JURI::base();
         $entry_url = JURI::getInstance($entry_url);
         unset($options['entry_url']);
         //We don't need this anymore
         //Create the url query information
         $options['return'] = isset($options['return']) ? base64_encode($options['return']) : base64_encode(JURI::base());
         $options[JUtility::getToken()] = 1;
         $process_url = sprintf($entry_url->toString() . "&username=%s", $credentials['username']);
         $process_url .= '&' . JURI::buildQuery($options);
         $trust_url = $entry_url->toString(array('path', 'host', 'port', 'scheme'));
         $redirect_url = $request->redirectURL($trust_url, $process_url);
         $session->set('trust_url', $trust_url);
         // Redirect the user to the OpenID server for authentication.  Store
         // the token for this authentication so we can verify the response.
         $mainframe->redirect($redirect_url);
         return false;
     }
     $result = $consumer->complete(JRequest::get('get'));
     switch ($result->status) {
         case Auth_OpenID_SUCCESS:
             $sreg = $result->extensionResponse('sreg');
             $response->status = JAUTHENTICATE_STATUS_SUCCESS;
             $response->error_message = '';
             $response->email = isset($sreg['email']) ? $sreg['email'] : "";
             $response->fullname = isset($sreg['fullname']) ? $sreg['fullname'] : "";
             $response->language = isset($sreg['language']) ? $sreg['language'] : "";
             $response->timezone = isset($sreg['timezone']) ? $sreg['timezone'] : "";
             break;
         case Auth_OpenID_CANCEL:
             $response->status = JAUTHENTICATE_STATUS_CANCEL;
             $response->error_message = 'Authentication cancelled';
             break;
         case Auth_OpenID_FAILURE:
             $response->status = JAUTHENTICATE_STATUS_FAILURE;
             $response->error_message = 'Authentication failed';
             break;
     }
 }
Пример #24
0
 /**
  * Initiate an OpenID request
  *
  * @param boolean $allow_sreg Default true
  * @param string $process_url Default empty (will use $CFG->wwwroot)
  * @param array $params Array of extra parameters to append to the request
  */
 function do_request($allow_sreg = true, $process_url = '', $params = array())
 {
     global $CFG, $USER;
     // Create the consumer instance
     $store = new Auth_OpenID_FileStore($CFG->dataroot . '/openid');
     $consumer = new Auth_OpenID_Consumer($store);
     $openid_url = optional_param('openid_url', null);
     if (defined('GOOGLE_OPENID_URL') && !empty($openid_url) && (stristr($openid_url, '@google.') || stristr($openid_url, '@gmail.'))) {
         // BJB101206: map Google email addresses to OpenID url
         $tmpemail = $openid_url;
         $openid_url = GOOGLE_OPENID_URL;
         logout_guestuser();
         if (empty($USER->id) && ($tmpuser = get_complete_user_data('email', $tmpemail)) && $tmpuser->auth != 'openid') {
             $allow_sreg = true;
             // would like to verify email later
             $process_url = $CFG->wwwroot . '/auth/openid/actions.php';
             $USER = $tmpuser;
             $params['openid_tmp_login'] = true;
             // require flag in action.php
             $params['openid_action'] = 'change';
             $params['openid_url'] = $openid_url;
             $params['openid_mode'] = 'switch2openid';
             // arbitrary != null
             //error_log('/auth/openid/auth.php::do_request() - Found user email: '.$tmpemail);
         }
     }
     if (!empty($this->config->auth_openid_google_apps_domain)) {
         $openid_url = $this->config->auth_openid_google_apps_domain;
         new GApps_OpenID_Discovery($consumer);
     }
     $authreq = $consumer->begin($openid_url);
     if (!$authreq && $this->is_sso()) {
         $endpoint = new Auth_OpenID_ServiceEndpoint();
         $endpoint->server_url = $openid_url;
         $endpoint->claimed_id = Auth_OpenID_IDENTIFIER_SELECT;
         $endpoint->type_uris = array('http://specs.openid.net/auth/2.0/signon');
         $authreq = $consumer->beginWithoutDiscovery($endpoint);
     }
     if (!$authreq) {
         print_error('auth_openid_login_error', 'auth_openid');
     } else {
         // Add any simple registration fields to the request
         if ($allow_sreg === true) {
             $sreg_added = false;
             $req = array();
             $opt = array();
             $privacy_url = null;
             // Required fields
             if (!empty($this->config->openid_sreg_required)) {
                 $req = array_map('trim', explode(',', $this->config->openid_sreg_required));
                 $sreg_added = true;
             }
             // Optional fields
             if (!empty($this->config->openid_sreg_optional)) {
                 $opt = array_map('trim', explode(',', $this->config->openid_sreg_optional));
                 $sreg_added = true;
             }
             // Privacy statement
             if ($sreg_added && !empty($this->config->openid_privacy_url)) {
                 $privacy_url = $this->config->openid_privacy_url;
             }
             // We call the on_openid_do_request event handler function if it
             // exists. This is called before the simple registration (sreg)
             // extension is added to allow changes to be made to the sreg
             // data fields if required
             if (function_exists('on_openid_do_request')) {
                 on_openid_do_request($authreq);
             }
             // Finally, the simple registration data is added
             if ($sreg_added && !(sizeof($req) < 1 && sizeof($opt) < 1)) {
                 $sreg_request = Auth_OpenID_SRegRequest::build($req, $opt, $privacy_url);
                 if ($sreg_request) {
                     $authreq->addExtension($sreg_request);
                 }
             }
             if (defined('ADD_AX_SUPPORT')) {
                 $AXattr = array();
                 $AXattr[] = Auth_OpenID_AX_AttrInfo::make(AX_SCHEMA_EMAIL, 1, 1, 'email');
                 $AXattr[] = Auth_OpenID_AX_AttrInfo::make(AX_SCHEMA_NICKNAME, 1, 1, 'nickname');
                 $AXattr[] = Auth_OpenID_AX_AttrInfo::make(AX_SCHEMA_FULLNAME, 1, 1, 'fullname');
                 $AXattr[] = Auth_OpenID_AX_AttrInfo::make(AX_SCHEMA_FIRSTNAME, 1, 1, 'firstname');
                 $AXattr[] = Auth_OpenID_AX_AttrInfo::make(AX_SCHEMA_LASTNAME, 1, 1, 'lastname');
                 $AXattr[] = Auth_OpenID_AX_AttrInfo::make(AX_SCHEMA_COUNTRY, 1, 1, 'country');
                 // Create AX fetch request
                 $ax = new Auth_OpenID_AX_FetchRequest();
                 // Add attributes to AX fetch request
                 foreach ($AXattr as $attr) {
                     $ax->add($attr);
                 }
                 // Add AX fetch request to authentication request
                 $authreq->addExtension($ax);
             }
         }
         // Prepare the remaining components for the request
         if (empty($process_url)) {
             $process_url = $CFG->wwwroot . '/login/index.php';
         }
         if (is_array($params) && !empty($params)) {
             $query = '';
             foreach ($params as $key => $val) {
                 $query .= '&' . $key . '=' . $val;
             }
             $process_url .= '?' . substr($query, 1);
         }
         $trust_root = $CFG->wwwroot . '/';
         $_SESSION['openid_process_url'] = $process_url;
         // Finally, redirect to the OpenID provider
         // Check if the server is allowed ...
         if (!openid_server_allowed($authreq->endpoint->server_url, $this->config)) {
             print_error('auth_openid_server_blacklisted', 'auth_openid', '', $authreq->endpoint->server_url);
         } elseif ($authreq->shouldSendRedirect()) {
             $redirect_url = $authreq->redirectURL($trust_root, $process_url);
             // If the redirect URL can't be built, display an error message.
             if (Auth_OpenID::isFailure($redirect_url)) {
                 error($redirect_url->message);
             } else {
                 redirect($redirect_url);
             }
         } else {
             // Generate form markup and render it.
             $form_id = 'openid_message';
             $message = $authreq->getMessage($trust_root, $process_url, false);
             // Display an error if the form markup couldn't be generated;
             // otherwise, render the HTML.
             if (Auth_OpenID::isFailure($message)) {
                 error($message);
             } else {
                 $form_html = $message->toFormMarkup($authreq->endpoint->server_url, array('id' => $form_id), get_string('continue'));
                 echo '<html><head><title>OpenID request</title></head><body onload="document.getElementById(\'', $form_id, '\').submit();" style="text-align: center;"><div style="background: lightyellow; border: 1px solid black; margin: 30px 20%; padding: 5px 15px;"><p>', get_string('openid_redirecting', 'auth_openid'), '</p></div>', $form_html, '</body></html>';
                 exit;
             }
         }
     }
 }
Пример #25
0
 public static function sendOpenidRequest($openid = "", $returnUrl = "", $max_auth_age = 18000)
 {
     // The first half of the authentication process should basically
     // follow this plan: Add an OpenID login field somewhere on your site. When an OpenID
     // is entered in that field and the form is submitted, it should make
     // a request to the your site which includes that OpenID URL.
     // Please make sure the curl and openssl extensions are enabled in your PHP installation,
     // or else OpenIDs using https (e.g. Google's OpenID) will cause an "Invalid OpenID" error.
     //if (OPENIDDEBUG) echo "<h3>IN sendOpenidRequest</h3>";
     //if (OPENIDDEBUG) echo "<p>HTTP_REFERER=".$_SERVER["HTTP_REFERER"]."</p>";
     if (empty($openid) && empty($GLOBALS["domain"])) {
         return "Please sign in or enter your OpenID";
     }
     //TODO:
     //if (empty($returnUrl)) return "Ojoj";
     if (!is_integer($max_auth_age) || $max_auth_age < 0) {
         $max_auth_age = 0;
     }
     // --------------------------------
     self::doIncludes();
     // --------------------------------
     // (1) First, the application should instantiate the Auth_OpenID_Consumer
     // class using the store of choice (Auth_OpenID_FileStore or one of
     // the SQL-based stores).
     // --------------------------------
     $AOstore = self::getStore();
     // essentially: $AOstore = new Auth_OpenID_FileStore("/tmp");
     $AOconsumer = new Auth_OpenID_Consumer($AOstore);
     //new GApps_OpenID_Discovery($AOconsumer); // If want GoogleApps OP support
     // --------------------------------
     // (2) Next, the application should call the Auth_OpenID_Consumer object's
     // 'begin' method. This method takes the OpenID URL.
     //
     // The 'begin' method returns an Auth_OpenID_AuthRequest object.
     // Methods:
     //   -> addExtension()
     //   -> addExtensionArg()
     //   -> setAnonymous()
     //   -> getMessage()
     //   -> redirectURL()
     //   -> formMarkup()
     //   -> htmlMarkup()
     // --------------------------------
     $AOauthRequest = $AOconsumer->begin($openid);
     // No auth request means we can't begin OpenID
     if (!$AOauthRequest) {
         return "OpenID authentication failed: Please enter a valid OpenID";
     }
     $_SESSION["openid_server_url"] = $AOauthRequest->endpoint->server_url;
     // --------------------------------
     // (3a) Add SREG extensions to the request...
     // http://openid.net/specs/openid-simple-registration-extension-1_0.html
     // An Auth_OpenID_SRegRequest object holds the state of a SR request.
     // Defined in '/Auth/Openid/SReg.php'
     //
     // Please be aware that "required" doesn’t mean it’s guaranteed you will
     // get a value for the specified fields from the OpenID provider. It simply
     // means those fields are required for the registration process, and if they
     // are not in the response from the OpenID provider, you have to be prepared
     // to deal with such a situation, i.e. you have to ask the user to manually
     // enter the required data.
     // --------------------------------
     $sreg_data_fields_required = array('nickname', 'fullname', 'email');
     $sreg_data_fields_optional = array('gender', 'dob', 'postcode', 'country', 'language', 'timezone');
     $AOsregRequest = Auth_OpenID_SRegRequest::build($sreg_data_fields_required, $sreg_data_fields_optional);
     if ($AOsregRequest) {
         $AOauthRequest->addExtension($AOsregRequest);
     }
     // --------------------------------
     // (3b) Add ATTRIBUTE EXCHANGE extensions to the request...
     // http://openid.net/specs/openid-attribute-exchange-1_0.html
     // Supported parameters: http://openid.net/specs/openid-attribute-properties-list-1_0-01.html
     // Defined in '/Auth/Openid/AX.php'
     // --------------------------------
     //TODO...
     // -- AX SCHEMA
     // The URLs like openid.net/schema/namePerson/prefix are not supposed to work.
     // They are basically names formatted as URLs to make them unique.
     // To know which one to use, the best way I know of is to look for a "hint" about which
     // schema(s) are supported in the OP's XRDS document. DotNetOpenAuth does this, for example,
     // and has a good success rate. When the XRDS doesn't contain any of the AX schema URIs, you
     // can send all three AX attribute URI formats to best ensure a useful response.
     //   http://blog.nerdbank.net/2009/03/how-to-pretty-much-guarantee-that-you.html
     /*
     Google will only give you, say, an email address if the RP indicates that it is an AX "required" attribute.  Google completely ignores attribute requests marked as "requested".
     Google supports, according to it's website https://developers.google.com/accounts/docs/OpenID, the following "required" attributes:
     
         namePerson/first (first name)
         namePerson/last (last name)
         contact/country/home
         contact/email
         pref/language
     */
     /*
         // Birth year (four digits)
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/birthDate/birthYear",1,0,"birthyear");
         // Birth month (1-12)
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/birthDate/birthMonth",1,0,"birthmonth");
         // Birth day
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/birthDate/birthday",1,0,"birthday");
         // Gender "M" or "F"
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/gender",1,0,"gender");
         // Language, as per [RFC4646]
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/language/pref",1,0,"language_pref");
         // Phone (preferred)
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/phone/default",1,0,"phone_default");
         // Phone (home)
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/phone/home",1,0,"phone_home");
         // Phone (work)
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/phone/business",1,0,"phone_business");
         // Phone (mobile)
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/phone/cell",1,0,"phone_cell");
         // Phone (fax)
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/phone/fax",1,0,"phone_fax");
         // Address
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/postaladdress/home",1,0,"postaladdress_home");
         // Address 2
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/postaladdressadditional/home",1,0,"postaladdressadditional_home");
         // City
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/city/home",1,0,"city_home");
         // State/Province
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/state/home",1,0,"state_home");
         // Country
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/country/home",1,0,"country_home");
         // Postal code
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/postalcode/home",1,0,"postalcode_home");
         // Business postal address: street number, name and apartment number
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/postaladdress/business",1,0,"postaladdress_business");
         // Business postal address: supplementary information
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/postaladdressadditional/business",1,0,"postaladdressadditional_business");
         // Business city name
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/city/business",1,0,"city_business");
         // Business state or province name
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/state/business",1,0,"state_business");
         // Business country code in [ISO.3166.1988] (alpha 2) format
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/country/business",1,0,"country_business");
         // Business postal or zip code; region specific format
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/postalcode/business",1,0,"postalcode_business");
         // Preferred instant messaging service (one of http://".$axSchema."/contact/IM/*)
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/IM/default",1,0,"IM_default");
         // AOL instant messaging service handle
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/IM/AIM",1,0,"IM_AIM");
         // ICQ instant messaging service handle
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/IM/ICQ",1,0,"IM_ICQ");
         // MSN instant messaging service handle
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/IM/MSN",1,0,"IM_MSN");
         // Yahoo! instant messaging service handle
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/IM/Yahoo",1,0,"IM_Yahoo");
         // Jabber instant messaging service handle
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/IM/Jabber",1,0,"IM_Jabber");
         // Skype instant messaging service handle
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/IM/Skype",1,0,"IM_Skype");
         // Web site URL
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/web/default",1,0,"web_default");
         // Blog URL
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/web/blog",1,0,"web_blog");
         // LinkedIn URL
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/web/Linkedin",1,0,"web_Linkedin");
         // Amazon URL
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/web/Amazon",1,0,"web_Amazon");
         // Flickr URL
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/web/Flickr",1,0,"web_Flickr");
         // del.icio.us URL
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/contact/web/Delicious",1,0,"web_Delicious");
         // Company name (employer)
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/company/name",1,0,"company_name");
         // Employee title
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/company/title",1,0,"company_title");
         // Spoken name (web URL)
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/media/spokenname",1,0,"spokenname");
         // Audio greeting (web URL)
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/media/greeting/audio",1,0,"greeting_audio");
         // Video greeting (web URL)
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/media/greeting/video",1,0,"greeting_video");
         // Biography (text)
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/media/biography",1,0,"biography");
         // Image (web URL); 16x16 pixels
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/media/image/16x16",1,0,"image_16x16");
         // Image (web URL); 32x32 pixels
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/media/image/32x32",1,0,"image_32x32");
         // Image (web URL); 48x48 pixels
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/media/image/48x48",1,0,"image_48x48");
         // Image (web URL); 64x64 pixels
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/media/image/64x64",1,0,"image_64x64");
         // Image (web URL); 80x80 pixels
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/media/image/80x80",1,0,"image_80x80");
         // Image (web URL); 128x128 pixels
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/media/image/128x128",1,0,"image_128x128");
         // Image (web URL) 4:3 ratio - landscape; 160x120 pixels
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/media/image/160x120",1,0,"image_160x120");
         // Image (web URL) 4:3 ratio - landscape; 320x240 pixels
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/media/image/320x240",1,0,"image_320x240");
         // Image (web URL) 4:3 ratio - landscape; 640x480 pixels
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/media/image/640x480",1,0,"image_640x480");
         // Image (web URL) 4:3 ratio - portrait; 120x160 pixels
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/media/image/120x160",1,0,"image_120x160");
         // Image (web URL) 4:3 ratio - portrait; 240x320 pixels
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/media/image/240x320",1,0,"image_240x320");
         // Image (web URL) 4:3 ratio - portrait; 480x640 pixels
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/media/image/480x640",1,0,"image_480x640");
         // Image (web URL); favicon format
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/media/image/favicon",1,0,"image_favicon");
         // Home time zone information (as specified in [zoneinfo])
         $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema."/timezone",1,0,"timezone");
     */
     $axSchema = self::guessOpAxSchema($openid);
     // -- Create attribute request object
     // Usage: make($type_uri, $count=1, $required=false, $alias=null)
     // Required:
     // Alias or "screen" name
     $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema . "/namePerson/friendly", 1, 1, "friendly");
     // Image (web URL); unspecified dimension
     $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema . "/media/image", 1, 1, "image");
     // Optional:
     // Internet SMTP email address
     $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema . "/contact/internet/email", 1, 0, "internet_email");
     // First name
     $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema . "/namePerson/first", 1, 0, "first");
     // Last name
     $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema . "/namePerson/last", 1, 0, "last");
     // Honorific name prefix ("Mr.", "Mrs.", "Dr.")
     $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema . "/namePerson/prefix", 1, 0, "prefix");
     // Middle name
     $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema . "/namePerson/middle", 1, 0, "middle");
     // Name suffix
     $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema . "/namePerson/suffix", 1, 0, "suffix");
     // GUID - Subject's globally unique identifier
     $attribute[] = Auth_OpenID_AX_AttrInfo::make($axSchema . "/person/guid", 1, 0, "guid");
     // NB. 'myopenid.com' seems to crash if there are more than two attributes (regardless of priorities)!
     // Also, only 'friendly' seems to be returned anyway.
     if (in_array(self::guessOpDomain($openid), array("myopenid"))) {
         $attribute = array_slice($attribute, 0, 2);
     }
     // -- Create AX fetch request
     $AOaxRequest = new Auth_OpenID_AX_FetchRequest();
     // -- Add attributes to AX fetch request
     foreach ($attribute as $attr) {
         $AOaxRequest->add($attr);
     }
     // -- Add AX fetch request to authentication request
     if ($AOaxRequest) {
         $AOauthRequest->addExtension($AOaxRequest);
     }
     // --------------------------------
     // (3c) Add PAPE policies to the request...
     // http://openid.net/specs/openid-provider-authentication-policy-extension-1_0.html
     // Defined in '/Auth/Openid/PAPE.php'
     //
     // $preferred_auth_policies: The authentication policies that
     // the relying party prefers
     //
     // $max_auth_age: The maximum time, in seconds, that the relying party
     // wants to allow to have elapsed before the user must re-authenticate
     //
     //   -- Physical Multi-Factor Authentication [extension of Multi-Factor Authentication]
     //
     //   PAPE_AUTH_MULTI_FACTOR_PHYSICAL = 'http://schemas.openid.net/pape/policies/2007/06/multi-factor-physical'
     //
     //   An authentication mechanism where the End User authenticates to the OpenID Provider by providing more than one authentication factor where at least one of the factors is a physical factor such as a hardware device or biometric. Common authentication factors are something you know, something you have, and something you are. This policy also implies the Multi-Factor Authentication policy (http://schemas.openid.net/pape/policies/2007/06/multi-factor) and both policies MAY BE specified in conjunction without conflict. An example would be authentication using a password and a hardware token.
     //
     //   -- Multi-Factor Authentication
     //
     //   PAPE_AUTH_MULTI_FACTOR = 'http://schemas.openid.net/pape/policies/2007/06/multi-factor'
     //
     //   An authentication mechanism where the End User authenticates to the OpenID Provider by providing more than one authentication factor. Common authentication factors are something you know, something you have, and something you are. An example would be authentication using a password and a software token or digital certificate.
     //
     //   -- Phishing-Resistant Authentication
     //
     //   PAPE_AUTH_PHISHING_RESISTANT = 'http://schemas.openid.net/pape/policies/2007/06/phishing-resistant'
     //
     //   An authentication mechanism where a party potentially under the control of the Relying Party can not gain sufficient information to be able to successfully authenticate to the End User's OpenID Provider as if that party were the End User. (Note that the potentially malicious Relying Party controls where the User-Agent is redirected to and thus may not send it to the End User's actual OpenID Provider).
     //
     //   -- Additional polices can be found at http://schemas.openid.net/pape/policies/
     //
     // --------------------------------
     $preferred_auth_policies = null;
     if (isset($_GET['policies'])) {
         $preferred_auth_policies = $_GET['policies'];
     } else {
         //$preferred_auth_policies[] = PAPE_AUTH_MULTI_FACTOR_PHYSICAL;
         //$preferred_auth_policies[] = PAPE_AUTH_MULTI_FACTOR;
         $preferred_auth_policies[] = PAPE_AUTH_PHISHING_RESISTANT;
     }
     $AOpapeRequest = new Auth_OpenID_PAPE_Request($preferred_auth_policies, $max_auth_age);
     if ($AOpapeRequest) {
         $AOauthRequest->addExtension($AOpapeRequest);
     }
     // --------------------------------
     // (3d) Add USER INTERFACE extensions to the request...
     // http://svn.openid.net/repos/specifications/user_interface/1.0/trunk/openid-user-interface-extension-1_0.html
     // Seems not to be defined in any '/Auth/Openid/...'
     // http://google-code-updates.blogspot.com/2009/05/google-openid-api-taking-next-steps.html
     // http://www.sociallipstick.com/?p=86
     //
     // -- openid.ns.ui
     //    (required) Indicates that the OpenID provider's authentication pages will be
     //    displayed in an alternative user interface. This parameter must be set to
     //      "http://specs.openid.net/extensions/ui/1.0"
     //
     // -- openid.ui.lang
     //    (requred; but not by Google, apparently) The user's preferred languages as a BCP-47
     //    language priority list, represented as a comma-separated list of BCP-47 basic language
     //    ranges in descending priority order. For instance, the value "fr-CA,fr-FR,en-CA"
     //    represents the preference for French spoken in Canada, French spoken in France,
     //    followed by English spoken in Canada.
     // -- openid.ui.mode
     //    (optional) Specifies the alternative user interface. The following values are valid:
     //      "popup"
     //         The RP SHOULD create the popup to be 450 pixels wide and 500 pixels tall. The popup
     //         MUST have the address bar displayed, and MUST be in a standalone browser window.
     //         The contents of the popup MUST NOT be framed by the RP.
     //         The RP SHOULD open the popup centered above the main browser window, and SHOULD dim
     //         the contents of the parent window while the popup is active. The RP SHOULD ensure
     //         that the user is not surprised by the appearance of the popup, and understands how
     //         to interact with it.
     //         To keep the user popup user experience consistent, it is RECOMMENDED that the OP
     //         does not resize the popup window unless the OP requires additional space to show
     //         special features that are not usually displayed as part of the default popup
     //         user experience.
     //         The OP MAY close the popup without returning a response to the RP. Closing the
     //         popup without sending a response should be interpreted as a negative assertion.
     //      "x-has-session" (used to indicate the presence of an authenticated session)
     //
     // -- openid.ui.icon
     //    (optional) Displays the favicon of the referring domain in the OpenID approval
     //    page if set to:
     //      "true"
     //    The RP SHOULD indicate the location of the graphical resource by adding an entry
     //    to its XRDS document.
     // --------------------------------
     //TODO
     // --------------------------------
     // (4) Next, the application should call the 'redirectURL' method of the
     // Auth_OpenID_AuthRequest object. This will redirect the user to the OpenID
     // server for authentication, and then store the token for this authentication
     // so we can verify the response.
     //
     // The 'return_to' URL parameter is the URL that the OpenID server will send the
     // user back to after attempting to verify his or her identity.
     // The 'trust_root' is the URL (or URL pattern) that identifies your web site
     // to the user when he or she is authorizing it.
     // Send a redirect to the resulting URL to the user's browser.
     // --------------------------------
     //
     // For OpenID v.1, send a redirect.
     // For OpenID v.2, use a Javascript form to send a POST request to the server.
     if ($AOauthRequest->shouldSendRedirect()) {
         // -- OPENID v.1
         $redirect_url = $AOauthRequest->redirectURL(self::getTrustRoot(), $returnUrl);
         /*
         $redirect_url =
         "http://www.myopenid.com/server?openid.assoc_handle=%7BHMAC-SHA1%7D%7B51346dca%7D%7BO4GEqw%3D%3D%7D&openid.claimed_id=http%3A%2F%2Fhvzm.myopenid.com%2F&openid.identity=http%3A%2F%2Fhvzm.myopenid.com%2F&openid.mode=checkid_setup&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.ns.pape=http%3A%2F%2Fspecs.openid.net%2Fextensions%2Fpape%2F1.0&openid.pape.preferred_auth_policies=&openid.realm=http%3A%2F%2Fwww.nordita.org%3A80%2F%7Ehvzm%2Fwww.nordita.org%2Fnews%2Finstitute%2F&openid.return_to=http%3A%2F%2Fwww.nordita.org%2F%7Ehvzm%2Fwww.nordita.org%2Fnews%2Finstitute%2Findex.php%3Farticleid%3D25%26janrain_nonce%3D2013-03-04T19%253A33%253A42Z46a1kl"
         */
         // If the redirect URL can't be built, display an error message
         if (Auth_OpenID::isFailure($redirect_url)) {
             return "Could not redirect to server: " . $redirect_url->message;
         } else {
             // Send redirect
             header("Location: " . $redirect_url);
         }
     } else {
         // -- OPENID v.2
         // $attr - An array of attributes to be added to the form tag.
         // 'accept-charset' and 'enctype' have defaults that can be overridden.
         // If a value is supplied for 'action' or 'method', it will be replaced. [NOP]
         $attr = array("id" => "openid_message", "accept-charset" => "UTF-8,ISO-8859-1;q=0.7,*;q=0.3", "enctype" => "application/x-www-form-urlencoded", "method" => "post");
         // Generate form markup:
         $form_html = $AOauthRequest->htmlMarkup(self::getTrustRoot(), $returnUrl, false, $attr);
         /*
         $form_html =
         "<html><head><title>OpenId transaction in progress</title></head>
         <body onload='document.forms[0].submit();'>
         <form accept-charset="UTF-8" enctype="application/x-www-form-urlencoded" id="openid_message" action="http://www.myopenid.com/server" method="post">
         <input type="hidden" name="openid.ns"           value="http://specs.openid.net/auth/2.0" />
         <input type="hidden" name="openid.ns.pape"      value="http://specs.openid.net/extensions/pape/1.0" />
         <input type="hidden" name="openid.pape.preferred_auth_policies"
                                                         value="" />
         <input type="hidden" name="openid.realm"        value="http://www.nordita.org:80/~hvzm/www.nordita.org/news/institute/" />
         <input type="hidden" name="openid.mode"         value="checkid_setup" />
         <input type="hidden" name="openid.return_to"    value="http://www.nordita.org/~hvzm/www.nordita.org/
                                                                news/institute/index.php?articleid=25
                                                                &amp;janrain_nonce=2013-03-04T19%3A19%3A08ZhdbeR4" />
         <input type="hidden" name="openid.identity"     value="http://hvzm.myopenid.com/" />
         <input type="hidden" name="openid.claimed_id"   value="http://hvzm.myopenid.com/" />
         <input type="hidden" name="openid.assoc_handle" value="{HMAC-SHA1}{51346dca}{O4GEqw==}" />
         <input type="submit" value="Continue" />
         </form>
         <script>
           var elements = document.forms[0].elements;
           for (var i = 0; i < elements.length; i++) { elements[i].style.display = "none";}
         </script>
         </body></html>"
         */
         //if (OPENIDDEBUG) echo htmlspecialchars($form_html);die("#");
         //if (OPENIDDEBUG) print "<br>RETURN URL = $returnUrl<br><br>".htmlspecialchars($form_html);die("%");
         // Assemble OpenId request, for debug purposes
         unset($_SESSION["openid_request"]);
         $txt = $form_html;
         $txt = htmlspecialchars($form_html);
         $txt = str_replace("\"", "'", str_replace("&quot;", "'", $txt));
         $txt = preg_replace("%&lt;.*action=(.*)&gt;%iU", "  action = \\1", $txt);
         $txt = preg_replace("%&lt;.* name='%iU", "  ", $txt);
         $txt = str_replace("' value=", " = ", $txt);
         $txt = str_replace(" /&gt;", "", $txt);
         $txt = preg_replace("%&lt;.*type='submit.*\\s.*\\s.*%i", "", $txt);
         $_SESSION["openid_request"] = $txt;
         // Display an error if the form markup couldn't be generated;
         // otherwise, render the HTML.
         if (Auth_OpenID::isFailure($form_html)) {
             $_SESSION["openid_request"] = "<strong>Could not redirect to server</strong>: " . htmlspecialchars($form_html->message);
             return $_SESSION["openid_request"];
         } else {
             header("X-XRDS-Location: " . URL_PREFIX . "/openid.xml");
             //TODO
             print $form_html;
             // automatic redirect to openid provider
             die;
             // essential!
         }
     }
     // end if
     return false;
     // NB. normal exit is via HTTP redirects
 }
Пример #26
0
Fifth Floor, Boston, MA 02110-1301 USA
--> */
// check for form input
if (trim($_POST['openid'] == '')) {
    die("ERROR: Please enter a valid OpenID.");
}
// include files
require_once "Auth/OpenID/Consumer.php";
require_once "Auth/OpenID/FileStore.php";
// start session (needed for YADIS)
session_start();
// create file storage area for OpenID data
$store = new Auth_OpenID_FileStore('/var/tmp/oid_store');
// create OpenID consumer
$consumer = new Auth_OpenID_Consumer($store);
// begin sign-in process
// create an authentication request to the OpenID provider
$auth = $consumer->begin($_POST['openid']);
if (!$auth) {
    die("ERROR: Please enter a valid OpenID.");
}
$httphost = $_SERVER['HTTP_HOST'];
$path = $_SERVER['SCRIPT_NAME'];
if ($_GET['nxrw_path']) {
    $path = $_GET['nxrw_path'];
}
$path_prefix = dirname($path) . '/';
$link_prefix = $path . '?nid=';
// redirect to OpenID provider for authentication
$url = $auth->redirectURL('http://' . $httphost, 'http://' . $httphost . $link_prefix . 'x-openid-login-done');
header('Location: ' . $url);