Beispiel #1
0
function openid_verify()
{
    $consumer = new Auth_OpenID_Consumer(new Auth_OpenID_MySQLStore(theDb()));
    // Complete the authentication process using the server's
    // response.
    $return_to = getReturnTo();
    $response = $consumer->complete($return_to);
    // Check the response status.
    if ($response->status == Auth_OpenID_CANCEL) {
        // This means the authentication was cancelled.
        $msg = 'Verification cancelled.';
    } else {
        if ($response->status == Auth_OpenID_FAILURE) {
            // Authentication failed; display the error message.
            $msg = "OpenID authentication failed: " . $response->message;
        } else {
            if ($response->status == Auth_OpenID_SUCCESS) {
                // This means the authentication succeeded; extract the
                // identity URL and Simple Registration data (if it was
                // returned).
                $openid = $response->getDisplayIdentifier();
                $esc_identity = htmlentities($openid);
                $success = sprintf('You have successfully verified ' . '<a href="%s">%s</a> as your identity.', $esc_identity, $esc_identity);
                if ($response->endpoint->canonicalID) {
                    $escaped_canonicalID = htmlentities($response->endpoint->canonicalID);
                    $success .= '  (XRI CanonicalID: ' . $escaped_canonicalID . ') ';
                }
                $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
                $sreg = $sreg_resp->contents();
                $ax = new Auth_OpenID_AX_FetchResponse();
                $obj = $ax->fromSuccessResponse($response);
                if ($obj) {
                    function ax_get($obj, $url)
                    {
                        if (!$obj) {
                            return "";
                        }
                        $x = $obj->get($url);
                        if (is_array($x) && is_string($x[0])) {
                            return $x[0];
                        }
                        return "";
                    }
                    if ($x = ax_get($obj, 'http://axschema.org/contact/email')) {
                        $sreg["email"] = $x;
                    }
                    if ($x = ax_get($obj, 'http://axschema.org/namePerson/first')) {
                        $sreg["fullname"] = $x . " " . ax_get($obj, 'http://axschema.org/namePerson/last');
                    }
                }
                openid_user_update($openid, $sreg);
                unset($_SESSION["auth_error"]);
                return true;
            }
        }
    }
    $_SESSION["auth_error"] = $msg;
    return false;
}
Beispiel #2
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]");
  }
}
Beispiel #3
0
 /**
  *  login_finish action implementation.
  *
  *  @access public
  *  @return string  forward name.
  */
 public function perform()
 {
     // if login do?
     $identity = $this->af->get('openid_identity');
     if ($this->af->get('janrain_nonce')) {
         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));
         $response = $consumer->complete($this->config->get('url') . "login_finish");
         if ($response->status == Auth_OpenID_CANCEL) {
             // This means the authentication was cancelled.
             $this->ae->add(null, "認証がキャンセルされました.Pastitを利用するには認証してください.");
             return 'login';
         } else {
             if ($response->status == Auth_OpenID_FAILURE) {
                 // Authentication failed; display the error message.
                 $this->ae->add(null, "認証に失敗しました.(" . $response->message . ")");
                 return 'login';
             } else {
                 if ($response->status == Auth_OpenID_SUCCESS) {
                     $openid_success_url = $response->getDisplayIdentifier();
                     $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
                     $sreg = $sreg_resp->contents();
                     $nickname = isset($sreg['nickname']) ? $sreg['nickname'] : "";
                     $this->session->set("identity", $identity);
                     $this->session->set("openid_success_url", $openid_success_url);
                 }
             }
         }
     }
     $um = $this->backend->getManager('user');
     if ($user = $um->getUserByIdentity($identity)) {
         $this->session->set('user', $user);
         return array('redirect', '/');
     } else {
         if (!Ethna::isError($id = $um->create($identity, $nickname))) {
             $user = $um->getUser($id);
             $this->session->set('user', $user);
             return array('redirect', 'setting');
         } else {
             $this->ae->addObject('name', $id);
             return 'error500';
         }
     }
     return 'login';
 }
 /**
  * @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 [];
 }
Beispiel #5
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;
 }
Beispiel #6
0
 /**
  *  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';
 }
 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;
 }
 /**
  * Function to process the response of the OpenID server
  */
 function processopenidresponse()
 {
     $consumer = new Auth_OpenID_Consumer(new OpenIDStorage(), new SessionWrapper());
     $trust_root = Director::absoluteBaseURL();
     $return_to_url = $trust_root . $this->Link('ProcessOpenIDResponse');
     // Complete the authentication process using the server's response.
     $response = $consumer->complete($return_to_url);
     if ($response->status == Auth_OpenID_SUCCESS) {
         Session::clear("FormInfo.Form_RegistrationWithOpenIDForm.data");
         $openid = $response->identity_url;
         if ($response->endpoint->canonicalID) {
             $openid = $response->endpoint->canonicalID;
         }
         $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
         $sreg = $sreg_resp->contents();
         // Convert the simple registration data to the needed format
         // try to split fullname to get firstname and surname
         $data = array('IdentityURL' => $openid);
         if (isset($sreg['nickname'])) {
             $data['Nickname'] = $sreg['nickname'];
         }
         if (isset($sreg['fullname'])) {
             $fullname = explode(' ', $sreg['fullname'], 2);
             if (count($fullname) == 2) {
                 $data['FirstName'] = $fullname[0];
                 $data['Surname'] = $fullname[1];
             } else {
                 $data['Surname'] = $fullname[0];
             }
         }
         if (isset($sreg['country'])) {
             $data['Country'] = $sreg['country'];
         }
         if (isset($sreg['email'])) {
             $data['Email'] = $sreg['email'];
         }
         Session::set("FormInfo.Form_RegistrationForm.data", $data);
         Director::redirect($this->Link('register'));
         return;
     }
     // The server returned an error message, handle it!
     if ($response->status == Auth_OpenID_CANCEL) {
         $error_message = _t('ForumMemberProfile.CANCELLEDVERIFICATION', 'The verification was cancelled. Please try again.');
     } else {
         if ($response->status == Auth_OpenID_FAILURE) {
             $error_message = _t('ForumMemberProfile.AUTHENTICATIONFAILED', 'The OpenID/i-name authentication failed.');
         } else {
             $error_message = _t('ForumMemberProfile.UNEXPECTEDERROR', 'An unexpected error occured. Please try again or register without OpenID');
         }
     }
     $this->RegistrationWithOpenIDForm()->addErrorMessage("Blurb", $error_message, 'bad');
     Director::redirect($this->Link('registerwithopenid'));
 }
 /**
  * @todo check whether the url field causes errors due to rewriting
  */
 public function getResponse($aReturnTo)
 {
     $OpenIDConsumer = new Auth_OpenID_Consumer($this->OpenIDStorage, $this->OpenIDSessionInterface);
     return $OpenIDConsumer->complete($aReturnTo, Auth_OpenID::getQuery());
 }
Beispiel #10
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;
 }
 /**
  * Run the controller (default action)
  *
  * @param array $requestParams Passed request parameters
  */
 function index($requestParams)
 {
     if (isset($_GET['debug_profile'])) {
         Profiler::mark("OpenIDAuthenticator_Controller");
     }
     $consumer = new Auth_OpenID_Consumer(new OpenIDStorage(), new SessionWrapper());
     // Complete the authentication process using the server's response.
     $response = $consumer->complete();
     if ($response->status == Auth_OpenID_CANCEL) {
         Session::set("Security.Message.message", _t('OpenIDAuthenticator.VERIFICATIONCANCELLED', 'The verification was cancelled. Please try again.'));
         Session::set("Security.Message.type", "bad");
         if (isset($_GET['debug_profile'])) {
             Profiler::unmark("OpenIDAuthenticator_Controller");
         }
         Director::redirect("Security/login");
     } else {
         if ($response->status == Auth_OpenID_FAILURE) {
             Session::set("Security.Message.message", _t('OpenIDAuthenticator.AUTHFAILED', 'The OpenID/i-name authentication failed.'));
             Session::set("Security.Message.type", "bad");
             if (isset($_GET['debug_profile'])) {
                 Profiler::unmark("OpenIDAuthenticator_Controller");
             }
             Director::redirect("Security/login");
         } else {
             if ($response->status == Auth_OpenID_SUCCESS) {
                 $openid = $response->identity_url;
                 if ($response->endpoint->canonicalID) {
                     $openid = $response->endpoint->canonicalID;
                 }
                 if (isset($_GET['debug_profile'])) {
                     Profiler::unmark("OpenIDAuthenticator_Controller");
                 }
                 $SQL_identity = Convert::raw2sql($openid);
                 if ($member = DataObject::get_one("Member", "Member.IdentityURL = '{$SQL_identity}'")) {
                     $firstname = Convert::raw2xml($member->FirstName);
                     Session::set("Security.Message.message", sprintf(_t('Member.WELCOMEBACK'), $firstname));
                     Session::set("Security.Message.type", "good");
                     $member->LogIn(Session::get('SessionForms.OpenIDLoginForm.Remember'));
                     Session::clear('SessionForms.OpenIDLoginForm.OpenIDURL');
                     Session::clear('SessionForms.OpenIDLoginForm.Remember');
                     if ($backURL = Session::get("BackURL")) {
                         Session::clear("BackURL");
                         Director::redirect($backURL);
                     } else {
                         Director::redirectBack();
                     }
                 } else {
                     Session::set("Security.Message.message", _t('OpenIDAuthenticator.LOGINFAILED', 'Login failed. Please try again.'));
                     Session::set("Security.Message.type", "bad");
                     if ($badLoginURL = Session::get("BadLoginURL")) {
                         Director::redirect($badLoginURL);
                     } else {
                         Director::redirectBack();
                     }
                 }
             }
         }
     }
 }
Beispiel #12
0
 public function action_finish()
 {
     // Get the OpenID identity
     $openid = Arr::get($_REQUEST, 'openid_identity');
     // Get the return page URI, default to home
     $return_to = Arr::get($_REQUEST, 'return_to', '');
     $store = new Auth_OpenID_FileStore($this->store_path);
     $consumer = new Auth_OpenID_Consumer($store);
     $response = $consumer->complete(URL::site($this->request->uri, TRUE));
     if ($response->status == Auth_OpenID_CANCEL) {
         throw new Exception(__('OpenID authentication cancelled.'));
     } elseif ($response->status == Auth_OpenID_FAILURE) {
         throw new Exception(__('OpenID authentication failed:') . ' ' . $response->message);
     } elseif ($response->status == Auth_OpenID_SUCCESS) {
         $openid = htmlentities($response->getDisplayIdentifier());
         // Create the user in our DB
         $user = ORM::factory('user')->save_openid($openid);
         // Log the user in
         Auth::instance()->force_login($user);
         // TODO: As we only have the open idententity, we should redirect to
         // profile page so user can update email etc.
         $message = $user->username . ' successfully signed in.';
         Message::set(Message::SUCCESS, __($message));
         $this->request->redirect($return_to);
     }
 }
Beispiel #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);
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;
}
 /**
  * @param array - the user data to get
  * @return boolean - true if success, false otherwise
  */
 public function receive(&$data)
 {
     // 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
     $response = $consumer->complete($this->returnToUrl);
     if ($response->status == Auth_OpenID_SUCCESS) {
         // Get registration informations
         $ax = new Auth_OpenID_AX_FetchResponse();
         $obj = $ax->fromSuccessResponse($response);
         // Print me raw
         $data = $obj->data;
         return true;
     } else {
         return false;
     }
 }
Beispiel #16
0
 /**
  * Iff user was authenticated (at URL returned by getLoginUrl),
  * returns associative array that WILL contain user's Harvard email
  * address (mail) and that MAY contain user's name (displayName).
  *
  * @param return_to  URL to which CS50 ID returned user
  *
  * @return user as associative array
  */
 public static function getUser($return_to)
 {
     // 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);
     // get response
     $consumer = new Auth_OpenID_Consumer($store);
     $response = $consumer->complete($return_to);
     if ($response->status == Auth_OpenID_SUCCESS) {
         // get user's identity
         $user = ["identity" => $response->identity_url];
         // get Simple Registration fields, if any
         if ($sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response)) {
             $user = array_merge($user, $sreg_resp->contents());
         }
         // get Attribute Exchange attributes, if any
         if ($ax_resp = Auth_OpenID_AX_FetchResponse::fromSuccessResponse($response)) {
             $user = array_merge($user, $ax_resp->data);
         }
     }
     // restore error_reporting
     error_reporting($error_reporting);
     // return user unless error
     return isset($user) ? $user : false;
 }
Beispiel #17
0
<?php

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();
$store = new Auth_OpenID_Store_FileStore('./tmp');
$consumer = new Auth_OpenID_Consumer($store);
$scriptPath = implode("/", explode('/', $_SERVER["REQUEST_URI"], -1));
$response = $consumer->complete('https://' . $_SERVER["SERVER_NAME"] . $scriptPath . '/verify.php');
$authenticated = false;
if ($response->status == Auth_OpenID_SUCCESS) {
    $ax = new Auth_OpenID_Extension_AX_FetchResponse();
    $obj = $ax->fromSuccessResponse($response);
    $_SESSION['openid_ax'] = $obj->data;
    $pape = Auth_OpenID_PAPE_Response::fromSuccessResponse($response);
    if ($pape) {
        $_SESSION['openid_pape'] = $pape;
    }
    $msg = "User has been authenticated!";
} elseif ($response->status == Auth_OpenID_CANCEL) {
    $msg = "User cancelled authentication.";
} else {
    $msg = "User has not been authenticated.";
}
if (isset($_GET['popup'])) {
    ?>

<h1><?php 
    echo $msg;
Beispiel #18
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;
     }
 }
Beispiel #19
0
 /**
  * Process an OpenID response
  *
  * By default, this method uses the error() function to display errors. This
  * is a terminal function so if you want to display errors inline using the
  * notify() function you will need to pass true to the $notify_errors
  * argument
  *
  * @param boolean $notify_errors Default true
  * @return mixed Successful response object or false
  */
 function process_response($notify_errors = false)
 {
     global $CFG;
     // Create the consumer instance
     $store = new Auth_OpenID_FileStore($CFG->dataroot . '/openid');
     $consumer = new Auth_OpenID_Consumer($store);
     if (!empty($this->config->auth_openid_google_apps_domain)) {
         new GApps_OpenID_Discovery($consumer);
     }
     $resp = $consumer->complete($_SESSION['openid_process_url']);
     unset($_SESSION['openid_process_url']);
     // Act based on response status
     switch ($resp->status) {
         case Auth_OpenID_SUCCESS:
             // Auth succeeded
             return $resp;
         case Auth_OpenID_CANCEL:
             // Auth cancelled by user.
             $msg = get_string('auth_openid_user_cancelled', 'auth_openid');
             if ($notify_errors) {
                 notify($msg);
             } else {
                 error($msg);
             }
             break;
         case Auth_OpenID_FAILURE:
             // Auth failed for some reason
             $msg = openid_get_friendly_message($resp->message);
             $msg = get_string('auth_openid_login_failed', 'auth_openid', $msg);
             error_log("/auth/openid/auth.php::process_response() - Auth_OpenID_FAILURE: {$msg}");
             if ($notify_errors) {
                 notify($msg);
             } else {
                 error($msg);
             }
     }
     return false;
 }
Beispiel #20
0
 public static function analyzeOpenidResponse($return_to, $server_url = "")
 {
     self::doIncludes();
     $idData = $idData["data"] = array();
     $_GET = $_REQUEST;
     // Janrain bugfix (?)
     // ------------------------------------------
     // Assemble OpenId response, for debug purposes
     //echo "<br>REQUEST=";debug::rrr();
     //echo "<br>GET=";debug::rr($_GET);
     unset($_SESSION["openid_response"]);
     $txt = "";
     foreach ($_GET as $key => $val) {
         if (preg_match("/^openid_(.*)\$/", $key, $res)) {
             $txt .= "  openid." . str_replace("_", ".", $res[1]) . " = '" . $val . "'\r\n";
         }
     }
     $_SESSION["openid_response"] = $txt;
     // ------------------------------------------
     // The second half of the process is done after the user's ID server sends
     // the user's browser a redirect back to your site to complete their
     // login.
     //
     // When that happens, the user will contact your site at the URL given
     // as the 'return_to' URL to the Auth_OpenID_AuthRequest::redirectURL
     // call made above.  The request will have several query parameters
     // added to the URL by the identity server as the information
     // necessary to finish the request.
     //if (OPENIDDEBUG) echo "<h3>IN analyzeOpenidResponse</h3>";
     // ------------------------------------------
     // (4) Instantiate an Auth_OpenID_Consumer instance as above
     $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
     // ------------------------------------------
     // (5) Call its 'complete' method of the Auth_OpenID_Consumer instance, passing
     // in all the received query arguments from the server's response.
     // The result $AOconsumerResponse is an instance of the Auth_OpenID_ConsumerResponse class
     $AOconsumerResponse = $AOconsumer->complete($return_to);
     /*
     debug::rr($AOconsumerResponse);
     echo gettype($_SESSION["_yadis_services__openid_consumer_"]);
     echo gettype($_SESSION["_yadis_services__openid_consumer_"]["endpoint"]);
     echo gettype($_SESSION["_yadis_services__openid_consumer_"]["_current"]);
     var_dump($_SESSION["_yadis_services__openid_consumer_"]["_current"]->server_url);
     if (isset($_SESSION["_yadis_services__openid_consumer_"]["endpoint"]["server_url"])) {
       $server_url = $_SESSION["_yadis_services__openid_consumer_"]["endpoint"]["server_url"];
     } else
     if (isset($_SESSION["_yadis_services__openid_consumer_"]["_current"]->server_url)) {
       $server_url = $_SESSION["_yadis_services__openid_consumer_"]["_current"]->server_url;
     } else {
       $server_url = "";
     }
     
     // $server_url =
     */
     //echo "<br>getAssociation= [$server_url]";debug::rr($AOstore->getAssociation($server_url));
     //echo "<br>_yadis_services__openid_consumer_ = ";debug::rr(unserialize($_SESSION["_yadis_services__openid_consumer_"]));
     //echo "<br>_openid_consumer_last_token = ";debug::rr($_SESSION["_openid_consumer_last_token"]);
     /*
     Output from $AOstore->getAssociation($server_url):
     
     Auth_OpenID_Association Object
     (
         [SIG_LENGTH] => 20
         [assoc_keys] => Array
             (
                 [0] => version
                 [1] => handle
                 [2] => secret
                 [3] => issued
                 [4] => lifetime
                 [5] => assoc_type
             )
         [_macs] => Array
             (
                 [HMAC-SHA1] => Auth_OpenID_HMACSHA1
                 [HMAC-SHA256] => Auth_OpenID_HMACSHA256
             )
         [handle] => 24a50fd087db11e2b793002655277584
         [secret] => �dc��GY,�Y�|��"
         [issued] => 1362738606
         [lifetime] => 86398
         [assoc_type] => HMAC-SHA1
     )
     */
     // ------------------------------------------
     // (6) There are multiple possible return types possible from that
     // method. These indicate the whether or not the login was successful,
     // and include any additional information appropriate for their type.
     if ($AOconsumerResponse->status == Auth_OpenID_CANCEL) {
         // This means the authentication was cancelled
         return "<strong>OpenID authentication was cancelled</strong>";
     } else {
         if ($AOconsumerResponse->status == Auth_OpenID_FAILURE) {
             // Authentication failed; display the error message
             if (isset($_SESSION["openid_last_valid_identifier"])) {
                 unset($_SESSION["openid_last_valid_identifier"]);
             }
             $error_org = htmlspecialchars($AOconsumerResponse->message);
             $error_public = "";
             if (strpos($error_org, "Bad signature") !== false && strpos($error_org, "Nonce already") !== false) {
                 $error_public = "Please try again";
             }
             if (IS_TESTSERVER) {
                 $error = ":<br>" . $error_org . (!empty($error_public) ? " (" . $error_public . ")" : "");
             } else {
                 $error = !empty($error_public) ? ":<br>" . $error_public : "";
             }
             // Panic error recovery
             if (strpos($error_org, "Bad signature") !== false || strpos($error_org, "No mode set") !== false) {
                 //if (isset($_SESSION["openid_identifier"])) unset($_SESSION["openid_identifier"]); // NOP!
                 self::cleanStore();
                 //echo "clean";
             }
             return "<strong>OpenID authentication failed</strong>" . $error;
         } else {
             if ($AOconsumerResponse->status == Auth_OpenID_SUCCESS) {
                 // This means the authentication succeeded; extract the
                 // identity URL and Simple Registration data (if it was
                 // returned).
                 // ---------------------
                 // RETURN THE DISPLAY IDENTIFIER FOR THIS RESPONSE
                 //
                 // The display identifier is related to the Claimed Identifier, but the
                 // two are not always identical. The display identifier is something the
                 // user should recognize as what they entered, whereas the response's
                 // claimed identifier (in the identity_url attribute) may have extra
                 // information for better persistence.
                 //
                 // URLs will be stripped of their fragments for display.  XRIs will
                 // display the human-readable identifier (i-name) instead of the
                 // persistent identifier (i-number).
                 //
                 // Use the display identifier in your user interface.  Use
                 // identity_url for querying your database or authorization server.
                 $idData["display_identifyer"] = htmlentities($AOconsumerResponse->getDisplayIdentifier());
                 if (@$AOconsumerResponse->endpoint->canonicalID) {
                     $idData["xri_canonical_id"] = htmlentities($AOconsumerResponse->endpoint->canonicalID);
                 }
                 //TODO: fragile
                 if (!empty($idData["display_identifyer"])) {
                     $_SESSION["openid_last_valid_identifier"] = $idData["display_identifyer"];
                 }
                 // ---------------------
                 // ANALYZE SIMPLE REGISTRATION EXTENSIONS
                 //
                 // http://openid.net/specs/openid-simple-registration-extension-1_0.html
                 //
                 // This extension allows you to retrieve nine commonly requested pieces of
                 // information: nickname, email, fullname, dob (date of birth), gender, postcode,
                 // country, language, and timezone.
                 //
                 // Please be aware that some OpenID providers (for example, Google) don't support SReg.
                 $idData["sreg"] = array();
                 $AOsregResponse = Auth_OpenID_SRegResponse::fromSuccessResponse($AOconsumerResponse);
                 $sregArr = $AOsregResponse->contents();
                 if (is_array($sregArr)) {
                     foreach ($sregArr as $key => $val) {
                         $idData["sreg"][$key] = htmlentities($val);
                         $idData["data"][$key][] = htmlentities($val);
                     }
                 }
                 // ---------------------
                 // ANALYZE ATTRIBUTE EXCHANGE
                 //
                 // http://openid.net/specs/openid-attribute-exchange-1_0.html
                 //
                 // Attribute Exchange allows you to retrieve identity information from the OpenID provider,
                 // if supported. http://www.axschema.org/types contains a list with possible attribute names,
                 // though only a small subset is usually supported by the OpenID providers.
                 $idData["ax"] = array();
                 $AOaxResponse = Auth_OpenID_AX_FetchResponse::fromSuccessResponse($AOconsumerResponse);
                 if ($AOaxResponse) {
                     $axArr = $AOaxResponse->data;
                     if (is_array($axArr)) {
                         foreach ($axArr as $key => $vals) {
                             foreach (array("axschema.org", "openid.net/schema", "schema.openid.net") as $schema) {
                                 $key = str_replace("http://" . $schema . "/", "", $key);
                             }
                             $idData["ax"][$key] = array();
                             if (is_array($vals)) {
                                 foreach ($vals as $val) {
                                     $idData["ax"][$key][] = htmlentities($val);
                                 }
                             }
                         }
                     }
                     if (!empty($idData["ax"]["namePerson/friendly"])) {
                         foreach ($idData["ax"]["namePerson/friendly"] as $value) {
                             $idData["data"]["nickname"][] = $value;
                         }
                     }
                     if (!empty($idData["ax"]["contact/internet/email"])) {
                         foreach ($idData["ax"]["contact/internet/email"] as $value) {
                             $idData["data"]["email"][] = $value;
                         }
                     }
                     //TODO: fragile
                     $fullname = (!empty($idData["ax"]["namePerson/prefix"][0]) ? $idData["ax"]["namePerson/prefix"][0] : "") . (!empty($idData["ax"]["namePerson/first"][0]) ? $idData["ax"]["namePerson/first"][0] : "") . (!empty($idData["ax"]["namePerson/middle"][0]) ? $idData["ax"]["namePerson/middle"][0] : "") . (!empty($idData["ax"]["namePerson/last"][0]) ? $idData["ax"]["namePerson/last"][0] : "") . (!empty($idData["ax"]["namePerson/suffix"][0]) ? $idData["ax"]["namePerson/suffix"][0] : "");
                     if (!empty($fullname)) {
                         $idData["data"]["fullname"][] = $fullname;
                     }
                     if (!empty($idData["ax"]["media/image"])) {
                         $idData["data"]["image"] = $idData["ax"]["media/image"];
                     }
                     if (!empty($idData["ax"]["person/guid"])) {
                         $idData["data"]["guid"] = $idData["ax"]["person/guid"];
                     }
                     if (!empty($idData["ax"]["birthDate/birthYear"][0]) && !empty($idData["ax"]["birthDate/birthMonth"][0]) && !empty($idData["ax"]["birthDate/birthday"][0])) {
                         $idData["data"]["dob"][] = $idData["ax"]["birthDate/birthYear"][0] . "-" . $idData["ax"]["birthDate/birthMonth"][0] . "-" . $idData["ax"]["birthDate/birthday"][0];
                     }
                     if (!empty($idData["ax"]["gender"])) {
                         foreach ($idData["ax"]["gender"] as $value) {
                             $idData["data"]["gender"][] = $value;
                         }
                     }
                     if (!empty($idData["ax"]["contact/postalcode/home"])) {
                         // There are other variants
                         foreach ($idData["ax"]["contact/postalcode/home"] as $value) {
                             $idData["data"]["postcode"][] = $value;
                         }
                     }
                     if (!empty($idData["ax"]["contact/country/home"])) {
                         // There are other variants
                         foreach ($idData["ax"]["contact/country/home"] as $value) {
                             $idData["data"]["country"][] = $value;
                         }
                     }
                     if (!empty($idData["ax"]["language/pref"])) {
                         foreach ($idData["ax"]["language/pref"] as $value) {
                             $idData["data"]["language"][] = $value;
                         }
                     }
                     if (!empty($idData["ax"]["timezone"])) {
                         foreach ($idData["ax"]["timezone"] as $value) {
                             $idData["data"]["timezone"][] = $value;
                         }
                     }
                 }
                 /*
                 // http://code.42dh.com/openid/
                 
                 class UsersController extends AppController {
                     public $components = array('Openid');
                 
                     public function login() {
                         $realm = 'http://'.$_SERVER['HTTP_HOST'];
                         $returnTo = $realm . '/users/login';
                 
                         if ($this->request->isPost() && !$this->Openid->isOpenIDResponse()) {
                             $this->makeOpenIDRequest($this->data['OpenidUrl']['openid'], $returnTo, $realm);
                         } elseif ($this->Openid->isOpenIDResponse()) {
                             $this->handleOpenIDResponse($returnTo);
                         }
                     }
                 
                     private function makeOpenIDRequest($openid, $returnTo, $realm) {
                         // some OpenID providers (e.g. MyOpenID) use 'schema.openid.net' instead of 'axschema.org'
                         $attributes[] = Auth_OpenID_AX_AttrInfo::make('http://axschema.org/namePerson', 1, true, 'fullname');
                         $this->Openid->authenticate($openid, $returnTo, $realm, array('ax' => $attributes));
                     }
                 
                     private function handleOpenIDResponse($returnTo) {
                         $AOconsumerResponse = $this->Openid->getResponse($returnTo);
                 
                         if ($AOconsumerResponse->status == Auth_OpenID_SUCCESS) {
                             $axResponse = Auth_OpenID_AX_FetchResponse::fromSuccessResponse($AOconsumerResponse);
                 
                             if ($axResponse) {
                                 debug($axResponse->get('http://axschema.org/namePerson'));
                                 debug($axResponse->getSingle('http://axschema.org/namePerson'));
                             }
                         }
                     }
                 }
                 */
                 // ---------------------
                 // ANALYZE PAPE EXTENSION
                 //
                 // http://openid.net/specs/openid-provider-authentication-policy-extension-1_0.html
                 $idData["pape"] = array();
                 // Create an Auth_OpenID_PAPE_Response object from a successful OpenID library response.
                 // Properties: ->auth_policies, ->auth_time, ->nist_auth_level
                 // Methods: ->getExtensionArgs(), ->fromSuccessResponse()
                 $AOpapeResponse = Auth_OpenID_PAPE_Response::fromSuccessResponse($AOconsumerResponse);
                 if ($AOpapeResponse) {
                     // One or more PAPE authentication policy URIs representing policies that the OP
                     // satisfied when authenticating the End User. If no policies were met though the
                     // OP wishes to convey other information in the response, this parameter is
                     // included with the value of http://schemas.openid.net/pape/policies/2007/06/none
                     //TODO: if policies have been requested but not used (value='none' or empty array), perhaps an error should be issued?
                     $pols = $AOpapeResponse->auth_policies;
                     $idData["pape"]["auth_policies"] = array();
                     // = "none";
                     if (is_array($pols)) {
                         if (count($pols) > 1 || isset($pols[0]) && !preg_match("#none\$#", $pols[0])) {
                             foreach ($AOpapeResponse->auth_policies as $uri) {
                                 $idData["pape"]["auth_policies"][] = htmlentities($uri);
                             }
                         }
                     }
                     // The authentication age: the most recent timestamp when the End User has
                     // actively authenticated to the OP in a manner fitting the asserted policies.
                     // All times are in the UTC time zone, indicated with a "Z", and with no fractional seconds.
                     if (@$AOpapeResponse->auth_time) {
                         $idData["pape"]["auth_time"] = htmlentities($AOpapeResponse->auth_time);
                     }
                     // The NIST Assurance Level that corresponds to the authentication method and
                     // policies employed by the OP when authenticating the End User.
                     if (@$AOpapeResponse->nist_auth_level) {
                         $idData["pape"]["nist_auth_level"] = htmlentities($AOpapeResponse->nist_auth_level);
                     }
                     // [This fix somewhat duplicates the reading off of class properties above, but
                     // ensures that also "empty" values are captured.]
                     $arg = $AOpapeResponse->getExtensionArgs();
                     if (is_array($arg)) {
                         foreach ($arg as $key => $val) {
                             if (!isset($idData["pape"][$key])) {
                                 if ($key == "auth_policies" && preg_match("#none\$#", $val)) {
                                     $idData["pape"][$key] = array();
                                 } else {
                                     $idData["pape"][$key] = htmlentities($val);
                                 }
                             }
                         }
                     }
                 }
                 // end pape
             }
         }
     }
     return $idData;
 }
Beispiel #21
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);
     // Create our own endpoint and skip the discovery step.
     $endpoint = new Auth_OpenID_ServiceEndpoint();
     $endpoint->server_url = $this->config->openid_sso_url;
     $endpoint->claimed_id = Auth_OpenID_IDENTIFIER_SELECT;
     $endpoint->type_uris = array(Auth_OpenID_OPENID1_NS);
     $authreq = $consumer->beginWithoutDiscovery($endpoint);
     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 ($authreq->shouldSendRedirect()) {
             $redirect_url = $authreq->redirectURL($trust_root, $process_url);
             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;
             }
         }
     }
 }
 static function authenticate_openid($getData, $store_path, $returnData = false)
 {
     global $serendipity;
     $trust_root = $serendipity['baseURL'] . 'serendipity_admin.php';
     $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";
     require_once "Auth/OpenID/SReg.php";
     require_once "Auth/OpenID/PAPE.php";
     $store = new Auth_OpenID_FileStore($store_path);
     $consumer = new Auth_OpenID_Consumer($store);
     $response = $consumer->complete($trust_root);
     //, $getData);
     if ($response->status == Auth_OpenID_CANCEL) {
         $success = 'Verification cancelled.';
     } else {
         if ($response->status == Auth_OpenID_FAILURE) {
             $success = "OpenID authentication failed: " . $response->message;
         } else {
             if ($response->status == Auth_OpenID_SUCCESS) {
                 // This means the authentication succeeded; extract the
                 // identity URL and Simple Registration data (if it was
                 // returned).
                 $openid = $response->getDisplayIdentifier();
                 $esc_identity = escape($openid);
                 $success = sprintf('You have successfully verified ' . '<a href="%s">%s</a> as your identity.', $esc_identity, $esc_identity);
                 if ($response->endpoint->canonicalID) {
                     $escaped_canonicalID = escape($response->endpoint->canonicalID);
                     $success .= '  (XRI CanonicalID: ' . $escaped_canonicalID . ') ';
                 }
                 $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
                 $sreg = $sreg_resp->contents();
                 if (@$sreg['email']) {
                     escape($sreg['email']);
                     $success .= "  You also returned '" . escape($sreg['email']) . "' as your email.";
                 }
                 if (@$sreg['nickname']) {
                     $success .= "  Your nickname is '" . escape($sreg['nickname']) . "'.";
                 }
                 if (@$sreg['fullname']) {
                     $success .= "  Your fullname is '" . escape($sreg['fullname']) . "'.";
                 }
             }
         }
     }
     if (!empty($openid)) {
         if ($returnData) {
             return array('realname' => $realname, 'email' => $email, 'openID' => $openid);
         }
         $password = md5($openid);
         $query = "SELECT DISTINCT a.email, a.authorid, a.userlevel, a.right_publish, a.realname\r\n                     FROM\r\n                       {$serendipity['dbPrefix']}authors AS a, {$serendipity['dbPrefix']}openid_authors AS oa\r\n                     WHERE\r\n                       oa.openid_url = '" . serendipity_db_escape_string($openid) . "' and \r\n                       oa.authorid = a.authorid";
         $row = serendipity_db_query($query, true, 'assoc');
         if (is_array($row)) {
             serendipity_setCookie('old_session', session_id());
             serendipity_setAuthorToken();
             $_SESSION['serendipityUser'] = $serendipity['serendipityUser'] = $row['realname'];
             $_SESSION['serendipityPassword'] = $serendipity['serendipityPassword'] = $password;
             $_SESSION['serendipityEmail'] = $serendipity['serendipityEmail'] = $email;
             $_SESSION['serendipityAuthorid'] = $serendipity['authorid'] = $row['authorid'];
             $_SESSION['serendipityUserlevel'] = $serendipity['serendipityUserlevel'] = $row['userlevel'];
             $_SESSION['serendipityAuthedUser'] = $serendipity['serendipityAuthedUser'] = true;
             $_SESSION['serendipityRightPublish'] = $serendipity['serendipityRightPublish'] = $row['right_publish'];
             $_SESSION['serendipityRealname'] = $serendipity['serendipityRealname'] = $row['realname'];
             $_SESSION['serendipityOpenID'] = true;
             serendipity_load_configuration($serendipity['authorid']);
             return true;
         } else {
             $_SESSION['serendipityAuthedUser'] = false;
             @session_destroy();
         }
     }
     return false;
 }
Beispiel #23
0
or write to the Free Software Foundation, Inc., 51 Franklin Street,
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');
Beispiel #24
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')));
 }
Beispiel #25
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;
     }
 }
Beispiel #26
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);
 }
 /**
  * Using this option, we need to redirect to user profile after login
  * to update user details as we have no other way of getting this info
  * @return type
  */
 function openIdLogin()
 {
     // 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');
     $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';
     $objMkDir = $this->getObject('mkdir', 'files');
     $openidPath = $this->objConfig->getcontentBasePath() . '/openid';
     $objMkDir->mkdirs($openidPath);
     $store = new Auth_OpenID_FileStore($openidPath);
     $consumer = new Auth_OpenID_Consumer($store);
     $response = $consumer->complete($OPENID_CALLBACK_PAGE);
     if ($response->status == Auth_OpenID_SUCCESS) {
         $ax = new Auth_OpenID_AX_FetchResponse();
         $obj = $ax->fromSuccessResponse($response);
         $data = $obj->data;
         //this is a workaround because some openid providers, like myopenid.com,
         //does not fully support attribute exchange just yet. They're working on it.
         //I may update it in the future.
         if ($_SESSION['openid_user']) {
             $email = $_SESSION['openid_user'];
             $_SESSION['openid_user'] = null;
         } else {
             $email = $data['http://axschema.org/contact/email']['0'];
         }
         $_SESSION['user'] = $email;
         $_SESSION['AUTH'] = true;
         $me = array();
         $updateDetailsPhrase = $this->objLanguage->languageText("mod_security_updateprofile", 'security');
         $me['username'] = $email;
         $me['email'] = $email;
         $me['first_name'] = $updateDetailsPhrase;
         $me['last_name'] = '';
         $me['gender'] = 'male';
         $me['id'] = mt_rand(1000, 9999) . date('ymd');
         return $this->openIdAuth($me);
     } else {
         $_SESSION['AUTH'] = false;
         header('Location: ' . $siteRoot . '?module=security&action=error&message=no_openidconnect&msg=mod_security_problemlogginginwith');
     }
 }
Beispiel #28
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;
     }
 }
Beispiel #29
0
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses
or write to the Free Software Foundation, Inc., 51 Franklin Street,
Fifth Floor, Boston, MA 02110-1301 USA
--> */
// 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
// read response from OpenID provider
$consumer = new Auth_OpenID_Consumer($store);
$httphost = $_SERVER['HTTP_HOST'];
$response = $consumer->complete($httphost . $link_prefix . 'x-openid-login-done');
// set session variable depending on authentication result
if ($response->status == Auth_OpenID_SUCCESS) {
    $_SESSION['OPENID_AUTH'] = true;
} else {
    $_SESSION['OPENID_AUTH'] = false;
}
$_SESSION['OPENID_AUTH'] = true;
$username = Nexista_Path::get('//user_login/user_login/username', 'flow');
$user_id = Nexista_Path::get('//user_login/user_login/id', 'flow');
$group_id = Nexista_Path::get('//user_login/user_login/group_id', 'flow');
$user_last_visit = Nexista_Path::get('//user_login/user_login/last_visit', 'flow');
$last_visit = gmdate('Y-m-d H:i:s', $user_last_visit);
// Remove duplicate roles