fromSuccessResponse() static public method

Construct a FetchResponse object from an OpenID library SuccessResponse object.
static public fromSuccessResponse ( $success_response, $signed = true )
function run()
{
    $consumer = getConsumer();
    // 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.';
        if (isset($_COOKIE[session_name()])) {
            setcookie(session_name(), '', time() - 42000, '/');
        }
        session_destroy();
    } else {
        if ($response->status == Auth_OpenID_FAILURE) {
            // Authentication failed; display the error message.
            $msg = "OpenID authentication failed: " . $response->message;
            if (isset($_COOKIE[session_name()])) {
                setcookie(session_name(), '', time() - 42000, '/');
            }
            session_destroy();
        } 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);
                $_SESSION = array();
                $_SESSION['openid'] = $esc_identity;
                if ($response->endpoint->canonicalID) {
                    $escaped_canonicalID = escape($response->endpoint->canonicalID);
                    $success .= '  (XRI CanonicalID: ' . $escaped_canonicalID . ') ';
                    $_SESSION['openid'] = $escaped_canonicalID;
                }
                // AX Process
                $ax_resp = Auth_OpenID_AX_FetchResponse::fromSuccessResponse($response);
                if ($ax_resp) {
                    global $ax_data;
                    foreach ($ax_data as $ax_key => $ax_data_ns) {
                        if ($ax_resp->data[$ax_data_ns][0]) {
                            $_SESSION['ax_' . $ax_key] = $ax_resp->data[$ax_data_ns][0];
                        }
                    }
                }
            }
        }
    }
    if ($_GET["popup"] == "true") {
        include 'close.php';
    } else {
        if ($_GET["callback"] == "ax") {
            header("Location: ./ax_example.php");
        } else {
            header("Location: ./index.php");
        }
    }
}
function openid_check($ci, $callback_url, &$data)
{
    if (!isset($data)) {
        $data = array();
    }
    $ci->lang->load('openid');
    $ci->config->load('openid');
    $ci->openid->set_request_to($callback_url);
    $response = $ci->openid->getResponse();
    switch ($response->status) {
        case Auth_OpenID_CANCEL:
            push_message($ci->lang->line('openid_cancel'), 'error', $ci);
            break;
        case Auth_OpenID_FAILURE:
            push_message(set_message('openid_failure', $response->message), 'error', $ci);
            break;
        case Auth_OpenID_SUCCESS:
            $openid = $response->getDisplayIdentifier();
            $esc_identity = htmlspecialchars($openid, ENT_QUOTES);
            $data['openid_identifier'] = $openid;
            $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
            $sreg = $sreg_resp->contents();
            $ax_resp = new Auth_OpenID_AX_FetchResponse();
            $ax = $ax_resp->fromSuccessResponse($response);
            if (isset($sreg['email'])) {
                $data['email'] = $sreg['email'];
            }
            if ($ax) {
                if (isset($ax->data['http://axschema.org/contact/email'])) {
                    $data['email'] = $ax->getSingle('http://axschema.org/contact/email');
                }
                if (isset($ax->data['http://axschema.org/namePerson/first'])) {
                    $first_name = $ax->getSingle('http://axschema.org/namePerson/first');
                } else {
                    $first_name = "Sample";
                }
                if (isset($ax->data['http://axschema.org/namePerson/last'])) {
                    $last_name = $ax->getSingle('http://axschema.org/namePerson/last');
                } else {
                    $last_name = "Avatar";
                }
                if ($first_name != null && $last_name != null) {
                    $data['username'] = "******";
                }
            }
            return true;
    }
    return false;
}
 public function googledoneAction()
 {
     $consumer = $this->getGoogleConsumer();
     $return_to = 'http://' . $_SERVER['HTTP_HOST'] . '/login/googledone';
     $response = $consumer->complete($return_to);
     if ($response->status == Auth_OpenID_CANCEL) {
         return $this->alert('取消登入', '/');
     }
     if ($response->status == Auth_OpenID_FAILURE) {
         return $this->alert('登入失敗: ' . $response->message, '/');
     }
     $ax = new Auth_OpenID_AX_FetchResponse();
     $obj = $ax->fromSuccessResponse($response);
     $email = $obj->data['http://axschema.org/contact/email'][0];
     if (!($user = User::search(array('user_name' => 'google://' . $email))->first())) {
         $user = User::insert(array('user_name' => 'google://' . $email));
     }
     Pix_Session::set('user_id', $user->user_id);
     return $this->redirect('/');
 }
Example #4
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;
 }
Example #5
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')));
 }
Example #6
0
 /**
  * Finish up authentication.
  *
  * @access  public
  * @return  string
  */
 public function finish_auth()
 {
     $msg = $error = $success = '';
     $consumer = $this->_get_consumer();
     // Complete the authentication process using the server's response.
     $response = $consumer->complete($this->_get_self());
     // Check the response status.
     if ($response->status == Auth_OpenID_CANCEL) {
         $data = $this->_throw_error(OPENID_RETURN_CANCEL);
     } else {
         if ($response->status == Auth_OpenID_FAILURE) {
             $data = $this->_throw_error(OPENID_RETURN_FAILURE, $response->message);
         } else {
             if ($response->status == Auth_OpenID_SUCCESS) {
                 // if AX
                 $ax_resp = Auth_OpenID_AX_FetchResponse::fromSuccessResponse($response);
                 if ($response->endpoint->used_yadis && $ax_resp) {
                     $data = $ax_resp->data;
                     $new_data = array();
                     foreach ($data as $i => $item) {
                         if (array_key_exists($i, $this->ax_aliases)) {
                             $new_data[$this->ax_aliases[$i]] = $item;
                         } else {
                             $new_data[$i] = $item;
                         }
                     }
                     $data = $new_data;
                 } else {
                     $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
                     $data = $sreg_resp->contents();
                 }
             }
         }
     }
     // if handling a popup request
     if ($this->ci->session->userdata('_openid_popup')) {
         $this->ci->session->unset_userdata('_openid_popup');
         // store the data in a session
         $this->ci->session->set_userdata('_openid_data', $data);
         // close the popup
         include OPENID_DIRECTORY . 'EasyOpenID_close.php';
         die;
     } else {
         return $data;
     }
 }
Example #7
0
/**
 * Get attributes from OpenID response and populate 'user'-like structure
 * If matching user exists then return matching user
 *
 * @param string $resp - the OpenID response
 * @return user object - false on multiple matches, or the matching user object 
 *                       _or_ new user object with members:
 *                           username, email, firstname, lastname, country
 */
function openid_resp_to_user(&$resp)
{
    $tmp_users = array();
    $user = new stdClass();
    $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($resp);
    $sreg = $sreg_resp->contents();
    if (defined('ADD_AX_SUPPORT')) {
        $ax_resp = new Auth_OpenID_AX_FetchResponse();
        $ax = $ax_resp->fromSuccessResponse($resp);
    }
    // We'll attempt to use the user's nickname to set their username
    if (isset($sreg['nickname']) && !empty($sreg['nickname']) && !($tmp_users['username'] = get_records('user', 'username', addslashes($sreg['nickname']))) || defined('USE_EMAIL_FOR_USERNAME') && isset($sreg['email']) && !empty($sreg['email']) && !($tmp_users['username_email'] = get_records('user', 'username', $sreg['email']))) {
        $user->username = addslashes(isset($sreg['nickname']) && !empty($sreg['nickname']) ? $sreg['nickname'] : $sreg['email']);
    } else {
        if (defined('ADD_AX_SUPPORT') && (($nickname = get_ax_data(AX_SCHEMA_NICKNAME, $ax)) && !($tmp_users['username'] = get_records('user', 'username', addslashes($nickname))) || defined('USE_EMAIL_FOR_USERNAME') && ($useremail = get_ax_data(AX_SCHEMA_EMAIL, $ax)) && !($tmp_users['username_email'] = get_records('user', 'username', $useremail)))) {
            // better to fall-back to email? may show-up in various display blocks
            $user->username = addslashes($nickname ? $nickname : $useremail);
        } else {
            $user->username = openid_normalize_url_as_username($resp->identity_url);
        }
    }
    // SREG fullname
    if (isset($sreg['fullname']) && !empty($sreg['fullname'])) {
        $name = openid_parse_full_name($sreg['fullname']);
        $user->firstname = addslashes($name['first']);
        $user->lastname = addslashes($name['last']);
    } else {
        if (defined('ADD_AX_SUPPORT') && (get_ax_data(AX_SCHEMA_FULLNAME, $ax) || get_ax_data(AX_SCHEMA_LASTNAME, $ax))) {
            if (get_ax_data(AX_SCHEMA_LASTNAME, $ax)) {
                $user->firstname = addslashes(get_ax_data(AX_SCHEMA_FIRSTNAME, $ax));
                $user->lastname = addslashes(get_ax_data(AX_SCHEMA_LASTNAME, $ax));
            } else {
                // fullname
                $name = openid_parse_full_name(get_ax_data(AX_SCHEMA_FULLNAME, $ax));
                $user->firstname = addslashes($name['first']);
                $user->lastname = addslashes($name['last']);
            }
        }
    }
    if (!empty($user->lastname)) {
        $tmp_users['fullname'] = get_records_select('user', "firstname = '" . $user->firstname . "' AND lastname = '" . $user->lastname . "'");
    }
    // SREG email
    if (!empty($sreg['email']) && !($tmp_users['email'] = get_records('user', 'email', $sreg['email']))) {
        $user->email = addslashes($sreg['email']);
    } else {
        if (defined('ADD_AX_SUPPORT') && ($useremail = get_ax_data(AX_SCHEMA_EMAIL, $ax)) && !($tmp_users['email'] = get_records('user', 'email', $useremail))) {
            $user->email = addslashes($useremail);
        }
    }
    // SREG country
    $country = '';
    if (isset($sreg['country']) && !empty($sreg['country'])) {
        $country = $sreg['country'];
    } else {
        if (defined('ADD_AX_SUPPORT') && get_ax_data(AX_SCHEMA_COUNTRY, $ax)) {
            $country = get_ax_data(AX_SCHEMA_COUNTRY, $ax);
        }
    }
    if (!empty($country)) {
        $country_code = strtoupper($country);
        $countries = get_list_of_countries();
        if (strlen($country) != 2 || !isset($countries[$country_code])) {
            $countries_keys = array_keys($countries);
            $countries_vals = array_values($countries);
            $country_code = array_search($country, $countries_vals);
            if ($country_code > 0) {
                $country_code = $countries_keys[$country_code];
            } else {
                $country_code = '';
            }
        }
        if (!empty($country_code)) {
            $user->country = $country_code;
        }
    }
    /* We're currently not attempting to get language and timezone values
        // SREG language
        if (isset($sreg['language']) && !empty($sreg['language'])) {
        }
    
        // SREG timezone
        if (isset($sreg['timezone']) && !empty($sreg['timezone'])) {
        }
      */
    $config = get_config('auth/openid');
    //error_log("/auth/openid/locallib.php::auth/openid::config=...");
    //err_dump($config);
    //error_log("/auth/openid/locallib.php::openid_resp_to_user() - check for user matching ...");
    //err_dump($user);
    // Map OpenID fields to whether field MUST be unique
    // TBD: make unique fields configurable im OpenID: auth_config_users.html
    // Keys must match keys in tmp_users[] array - set above.
    $openid_fields = array('email' => 1, 'fullname' => 0, 'username' => 0, 'username_email' => 1);
    foreach ($openid_fields as $openid_field => $field_unique) {
        $match_array = str_word_count($config->auth_openid_match_fields, 1, '_');
        $num = !empty($match_array) ? 1 : 0;
        if ($field_unique && !empty($tmp_users[$openid_field]) && count($tmp_users[$openid_field]) > $num) {
            //error_log("/auth/openid/locallib.php::openid_resp_to_user() - multiple matches on count(tmp_users[{$openid_field}])=".count($tmp_users[$openid_field])." ...");
            //err_dump($tmp_users[$openid_field]);
            //error_log("> match_array=...");
            //err_dump($match_array);
            return false;
        }
    }
    $matching_user = null;
    // check tmp_users[] matches for valid existing user,
    // return false if conflicts between matching fields
    if (!empty($config->auth_openid_match_fields)) {
        $openid_match_fields = explode(',', $config->auth_openid_match_fields);
        foreach ($openid_match_fields as $match_field) {
            $match_field = trim($match_field);
            if (!empty($tmp_users[$match_field]) && count($tmp_users[$match_field]) == 1) {
                if (!$matching_user) {
                    $matching_user = reset($tmp_users[$match_field]);
                } else {
                    if ($openid_fields[$match_field] && $matching_user->id != reset($tmp_users[$match_field])->id) {
                        // unique field matches different user!
                        return false;
                    }
                }
            }
        }
    }
    if (!empty($matching_user)) {
        merge_user_fields($matching_user, $user);
        //error_log( "openid_resp_to_user() - merged matching user: ");
        //err_dump($matching_user);
        return $matching_user;
    }
    return $user;
}
Example #8
0
function run()
{
    $consumer = getConsumer();
    // 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 = 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']) {
                    $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']) . "'.";
                }
                // Show all the registration data
                $success .= '<h2>SReg Data</h2>';
                $success .= PHP_EOL . '<pre>';
                $success .= print_r(@$sreg, true);
                $success .= '</pre>' . PHP_EOL;
                $ax = new Auth_OpenID_AX_FetchResponse();
                $obj = $ax->fromSuccessResponse($response);
                $success .= '<h2>AX Data</h2>';
                if ($obj) {
                    $success .= PHP_EOL . '<pre>';
                    $success .= print_r($obj->data, true);
                    $success .= '</pre>' . PHP_EOL;
                } else {
                    $success .= PHP_EOL . '<pre>';
                    $success .= PHP_EOL . 'Type is ' . gettype($obj) . PHP_EOL;
                    $success .= print_r($obj, true);
                    $success .= '</pre>' . PHP_EOL;
                }
                $pape_resp = Auth_OpenID_PAPE_Response::fromSuccessResponse($response);
                if ($pape_resp) {
                    if ($pape_resp->auth_policies) {
                        $success .= "<p>The following PAPE policies affected the authentication:</p><ul>";
                        foreach ($pape_resp->auth_policies as $uri) {
                            $escaped_uri = escape($uri);
                            $success .= "<li><tt>{$escaped_uri}</tt></li>";
                        }
                        $success .= "</ul>";
                    } else {
                        $success .= "<p>No PAPE policies affected the authentication.</p>";
                    }
                    if ($pape_resp->auth_age) {
                        $age = escape($pape_resp->auth_age);
                        $success .= "<p>The authentication age returned by the " . "server is: <tt>" . $age . "</tt></p>";
                    }
                    if ($pape_resp->nist_auth_level) {
                        $auth_level = escape($pape_resp->nist_auth_level);
                        $success .= "<p>The NIST auth level returned by the " . "server is: <tt>" . $auth_level . "</tt></p>";
                    }
                } else {
                    $success .= "<p>No PAPE response was sent by the provider.</p>";
                }
            }
        }
    }
    include 'index.php';
}
Example #9
0
 /**
 * Verifies a given signed assertion.
 * @param &Attribute_Verifier &$attributeVerifier - An instance of the class 
                                         passed for the verification.
 * @param Auth_OpenID_Response - Response object for extraction.
 * @return boolean - true if successful, false if verification fails.
 */
 function verifyAssertion(&$attributeVerifier, $response)
 {
     $ax_resp = Auth_OpenID_AX_FetchResponse::fromSuccessResponse($response);
     if ($ax_resp instanceof Auth_OpenID_AX_FetchResponse) {
         $ax_args = $ax_resp->getExtensionArgs();
         if ($ax_args) {
             $value = base64_decode($ax_args['value.ext1.1']);
             if ($attributeVerifier->verify($value)) {
                 return base64_decode($ax_args['value.ext0.1']);
             } else {
                 return null;
             }
         } else {
             return null;
         }
     } else {
         return null;
     }
 }
Example #10
0
 function compare_useremail_response($user, $response, &$return_email = null)
 {
     $email = null;
     if (empty($user) || empty($user->email)) {
         return true;
     }
     // cannot compare, assume ok
     $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
     $sreg = $sreg_resp->contents();
     if (defined('ADD_AX_SUPPORT')) {
         $ax_resp = new Auth_OpenID_AX_FetchResponse();
         $ax = $ax_resp->fromSuccessResponse($response);
         $email = get_ax_data(AX_SCHEMA_EMAIL, $ax);
     }
     if (empty($email) && !empty($sreg['email'])) {
         $email = $sreg['email'];
     }
     if ($return_email !== null) {
         $return_email = $email;
     }
     //error_log("/auth/openid/auth.php::compare_useremail_response(): $user->email ?= $email ");
     return !empty($email) ? $user->email == $email : true;
 }
 /**
  * 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');
     }
 }
 private function finishAuth()
 {
     $consumer = getConsumer();
     // 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.
         echo 'Verification cancelled.';
     } else {
         if ($response->status == Auth_OpenID_FAILURE) {
             // Authentication failed; display the error message.
             echo "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);
                 // Fetch some random information
                 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();
                 $email = isset($sreg['email']) ? $sreg['email'] : null;
                 $language = isset($sreg['language']) ? strtolower($sreg['language']) : null;
                 $country = isset($sreg['country']) ? $sreg['country'] : null;
                 $dob = isset($sreg['dob']) ? $sreg['dob'] : null;
                 $gender = isset($sreg['gender']) ? $sreg['gender'] : null;
                 if (!empty($dob)) {
                     $_SESSION['birthday'] = strtotime($dob);
                 }
                 if (!empty($gender)) {
                     $_SESSION['gender'] = $gender;
                 }
                 $nickname = isset($sreg['nickname']) ? $sreg['nickname'] : null;
                 //customMail ('*****@*****.**', 'login test', print_r ($sreg, true));
                 // Check if this language exists:
                 if (isset($language)) {
                     $allLanguages = Neuron_Core_Text::getLanguages();
                     if (in_array($language, $allLanguages)) {
                         if (!isset($_COOKIE['user_language'])) {
                             $_SESSION['language'] = $language;
                         }
                         //setcookie ('user_language', $language, time () + COOKIE_LIFE, '/');
                     }
                 }
                 if (isset($nickname)) {
                     $_SESSION['openid_nickname'] = $nickname;
                 }
                 // Fetch the AX
                 $notify_url = null;
                 $profilebox_url = null;
                 $openid_userstats = null;
                 $ax = Auth_OpenID_AX_FetchResponse::fromSuccessResponse($response);
                 if ($ax) {
                     $ax_data = $ax->data;
                     $keyname = 'http://www.browser-games-hub.org/schema/openid/notify_url.xml';
                     $notify_url = isset($ax_data[$keyname]) ? $ax_data[$keyname] : array();
                     $keyname2 = 'http://www.browser-games-hub.org/schema/openid/profilebox_url.xml';
                     $profilebox_url = isset($ax_data[$keyname2]) ? $ax_data[$keyname2] : array();
                     $keyname3 = 'http://www.browser-games-hub.org/schema/openid/messagebundle_url.xml';
                     $messagebundle_url = isset($ax_data[$keyname3]) ? $ax_data[$keyname3] : array();
                     $keyname4 = 'http://www.browser-games-hub.org/schema/openid/container.xml';
                     $openid_container = isset($ax_data[$keyname4]) ? $ax_data[$keyname4] : array();
                     $keyname5 = 'http://www.browser-games-hub.org/schema/openid/fullscreen.xml';
                     $openid_fullscreen = isset($ax_data[$keyname5]) ? $ax_data[$keyname5] : array();
                     $keyname6 = 'http://www.browser-games-hub.org/schema/openid/userstats_url.xml';
                     $openid_userstats = isset($ax_data[$keyname6]) ? $ax_data[$keyname6] : array();
                     $keyname7 = 'http://www.browser-games-hub.org/schema/openid/hide_advertisement.xml';
                     $hide_advertisement = isset($ax_data[$keyname7]) ? $ax_data[$keyname7] : array();
                     $keyname8 = 'http://www.browser-games-hub.org/schema/openid/hide_advertisement.xml';
                     $hide_chat = isset($ax_data[$keyname8]) ? $ax_data[$keyname8] : array();
                     $notify_url = count($notify_url) > 0 ? $notify_url[0] : null;
                     $profilebox_url = count($profilebox_url) > 0 ? $profilebox_url[0] : null;
                     $messagebundle_url = count($messagebundle_url) > 0 ? $messagebundle_url[0] : null;
                     $openid_container = count($openid_container) > 0 ? $openid_container[0] : null;
                     $openid_fullscreen = count($openid_fullscreen) > 0 ? $openid_fullscreen[0] : null;
                     $openid_userstats = count($openid_userstats) > 0 ? $openid_userstats[0] : null;
                     $hide_advertisement = count($hide_advertisement) > 0 ? $hide_advertisement[0] : null;
                     $hide_chat = count($hide_chat) > 0 ? $hide_chat[0] : null;
                     $_SESSION['opensocial_messagebundle'] = $messagebundle_url;
                     $_SESSION['opensocial_container'] = $openid_container;
                     $_SESSION['fullscreen'] = $openid_fullscreen == 1;
                     $_SESSION['hide_advertisement'] = $hide_advertisement == 1;
                     $_SESSION['hide_chat'] = $hide_chat == 1;
                     $_SESSION['welcome_url'] = getAXValue($ax_data, 'http://www.browser-games-hub.org/schema/openid/welcome_url.xml');
                     $_SESSION['tracker_url'] = getAXValue($ax_data, 'http://www.browser-games-hub.org/schema/openid/tracker_url.xml');
                     // Load the tracker
                     if (isset($_SESSION['tracker_url'])) {
                         $_SESSION['tracker_html'] = @file_get_contents($_SESSION['tracker_url']);
                     }
                     if (isset($_SESSION['welcome_url'])) {
                         $_SESSION['welcome_html'] = @file_get_contents($_SESSION['welcome_url']);
                     }
                 }
                 // Fetch a fresh user ID
                 $db = Neuron_Core_Database::__getInstance();
                 $login = Neuron_Core_Login::__getInstance();
                 // See if there is an account available
                 $acc = $db->select('n_auth_openid', array('user_id'), "openid_url = '" . $db->escape($esc_identity) . "'");
                 $_SESSION['neuron_openid_identity'] = $esc_identity;
                 if (count($acc) == 1 && $acc[0]['user_id'] > 0) {
                     $id = $acc[0]['user_id'];
                     loginAndRedirect($acc[0]['user_id'], $email);
                 } else {
                     if (count($acc) == 0) {
                         // Create a new account
                         $db->insert('n_auth_openid', array('openid_url' => $esc_identity, 'user_id' => 0));
                     }
                     // Set a session key to make sure
                     // that the server still knows you
                     // when you hit submit.
                     $_SESSION['dolumar_openid_identity'] = $esc_identity;
                     $_SESSION['dolumar_openid_email'] = $email;
                     $url = ABSOLUTE_URL . 'dispatch.php?module=openid/register/&session_id=' . session_id();
                     header('Location: ' . $url);
                 }
                 // Update this ID
                 $db->update('n_auth_openid', array('notify_url' => $notify_url, 'profilebox_url' => $profilebox_url, 'userstats_url' => $openid_userstats), "openid_url = '" . $db->escape($esc_identity) . "'");
             }
         }
     }
 }
 //connect to database
 /* Set identity cookie */
 if ($_REQUEST['email']) {
     setcookie("user_openid", $_REQUEST['email'], time() + 3600 * 1000, '/');
 } else {
     setcookie("user_openid", $response->identity_url, time() + 3600 * 1000, '/');
 }
 //set cookie
 /* Get sreg resp or defaults */
 $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
 $sreg = $sreg_resp->contents();
 $fullname = explode(' ', mysql_real_escape_string(@$sreg['fullname'], $db));
 $email = @$sreg['email'] ? mysql_real_escape_string(@$sreg['email'], $db) : mysql_real_escape_string($_REQUEST['email'], $db);
 $nickname = @$sreg['nickname'] ? mysql_real_escape_string(@$sreg['nickname'], $db) : false;
 /* Augment with any AX response there may have been */
 $ax_resp = Auth_OpenID_AX_FetchResponse::fromSuccessResponse($response);
 if (($ax_email = $ax_resp->getSingle('http://axschema.org/contact/email')) && !is_a($ax_email, 'Auth_OpenID_AX_Error')) {
     $email = mysql_real_escape_string($ax_email, $db);
 }
 if (($ax_nickname = $ax_resp->getSingle('http://axschema.org/namePerson/friendly')) && !is_a($ax_nickname, 'Auth_OpenID_AX_Error')) {
     $nickname = mysql_real_escape_string($ax_nickname, $db);
 }
 if (($ax_fullname = $ax_resp->getSingle('http://axschema.org/namePerson')) && !is_a($ax_fullname, 'Auth_OpenID_AX_Error')) {
     $fullname = explode(' ', mysql_real_escape_string($ax_fullname, $db));
 }
 /* And with any hCard */
 if (!$email || !$nickname || !$photo) {
     $r = explode("\n", shell_exec("representative_hcard.rb '" . escapeshellcmd($response->identity_url) . "'"));
     if ($r[0]) {
         $nickname = mysql_real_escape_string($r[0], $db);
     }
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;
}
Example #15
0
 /**
  * Register an user that logged in with OpenID for the first time.
  * 
  * @param object $op_response object returned by Janrain 
  * Consumer::complete method.
  * @return mixed the user_id inserted or FALSE on error
  */
 public function openid_register($op_response)
 {
     $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($op_response);
     $ax_resp = Auth_OpenID_AX_FetchResponse::fromSuccessResponse($op_response);
     if ($ax_resp) {
         $ax_email = $ax_resp->get('http://axschema.org/contact/email');
         $ax_first_name = $ax_resp->get('http://axschema.org/namePerson/first');
         $ax_last_name = $ax_resp->get('http://axschema.org/namePerson/last');
         $ax_country = $ax_resp->get('http://axschema.org/contact/country');
     } else {
         $ax_email = '';
         $ax_first_name = '';
         $ax_last_name = '';
         $ax_country = '';
     }
     if ($sreg_resp) {
         $sreg_email = $sreg_resp->get('email', '');
         $sreg_fullname = $sreg_resp->get('fullname', '');
         $sreg_nickname = $sreg_resp->get('nickname', '');
         $sreg_country = $sreg_resp->get('country', '');
         $sreg_dob = $sreg_resp->get('dob', NULL);
     } else {
         $sreg_email = $sreg_fullname = $sreg_nickname = $sreg_country = '';
         $sreg_dob = NULL;
     }
     // E-mail
     if (empty($ax_email) || is_a($ax_email, 'Auth_OpenID_AX_Error')) {
         $data['email'] = $sreg_email;
     } else {
         $data['email'] = $ax_email[0];
     }
     $data['email'] = strtolower($data['email']);
     // First Name
     if (empty($ax_first_name) || is_a($ax_first_name, 'Auth_OpenID_AX_Error')) {
         $data['first_name'] = '';
     } else {
         $data['first_name'] = $ax_first_name[0];
     }
     // Sur Name
     if (empty($ax_last_name) || is_a($ax_last_name, 'Auth_OpenID_AX_Error')) {
         $data['last_name'] = '';
     } else {
         $data['last_name'] = $ax_last_name[0];
     }
     // First Name and Last Name
     if (empty($data['first_name']) || empty($data['last_name'])) {
         if ($sreg_fullname) {
             if (empty($data['first_name'])) {
                 $data['first_name'] = substr($sreg_fullname, 0, strrpos($sreg_fullname, ' '));
             }
             if (empty($data['last_name'])) {
                 $data['last_name'] = substr($sreg_fullname, strrpos($sreg_fullname, ' ') + 1);
             }
         }
     }
     // Username
     $data['username'] = $sreg_nickname;
     if (!$data['username']) {
         // Generate username from email
         if (!empty($data['email'])) {
             $data['username'] = substr($data['email'], 0, strpos($data['email'], '@'));
             $data['username'] = preg_replace(array('/[^a-z0-9\\._]*/'), array(''), $data['username']);
         } else {
             if (!empty($data['first_name']) || !empty($data['last_name'])) {
                 $data['username'] = $data['first_name'] . '_' . $data['last_name'];
             } else {
                 $data['username'] = $this->gen_username();
             }
         }
     }
     // Limit username to 24 characters because a prefix of 8 characters
     // will be added: 'autogen_'.
     $data['username'] = substr($data['username'], 0, 24);
     // Append a random character to the username each time it still exists.
     if ($this->get_userdata($data['username'])) {
         $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
         $len_chars = strlen($chars);
         $data['username'] .= '_';
         do {
             $data['username'] .= $chars[mt_rand(0, $len_chars - 1)];
         } while ($this->get_userdata($data['username']));
     }
     // Usernames autogenerated have 'autogen_' prefix and can be changed
     // by the user from the account section. After this process it cannot
     // be changed anymore.
     $data['username'] = '******' . $data['username'];
     // Country
     if (empty($ax_country) || is_a($ax_country, 'Auth_OpenID_AX_Error')) {
         $data['country'] = $sreg_country;
     } else {
         $data['country'] = $ax_country[0];
     }
     // Birth Date
     $data['birth_date'] = $sreg_dob;
     // OpenID
     $data['auth_src'] = 'openid';
     if (!$this->register($data, $op_response->getDisplayIdentifier())) {
         return FALSE;
     }
     $query = $this->db->query("SELECT id from `users`\n\t\t\tWHERE username = '******'username']}'");
     return $query->row()->id;
 }
Example #16
0
 /**
  * Returns null and sets a flash message on all errors.
  **/
 static function finishAuth()
 {
     $consumer = self::getConsumer();
     $return_to = self::getReturnTo();
     $response = $consumer->complete($return_to);
     if ($response->status == Auth_OpenID_CANCEL) {
         FlashMessage::add('Verificare anulată.');
         return null;
     } else {
         if ($response->status == Auth_OpenID_FAILURE) {
             FlashMessage::add('Verificarea a eșuat: ' . $response->message);
             return null;
         } else {
             if ($response->status == Auth_OpenID_SUCCESS) {
                 $result = array();
                 $result['identity'] = htmlentities($response->getDisplayIdentifier());
                 if ($response->endpoint->canonicalID) {
                     $escaped_canonicalID = htmlentities($response->endpoint->canonicalID);
                     // Ignored for now
                 }
                 $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
                 if ($sreg_resp) {
                     $sreg = $sreg_resp->contents();
                     if (isset($sreg['email'])) {
                         $result['email'] = $sreg['email'];
                     }
                     if (isset($sreg['nickname'])) {
                         $result['nickname'] = $sreg['nickname'];
                     }
                     if (isset($sreg['fullname'])) {
                         $result['fullname'] = $sreg['fullname'];
                     }
                 }
                 $ax_resp = Auth_OpenID_AX_FetchResponse::fromSuccessResponse($response);
                 if ($ax_resp) {
                     $data = $ax_resp->data;
                     if (isset($data['http://axschema.org/contact/email']) && count($data['http://axschema.org/contact/email'])) {
                         $result['email'] = $data['http://axschema.org/contact/email'][0];
                         // Take this over sreg
                     }
                     if (isset($data['http://axschema.org/namePerson']) && count($data['http://axschema.org/namePerson'])) {
                         $result['fullname'] = $data['http://axschema.org/namePerson'][0];
                     }
                     $names = array();
                     if (isset($data['http://axschema.org/namePerson/first']) && count($data['http://axschema.org/namePerson/first'])) {
                         $names[] = $data['http://axschema.org/namePerson/first'][0];
                     }
                     if (isset($data['http://axschema.org/namePerson/last']) && count($data['http://axschema.org/namePerson/last'])) {
                         $names[] = $data['http://axschema.org/namePerson/last'][0];
                     }
                     if (count($names)) {
                         $result['fullname'] = implode(' ', $names);
                     }
                 }
                 return $result;
             }
         }
     }
 }
	/**
	 * Called when returning from the authentication server
	 * Find the user with the given openid, if any or displays the "Choose name"
	 * form
	 */
	function finish() {
		global $wgOut, $wgUser, $wgOpenIDUseEmailAsNickname;

		wfSuppressWarnings();
		$consumer = $this->getConsumer();
		$response = $consumer->complete( $this->scriptUrl( 'Finish' ) );
		wfRestoreWarnings();

		if ( is_null( $response ) ) {
			wfDebug( "OpenID: aborting in auth because no response was recieved\n" );
			$wgOut->showErrorPage( 'openiderror', 'openiderrortext' );
			return;
		}

		switch ( $response->status ) {
		case Auth_OpenID_CANCEL:
			// This means the authentication was cancelled.
			$wgOut->showErrorPage( 'openidcancel', 'openidcanceltext' );
			break;
		case Auth_OpenID_FAILURE:
			wfDebug( "OpenID: error message '" . $response->message . "'\n" );
			$wgOut->showErrorPage( 'openidfailure', 'openidfailuretext',
				array( ( $response->message ) ? $response->message : '' ) );
			break;
		case Auth_OpenID_SUCCESS:
			// This means the authentication succeeded.
			wfSuppressWarnings();
			$openid = $response->identity_url;

			if ( !$this->canLogin( $openid ) ) {
				$wgOut->showErrorPage( 'openidpermission', 'openidpermissiontext' );
				return;
			}

			$sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse( $response );
			$sreg = $sreg_resp->contents();
			$ax_resp = Auth_OpenID_AX_FetchResponse::fromSuccessResponse( $response );
			$ax = $ax_resp->data;
			wfRestoreWarnings();

			if ( is_null( $openid ) ) {
				wfDebug( "OpenID: aborting in auth success because identity URL is missing\n" );
				$wgOut->showErrorPage( 'openiderror', 'openiderrortext' );
				return;
			}

			$user = self::getUserFromUrl( $openid );

			if ( $user instanceof User ) {
				$this->updateUser( $user, $sreg, $ax ); # update from server
				$wgUser = $user;
				$this->displaySuccessLogin( $openid );
			} else {
				// if we are hardcoding nickname, and a valid e-mail address was returned, create a user with this name
				if ( $wgOpenIDUseEmailAsNickname ) {
					$name = $this->getNameFromEmail( $openid, $sreg, $ax );
					if ( !empty( $name ) && $this->userNameOk( $name ) ) {
						$wgUser = $this->createUser( $openid, $sreg, $ax, $name );
						$this->displaySuccessLogin( $openid );
						return;
					}
				}

				$this->saveValues( $openid, $sreg, $ax );
				$this->chooseNameForm( $openid, $sreg, $ax );
				return;
			}
		}
	}
Example #18
0
     // 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
                 $ax = new Auth_OpenID_AX_FetchResponse();
                 $obj = $ax->fromSuccessResponse($response);
                 $openid_username = $obj->data['http://axschema.org/contact/email'][0];
             }
         }
     }
 }
 if (isset($_REQUEST['p1'])) {
     $p1 = $_REQUEST['p1'];
 } else {
     $p1 = $_REQUEST['camila_1'];
 }
 if (isset($_REQUEST['p2'])) {
     $p2 = $_REQUEST['p2'];
 } else {
     $p2 = $_REQUEST['camila_2'];
 }
Example #19
0
 public function getResponseAx()
 {
     $ax_resp = Auth_OpenID_AX_FetchResponse::fromSuccessResponse($this->response);
     return $ax_resp;
 }
Example #20
0
<?php

include "config.php";
include "authCommon.php";
$response = $openID->complete($baseURL . $basePath);
$identifier = $response->getDisplayIdentifier();
if ($response->status == Auth_OpenID_SUCCESS) {
    $axFetcher = new Auth_OpenID_AX_FetchResponse();
    $axList = $axFetcher->fromSuccessResponse($response);
    $emailSplit = explode("@", $axList->data["http://axschema.org/contact/email"][0]);
    if ($emailSplit[1] != $requiredEmailDomain) {
        die("You must login using your " . $requiredEmailDomain . " account.<br><a href='https://www.google.com/accounts/Logout'>Logout</a> before trying again.");
    }
    if (intval($emailSplit[0]) != 0) {
        die("Students may not access this system! <a href='https://www.google.com/accounts/Logout'>Logout</a>");
    }
    $_SESSION['loggedIn'] = true;
    $_SESSION['email'] = $axList->data["http://axschema.org/contact/email"][0];
    header("Location: index.php");
} else {
    echo "OpenID auth failed!<br><br>";
    print_r($response);
}
            //display pape policy return data if available
            $response_pape = Auth_OpenID_PAPE_Response::fromSuccessResponse($response);
            if ($response_pape) {
                //pape policies affected by authentication
                if ($response_pape->auth_policies) {
                    $response_state .= "<br />PAPE returned policies which affected the authentication:";
                    foreach ($response_pape->auth_policies as $uri) {
                        $response_state .= '- ' . htmlentities($uri);
                    }
                }
                //server authentication age
                if ($response_pape->auth_age) {
                    $response_state .= "<br />PAPE returned server authentication age with the value: " . htmlentities($response_pape->auth_age);
                }
                //nist authentication level
                if ($response_pape->nist_auth_level) {
                    $response_state .= "<br />PAPE returned server NIST auth level with the value: " . htmlentities($response_pape->nist_auth_level);
                }
            }
            //get attribute exchange return values
            $response_ax = new Auth_OpenID_AX_FetchResponse();
            $ax_return = $response_ax->fromSuccessResponse($response);
            echo "<h1>AX</h1>";
            var_dump($ax_return);
            foreach ($ax_return->data as $item => $value) {
                $response_state .= "<br />AX returned <b>{$item}</b> with the value: <b>{$value[0]}</b>";
            }
        }
    }
}
print $response_state;
Example #22
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;
}
 private function getUserProfileInfo($response)
 {
     if (Auth_OpenID_supportsSReg($response->endpoint)) {
         $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
         $sreg = $sreg_resp->contents();
         $email = @$sreg['email'];
         $full_name = @$sreg['fullname'];
     } else {
         //AX
         // Get registration informations
         $ax = new Auth_OpenID_AX_FetchResponse();
         $obj = $ax->fromSuccessResponse($response);
         $email = $obj->data["http://axschema.org/contact/email"][0];
         if (isset($obj->data["http://axschema.org/namePerson/first"])) {
             $full_name = $obj->data["http://axschema.org/namePerson/first"][0] . ' ' . $obj->data["http://axschema.org/namePerson/last"][0];
         } else {
             $full_name = $obj->data["http://axschema.org/namePerson"][0];
         }
     }
     return array($email, $full_name);
 }
Example #24
0
 function check()
 {
     $this->config->load('openid');
     $this->load->helper('gfx');
     $this->openid->set_request_to(site_url('auth/check'));
     $response = $this->openid->getResponse();
     switch ($response->status) {
         case Auth_OpenID_CANCEL:
             flashdata_message('auth_login_canceled', 'highlight', 'info');
             header('Location: ' . base_url());
             break;
         case Auth_OpenID_FAILURE:
             flashdata_message('auth_login_failed');
             header('Location: ' . base_url());
             break;
             //case Auth_OpenID_SETUP_NEEDED:	//Only happens in checkid_immediate mode
             //	flashdata_message('Auth_OpenID_SETUP_NEEDED');
             //	header('Location: ' . base_url());
             //	break;
         //case Auth_OpenID_SETUP_NEEDED:	//Only happens in checkid_immediate mode
         //	flashdata_message('Auth_OpenID_SETUP_NEEDED');
         //	header('Location: ' . base_url());
         //	break;
         case Auth_OpenID_SUCCESS:
             $open_id = $response->getDisplayIdentifier();
             $this->load->database();
             $user = $this->db->get_where('users', array('login' => $open_id));
             $sreg = Auth_OpenID_SRegResponse::fromSuccessResponse($response)->contents();
             $ax_response = Auth_OpenID_AX_FetchResponse::fromSuccessResponse($response);
             if ($ax_response) {
                 $ax = $ax_response->data;
             } else {
                 $ax = array();
             }
             if ($user->num_rows() !== 0) {
                 /* User exists */
                 $data = $user->row_array();
                 flashdata_message('auth_login', 'highlight', 'info');
                 if (!$data['email']) {
                     if (isset($sreg['email'])) {
                         $data['email'] = $sreg['email'];
                         $this->db->update('users', array('email' => $sreg['email']), array('id' => $data['id']));
                     } elseif (isset($ax['http://axschema.org/contact/email'])) {
                         $data['email'] = $ax['http://axschema.org/contact/email'][0];
                         $this->db->update('users', array('email' => $ax['http://axschema.org/contact/email'][0]), array('id' => $data['id']));
                     }
                 }
             } else {
                 $this->load->config('gfx');
                 if ($this->config->item('gfx_require_pre_authorization')) {
                     header('Location: ' . site_url('about/closetest?claimed_id=' . urlencode($open_id)));
                     return;
                 }
                 /* Create new user */
                 flashdata_message('auth_login_new', 'highlight', 'info');
                 $data = array('login' => $open_id, 'name' => '__temp__' . md5($open_id . time()), 'title' => '', 'admin' => 'N', 'avatar' => '', 'email' => '', 'bio' => '', 'web' => '', 'blog' => '', 'blog_rss' => '', 'forum_username' => '', 'count' => 1, 'visited' => 0);
                 if (isset($sreg['fullname'])) {
                     $data['title'] = $sreg['fullname'];
                 } elseif (isset($sreg['nickname'])) {
                     $data['title'] = $sreg['nickname'];
                 } elseif (isset($ax['http://axschema.org/namePerson/first'])) {
                     $data['title'] = $ax['http://axschema.org/namePerson/first'][0];
                 }
                 if (isset($sreg['email'])) {
                     $data['avatar'] = '(gravatar)';
                     $data['email'] = $sreg['email'];
                 } elseif (isset($ax['http://axschema.org/contact/email'])) {
                     $data['avatar'] = '(gravatar)';
                     $data['email'] = $ax['http://axschema.org/contact/email'][0];
                 }
                 if (preg_match('/myid\\.tw\\/$/', $data['login'])) {
                     $data['avatar'] = '(myidtw)';
                 }
                 $this->db->insert('users', $data);
                 $data['id'] = $this->db->insert_id();
                 $this->db->insert('u2g', array('user_id' => $data['id'], 'group_id' => '1', 'order' => '1'));
             }
             session_data_set(array('id' => $data['id'], 'name' => $data['name'], 'admin' => $data['admin'], 'hide_announcement' => ''), false);
             header('Location: ' . site_url('editor'));
     }
     if (isset($_COOKIE[session_name()])) {
         setcookie(session_name(), '', 0, '/');
     }
     session_destroy();
 }
Example #25
0
 /**
  * Process an authentication response.
  *
  * @param array &$state  The state array.
  */
 public function postAuth(array &$state)
 {
     $consumer = $this->getConsumer($state);
     $return_to = SimpleSAML_Utilities::selfURL();
     // Complete the authentication process using the server's
     // response.
     $response = $consumer->complete($return_to);
     // Check the response status.
     if ($response->status == Auth_OpenID_CANCEL) {
         // This means the authentication was cancelled.
         throw new SimpleSAML_Error_UserAborted();
     } else {
         if ($response->status == Auth_OpenID_FAILURE) {
             // Authentication failed; display the error message.
             throw new SimpleSAML_Error_AuthSource($this->authId, 'Authentication failed: ' . var_export($response->message, TRUE));
         } else {
             if ($response->status != Auth_OpenID_SUCCESS) {
                 throw new SimpleSAML_Error_AuthSource($this->authId, 'General error. Try again.');
             }
         }
     }
     // This means the authentication succeeded; extract the
     // identity URL and Simple Registration data (if it was
     // returned).
     $openid = $response->identity_url;
     $attributes = array('openid' => array($openid));
     $attributes['openid.server_url'] = array($response->endpoint->server_url);
     if ($response->endpoint->canonicalID) {
         $attributes['openid.canonicalID'] = array($response->endpoint->canonicalID);
     }
     if ($response->endpoint->local_id) {
         $attributes['openid.local_id'] = array($response->endpoint->local_id);
     }
     $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response, $this->validateSReg);
     $sregresponse = $sreg_resp->contents();
     if (is_array($sregresponse) && count($sregresponse) > 0) {
         $attributes['openid.sregkeys'] = array_keys($sregresponse);
         foreach ($sregresponse as $sregkey => $sregvalue) {
             $attributes['openid.sreg.' . $sregkey] = array($sregvalue);
         }
     }
     // Get AX response information
     $ax = new Auth_OpenID_AX_FetchResponse();
     $ax_resp = $ax->fromSuccessResponse($response);
     if ($ax_resp instanceof Auth_OpenID_AX_FetchResponse && !empty($ax_resp->data)) {
         $axresponse = $ax_resp->data;
         $attributes['openid.axkeys'] = array_keys($axresponse);
         foreach ($axresponse as $axkey => $axvalue) {
             if (preg_match("/^\\w+:/", $axkey)) {
                 $attributes[$axkey] = is_array($axvalue) ? $axvalue : array($axvalue);
             } else {
                 SimpleSAML_Logger::warning('Invalid attribute name in AX response: ' . var_export($axkey, TRUE));
             }
         }
     }
     SimpleSAML_Logger::debug('OpenID Returned Attributes: ' . implode(", ", array_keys($attributes)));
     $state['Attributes'] = $attributes;
     SimpleSAML_Auth_Source::completeAuth($state);
 }
Example #26
0
/**
 * Retrieve user data from OpenID Attribute Exchange.
 *
 * @param string $identity_url OpenID to get user data about
 * @param reference $data reference to user data array
 * @see get_user_data
 */
function openid_get_user_data_ax($data, $identity_url) {
	set_include_path( dirname(__FILE__) . PATH_SEPARATOR . get_include_path() );
	require_once('Auth/OpenID/AX.php');
	restore_include_path();

	$response = openid_response();
	$ax = Auth_OpenID_AX_FetchResponse::fromSuccessResponse($response);

	if (!$ax) return $data;

	$email = $ax->getSingle('http://axschema.org/contact/email');
	if ($email && !is_a($email, 'Auth_OpenID_AX_Error')) {
		$data['user_email'] = $email;
	}

	$nickname = $ax->getSingle('http://axschema.org/namePerson/friendly');
	if ($nickname && !is_a($nickname, 'Auth_OpenID_AX_Error')) {
		$data['nickname'] = $ax->getSingle('http://axschema.org/namePerson/friendly');
		$data['user_nicename'] = $ax->getSingle('http://axschema.org/namePerson/friendly');
		$data['display_name'] = $ax->getSingle('http://axschema.org/namePerson/friendly');
	}

	$fullname = $ax->getSingle('http://axschema.org/namePerson');
	if ($fullname && !is_a($fullname, 'Auth_OpenID_AX_Error')) {
		$namechunks = explode( ' ', $fullname, 2 );
		if( isset($namechunks[0]) ) $data['first_name'] = $namechunks[0];
		if( isset($namechunks[1]) ) $data['last_name'] = $namechunks[1];
		$data['display_name'] = $fullname;
	}

	return $data;
}
Example #27
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;
 }
function run()
{
    $consumer = getConsumer();
    // 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 = gettext('Verification cancelled.');
    } else {
        if ($response->status == Auth_OpenID_FAILURE) {
            // Authentication failed; display the error message.
            $msg = sprintf(gettext("OpenID authentication failed: %s"), $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(gettext('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 . ') ';
                }
                $email = $name = NULL;
                $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
                $sreg = $sreg_resp->contents();
                if ($sreg) {
                    if (@$sreg['email']) {
                        $email = trim($sreg['email']);
                    }
                    if (@$sreg['nickname']) {
                        $name = $sreg['nickname'];
                    }
                    if (@$sreg['fullname']) {
                        $name = $sreg['fullname'];
                    }
                }
                $ax_resp = Auth_OpenID_AX_FetchResponse::fromSuccessResponse($response);
                if ($ax_resp) {
                    $arr_ax_resp = get_object_vars($ax_resp);
                    $arr_ax_data = $arr_ax_resp['data'];
                    if (empty($email) && isset($arr_ax_data["http://axschema.org/contact/email"]) && count($arr_ax_data["http://axschema.org/contact/email"]) > 0) {
                        $email = $arr_ax_data["http://axschema.org/contact/email"][0];
                    }
                    if (empty($name) && isset($arr_ax_data["http://axschema.org/namePerson"]) && count($arr_ax_data["http://axschema.org/namePerson"]) > 0) {
                        $name = $arr_ax_data["http://axschema.org/namePerson"][0];
                    }
                    if (empty($name)) {
                        $name_first = '';
                        $name_middle = '';
                        $name_last = '';
                        if (isset($arr_ax_data["http://axschema.org/namePerson/first"]) && count($arr_ax_data["http://axschema.org/namePerson/first"]) > 0) {
                            $name_first = $arr_ax_data["http://axschema.org/namePerson/first"][0];
                        }
                        if (isset($arr_ax_data["http://axschema.org/namePerson/middle"]) && count($arr_ax_data["http://axschema.org/namePerson/middle"]) > 0) {
                            $name_middle = $arr_ax_data["http://axschema.org/namePerson/middle"][0];
                        }
                        if (isset($arr_ax_data["http://axschema.org/namePerson/last"]) && count($arr_ax_data["http://axschema.org/namePerson/last"]) > 0) {
                            $name_last = $arr_ax_data["http://axschema.org/namePerson/last"][0];
                        }
                        $fullname = trim(trim(trim($name_first) . ' ' . $name_middle) . ' ' . $name_last);
                        if (!empty($fullname)) {
                            $name = $fullname;
                        }
                    }
                    if (empty($name) && isset($arr_ax_data["http://axschema.org/namePerson/friendly"]) && count($arr_ax_data["http://axschema.org/namePerson/friendly"]) > 0) {
                        $name = $arr_ax_data["http://axschema.org/namePerson/friendly"][0];
                    }
                }
                $userid = trim(str_replace(array('http://', 'https://'), '', $openid), '/');
                //	always remove the protocol
                $pattern = @$_SESSION['OpenID_cleaner_pattern'];
                if ($pattern) {
                    if (preg_match($pattern, $userid, $matches)) {
                        $userid = $matches[1];
                    }
                }
                $provider = @$_SESSION['provider'];
                if (strlen($userid) + strlen($provider) > 63) {
                    $userid = sha1($userid);
                }
                if ($provider) {
                    $userid = $provider . ':' . $userid;
                }
                $redirect = @$_SESSION['OpenID_redirect'];
                $success .= logonFederatedCredentials($userid, $email, $name, $redirect);
            }
        }
    }
    return $success;
}
Example #29
0
 function test_fromSuccessResponse()
 {
     $name = "ziggy";
     $value = "stardust";
     $uri = "http://david.bowie.name/";
     $args = array('mode' => 'id_res', 'ns' => Auth_OpenID_OPENID2_NS, 'ns.ax' => Auth_OpenID_AX_NS_URI, 'ax.mode' => 'fetch_response', 'ax.update_url' => 'http://example.com/realm/update_path', 'ax.type.' . $name => $uri, 'ax.count.' . $name => '1', 'ax.value.' . $name . '.1' => $value);
     $sf = array();
     foreach (array_keys($args) as $k) {
         array_push($sf, $k);
     }
     $msg = Auth_OpenID_Message::fromOpenIDArgs($args);
     $e = new FauxEndpoint();
     $resp = new Auth_OpenID_SuccessResponse($e, $msg, $sf);
     $ax_resp = Auth_OpenID_AX_FetchResponse::fromSuccessResponse($resp, false);
     $this->assertFalse($ax_resp === null);
     $this->assertTrue(is_a($ax_resp, 'Auth_OpenID_AX_FetchResponse'));
     $values = $ax_resp->get($uri);
     $this->assertEquals(array($value), $values);
 }
 protected function appendMemberInformationFromProvider($member)
 {
     $ax = Auth_OpenID_AX_FetchResponse::fromSuccessResponse($this->getResponse());
     if ($ax) {
         $axExchange = new opOpenIDProfileExchange('ax', $member);
         $axExchange->setData($ax->data);
     }
     $sreg = Auth_OpenID_SRegResponse::fromSuccessResponse($this->getResponse());
     if ($sreg) {
         $sregExchange = new opOpenIDProfileExchange('sreg', $member);
         $sregExchange->setData($sreg->contents());
     }
     return $member;
 }