I have a website running on a less well known CMS called Ushahidi. There is built in OpenID functionality where folk can login with Facebook or Google.
I don't have enough dev skills to understand whats happening here but, it appears that I've almost got it working, except, I'm receiving the following error when trying to test it out on my own Google login:
An error was detected which prevented the loading of this page. If
this problem persists, please contact the website administrator.
application/controllers/login.php [503]: Undefined variable: user
I suspect, but am not sure, that defining a variable is easy enough but since I lack the knowledge I hoped to ask someone on here if they could see where I need to define the variable. Line 503 is part of a larger code block of about 100 lines, I know that it's not good practice to post larger chunks of code on here but I'm really unsure of what is and is not relevant. So forgive me. I have highlighted in bold where line 503 is. Can anyone point out what I must do here?
// OpenID Post
try
{
$openid = new OpenID;
// Retrieve the Name (if available) and Email
$openid->required = array("namePerson", "contact/email");
if( ! $openid->mode)
{
if(isset($_POST["openid_identifier"]))
{
$openid->identity = $_POST["openid_identifier"];
header("Location: " . $openid->authUrl());
}
}
elseif ($openid->mode == "cancel")
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = "You have canceled authentication!";
}
else
{
if ($openid->validate())
{
// Does User Exist?
$openid_user = ORM::factory("openid")
->where("openid", $openid->identity)
->find();
if ($openid_user->loaded AND $openid_user->user)
{
// First log all other sessions out
$auth->logout();
// Initiate Ushahidi side login + AutoLogin
$auth->force_login($openid_user->user->username);
// Exists Redirect to Dashboard
**(THIS IS LINE 503)** url::redirect($user->dashboard());
}
else
{
// Does this openid have the required email??
$new_openid = $openid->getAttributes();
if ( ! isset($new_openid["contact/email"]) OR
empty($new_openid["contact/email"]))
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = $openid->identity . " has not been logged in. No Email Address Found.";
}
else
{
// Create new User and save OpenID
$user = ORM::factory("user");
// But first... does this email address already exist
// in the system?
if ($user->email_exists($new_openid["contact/email"]))
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = $new_openid["contact/email"] . " is already registered in our system.";
}
else
{
$username = "user".time(); // Random User Name from TimeStamp - can be changed later
$password = text::random("alnum", 16); // Create Random Strong Password
// Name Available?
$user->name = (isset($new_openid["namePerson"]) AND ! empty($new_openid["namePerson"]))
? $new_openid["namePerson"]
: $username;
$user->username = $username;
$user->password = $password;
$user->email = $new_openid["contact/email"];
// Add New Roles
$user->add(ORM::factory('role', 'login'));
$user->add(ORM::factory('role', 'member'));
$user->save();
// Save OpenID and Association
$openid_user->user_id = $user->id;
$openid_user->openid = $openid->identity;
$openid_user->openid_email = $new_openid["contact/email"];
$openid_user->openid_server = $openid->server;
$openid_user->openid_date = date("Y-m-d H:i:s");
$openid_user->save();
// Initiate Ushahidi side login + AutoLogin
$auth->login($username, $password, TRUE);
// Redirect to Dashboard
url::redirect($user->dashboard());
}
}
}
}
else
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = $openid->identity . "has not been logged in.";
}
}
}
catch (ErrorException $e)
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = $e->getMessage();
}
The problem is that the code is using $user several lines before it's actually defined. It might be a typo, though - maybe $openid_user->user->dashboard() at line 503 might work, though it's a WAG.
Related
During my create user process I make a few queries to various database's to get the new user setup. This script has been working fine for about a year and a half, but now something is off.
So the first thing I do is I check to see if a user exists with the credentials being submitted. I've thoroughly tested the check and I'm confident my issue isn't there.
If that check comes back false then the script continues to create the user.
public function registerUser() {
parse_str($_SERVER['QUERY_STRING'], $data);
$data = (object) $data;
$check = json_decode($this->checkUserExists($data->email));
if ($check->res) {
$res = new \stdClass();
$res->res = false;
$res->user_status = $check->user_status;
$res->msg = 'User exists.';
echo json_encode($res);
}
if (!$check->res) {
$this->createUser($data);
}
}
The problem arises after all the queries have been completed, the script does not seem to want to run the if statement at the bottom. I marked it with comment characters so it's easier to find, but I included the entire function for clarity, maybe I'm doing something that is causing the issue.
I tried invoking an error manually at various points during the script. And I am able to trigger an error all the way down to the bottom of the script.
private function createUser($data) {
$Crypt = new CryptController();
$AuthSelect = new AuthController();
$Time = new TimeController();
$remote_address = new RemoteAddressController();
$Session = new SessionController();
$AuthInsert = new AuthModel_Insert();
$hashed_password = $Crypt->create_hash($data->password);
$data->password = '';
$AuthData = json_decode($AuthSelect->getAuth());
$system_auth_id = $AuthData->system_auth_id;
$user_id = $Crypt->get_uuid();
$user_auth_id = $Crypt->get_uuid();
$user_createddate = $Time->time();
$user_updateddate = $Time->time();
$user_lastupdateddate = $Time->time();
$agent_ip = $remote_address->getIpAddress();
$userData = $this->createUserObject(
$user_id,
$user_auth_id,
$system_auth_id,
$hashed_password,
$user_createddate,
$user_updateddate,
$user_lastupdateddate,
$data
);
$agentData = $this->createAgentObject(
$user_id,
$agent_ip,
$data
);
//////////////////////////////////////////
$create_user = $AuthInsert->createNewUser(
$userData
);
$create_user_agent = $this->setUserAgent(
$agentData
);
$sessionKeyData = new \stdClass();
$sessionKeyData->user_id = $user_id;
$sessionKeyData->user_auth_id = $user_auth_id;
$sessionKeyData->system_auth_id = $system_auth_id;
$sessionKeyData->agent_id = $create_user_agent->agent->agent_id;
$set_session_key = $Session->setSessionKey(
$sessionKeyData
);
$send_activation_email = $this->createUserActivation(
$userData
);
if (
$create_user &&
$create_user_agent->res &&
$set_session_key->res &&
$send_activation_email->res) {
$res = new \stdClass();
$res->res = true;
$res->msg = 'New user successfully created.';
echo json_encode($res);
} else {
$res = new \stdClass();
$res->res = false;
$res->msg = 'Error: User creation process incomplete.';
echo json_encode($res);
}
//////////////////////////////////////////
trigger_error("Invoked Error: ",E_USER_ERROR);
}
The queries themselves go through just fine, all the tables are populated just fine. The issue is that after that happens the script doesn't finish. It seems to end the createUser() function and return to the registerUser() function at which point the user will exist so it will return false and echo that back to the client.
In my testing it seems my issue might be at the bottom with that if statement. But I've tested each of those queries individually and they do return the desired booleans to get the true condition. But, even the false condition doesn't go through which should return 'Error: User creation process incomplete.'. That doesn't happen either.
I'm hoping someone sees something I'm missing because I've been stuck on this problem for too long. I appreciate any guidance that might lead me to an answer. Thanks in advance.
Just for clarification the message I'm getting back is $res->msg = 'User exists.'; which comes from registeruser(). The message I'm expecting back is $res->msg = 'New user successfully created.'; which should come from createUser().
I'm trying to add microsoft login to an application I'm developing, but I'm repeatedly getting this error which I'm unable to understand.
The URL is :-
https://login.live.com/err.srf?lc=1033#error=invalid_request&error_description=The%20provided%20value%20for%20the%20input%20parameter%20'redirect_uri'%20is%20not%20valid.%20The%20expected%20value%20is%20'https://login.live.com/oauth20_desktop.srf'%20or%20a%20URL%20which%20matches%20the%20redirect%20URI%20registered%20for%20this%20client%20application.&state=1403724714-562028
Code
<?php
require('lib/http.php');
require('lib/oauth_client.php');
$client = new oauth_client_class;
$client->server = 'Microsoft';
//$client->redirect_uri = 'http://'.$_SERVER['HTTP_HOST'].
//dirname(strtok($_SERVER['REQUEST_URI'],'?')).'/login.php';
$client->redirect_uri='http://novostack.com/mscr/login.php';
$client->client_id = 'clietidhere'; $application_line = __LINE__;
$client->client_secret = 'secrethere';
if(strlen($client->client_id) == 0
|| strlen($client->client_secret) == 0)
die('Please go to Microsoft Live Connect Developer Center page '.
'https://manage.dev.live.com/AddApplication.aspx and create a new'.
'application, and in the line '.$application_line.
' set the client_id to Client ID and client_secret with Client secret. '.
'The callback URL must be '.$client->redirect_uri.' but make sure '.
'the domain is valid and can be resolved by a public DNS.');
/* API permissions
*/
$client->scope = 'wl.basic wl.emails wl.birthday';
if(($success = $client->Initialize()))
{
if(($success = $client->Process()))
{
if(strlen($client->authorization_error))
{
$client->error = $client->authorization_error;
$success = false;
}
elseif(strlen($client->access_token))
{
$success = $client->CallAPI(
'https://apis.live.net/v5.0/me',
'GET', array(), array('FailOnAccessError'=>true), $user);
}
}
$success = $client->Finalize($success);
}
if($client->exit)
exit;
if($success)
{
session_start();
$_SESSION['userdata']=$user;
header("location: index.php");
}
else
{
echo 'Error:'.HtmlSpecialChars($client->error);
}
?>
Here's a link to check online :- www.novostack.com/mcr/
I do have the correct settings in my developer console.
What seems to be the problem here?
All suggestions are appreciated.
Make sure that the "Root domain" under APP Settings is equal to your caller domain (www.novostack.com).
I am in a complicated situation. I have two projects. One is designed using Yii Framework, another one includes only pure PHP code (I mean no framework). What I want to do is that, when user logged in the project, he/she should be logged in Yii project either. I tried to set session_id in Yii project, but it didn't work. I am redirecting user by using php header function in order to Yii project in order to let user log in. Here are the codes:
PHP project:
if (isset($_POST['giris-yap'])) {
$_POST['eposta'] = $this->cstring->validEmail($_POST['eposta']);
$_POST['sifre'] = md5($_POST['sifre']);
if ($_POST['eposta'] != '' && $_POST['sifre'] != '') {
$params = array(
'e-posta' => $_POST['eposta'],
'sifre' => $_POST['sifre']
);
$sonuc = $this->loginKendim($params);
if ($sonuc) {
$_SESSION['_utmkendim'] = md5('üyegirişyaptı'.$_POST['eposta']);
//mya user authentication
if($_SERVER["REMOTE_ADDR"] = "88.248.192.175")
{
header("Location: https://mya.genel.com/?sessionId=" . $_COOKIE["PHPSESSID"]);
exit;
}
//end of mya user authentication
header("Location: https://www.kendim.com/panel");
exit;
}
else
$this->_kayithata = 1;
}
else
$this->_kayithata = 1;
}
Yii Project:
public function beforeAction($action) {
if(isset($_GET["sessionId"]) && $_GET["sessionId"] != "")
{
Yii::app()->session->setSessionID($_GET["sessionId"]);
session_id($_GET["sessionId"]);
header("Location: https://www.kendim.com/panel");
exit;
}
# mya wl-api den gelen kullanıcıyı login edelim.
if(isset($_GET['_MYAU'])){
$_useruniqueid = Yii::app()->CString->CleanSTR($_GET['_MYAU']);
$userlogin = UserslogLogin::model()->findByAttributes(array('login_uniqueid' => $_useruniqueid ));
if($userlogin){
$user = UsersAccounts::model()->findByPk($userlogin->user_id, array('select' => 'user_id, user_name, user_email, user_pass'));
$identity = new UserIdentity($user->user_email, $user->user_pass);
$identity->id = $user->user_id;
$identity->name = $user->user_name;
$identity->username = $user->user_email;
$duration = 3600*24; //$this->rememberMe ? 3600*24*30 : 1800; // 30 days
Yii::app()->user->login($identity, $duration);
Yii::app()->request->redirect('/anasayfa');
Yii::app()->end();
}else{
$action = 'actionError';
$this->$action();
Yii::app()->end();
}
}
# kullanıcı login değilse indexe yönlendir
if(Yii::app()->user->isGuest){
$action = 'actionIndex';
$this->$action();
Yii::app()->end();
}else{
$this->getuser = UsersAccounts::user();
Controller::$projectModel = Projects::loadModel($this->getuser->project_code);
}
return parent::beforeAction($action);
}
I don't think the problem was the framework. The problem are the domains, as DaSourcerer guessed.
Take a look at this previous post:
Preserving session variables across different domains
Ok I found the solution. I've forgotten using session_start();. Problem is solved. I can transfer session between domains right now.
I'm writing a code that allows users to place a like box on their page, so I need to make sure that the page is valid for a like box as personal pages won't work. I'm currently using the facebook.php file, but when I use the following code:
// $fbexist is the page username in this case "clubcoreme"
function CheckFB($fbexist) {
require_once("include/facebook.php");
$config = array();
$config['appId'] = 'APP_ID';
$config['secret'] = 'APP_SECRET';
$facebook = new Facebook($config);
try {
$facebook->api($fbexist);
if (!$facebook->api($fbexist)) {
$personal = "No";
} else {
$personal = "Yes";
}
} catch(FacebookApiException $e) {
$checked = array(false, $personal);
return $checked;
}
$checked = array(true, $personal);
return $checked;
}
it always comes back as $personal = "No" which should mean that it isn't valid for a like box. But I know for a fact that I can use clubcoreme for a like box. And when I try "JohnnieWalkerLebanon" instead of clubcoreme it works. What am I doing wrong? and is there a better way to do it?
Thank you in advance,
Robert
I start saying that I HATE OpenID, because it's poorly implemented/documented.
I'm trying to use "openid-php-openid-2.2.2-24". Here the source code: https://github.com/openid/php-openid
When I try to use the authentication example, it returns to me:
"You have successfully verified https://www.google.com/accounts/o8/id?id=[...] as your identity.
No PAPE response was sent by the provider."
but there's no shadow of email, nickname or fullname of google openid login data.
While reading the file ("/openid/examples/consumer/finish_auth.php"), I note that SREG variables have to be printed between the "You have successfully verified" and "No PAPE response" messages, but they don't:
$success = sprintf('You have successfully verified ' .
'%s 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']).
"'.";
$_SESSION['nickname'] = escape($sreg['nickname']);
}
if (#$sreg['fullname']) {
$success .= " Your fullname is '".escape($sreg['fullname']).
"'.";
}
$pape_resp = Auth_OpenID_PAPE_Response::fromSuccessResponse($response);
if ($pape_resp) {
[...]
} else {
$success .= "<p>No PAPE response was sent by the provider.</p>";
}
I've tried to print the content of $sreg['email'], $sreg['nickname'] and $sreg['fullname'], but they return all blank contents (null/empty values).
I need to retrieve the email address of the account which users use to login in..
Dante
To get the question off the unanswered list, I post dante's answer here as answer:
I solved my problem.
Example usage of AX in PHP OpenID: Example usage of AX in PHP OpenID
After 2 days of research, I've just now found the answer ("but Google uses AX (attribute exchange) instead of SReg for additional data"). Why Google must always be so different?
However, the code in that stackoverflow answer page doesn't work for me (my hosting server returns 500 internal server error code).
So, I post here "my code" (it's so rough):
oid_ax_common.php
<?php
// Circumnavigate bugs in the GMP math library that can be result in signature
// validation errors
define('Auth_OpenID_BUGGY_GMP', true);
$path_extra = dirname(dirname(dirname(__FILE__)));
$path = ini_get('include_path');
$path = $path_extra . PATH_SEPARATOR . $path;
ini_set('include_path', $path);
function displayError($message) {
$error = $message;
include './index.php';
exit(0);
}
function doIncludes() {
/**
* Require the OpenID consumer code.
*/
require_once "Auth/OpenID/Consumer.php";
/**
* Require the "file store" module, which we'll need to store
* OpenID information.
*/
require_once "Auth/OpenID/FileStore.php";
/**
* Require the Simple Registration extension API.
*/
//require_once "Auth/OpenID/SReg.php";
require_once "Auth/OpenID/AX.php";
/**
* Require the PAPE extension module.
*/
require_once "Auth/OpenID/PAPE.php";
}
doIncludes();
global $pape_policy_uris;
$pape_policy_uris = array(
PAPE_AUTH_MULTI_FACTOR_PHYSICAL,
PAPE_AUTH_MULTI_FACTOR,
PAPE_AUTH_PHISHING_RESISTANT
);
function &getStore() {
/**
* This is where the example will store its OpenID information.
* You should change this path if you want the example store to be
* created elsewhere. After you're done playing with the example
* script, you'll have to remove this directory manually.
*/
$store_path = null;
if (function_exists('sys_get_temp_dir')) {
$store_path = sys_get_temp_dir();
}
else {
if (strpos(PHP_OS, 'WIN') === 0) {
$store_path = $_ENV['TMP'];
if (!isset($store_path)) {
$dir = 'C:\Windows\Temp';
}
}
else {
$store_path = #$_ENV['TMPDIR'];
if (!isset($store_path)) {
$store_path = '/tmp';
}
}
}
$store_path = './tmp/';
$store_path .= DIRECTORY_SEPARATOR . '_php_consumer_test';
if (!file_exists($store_path) &&
!mkdir($store_path)) {
print "Could not create the FileStore directory '$store_path'. ".
" Please check the effective permissions.";
exit(0);
}
$r = new Auth_OpenID_FileStore($store_path);
return $r;
}
function &getConsumer() {
/**
* Create a consumer object using the store object created
* earlier.
*/
$store = getStore();
$r = new Auth_OpenID_Consumer($store);
return $r;
}
function getScheme() {
$scheme = 'http';
if (isset($_SERVER['HTTPS']) and $_SERVER['HTTPS'] == 'on') {
$scheme .= 's';
}
return $scheme;
}
function getReturnTo() {
return sprintf("%s://%s:%s%s/oid_ax_receive.php",
getScheme(), $_SERVER['SERVER_NAME'],
$_SERVER['SERVER_PORT'],
dirname($_SERVER['PHP_SELF']));
}
function getTrustRoot() {
return sprintf("%s://%s:%s%s/",
getScheme(), $_SERVER['SERVER_NAME'],
$_SERVER['SERVER_PORT'],
dirname($_SERVER['PHP_SELF']));
}
?>
oid_ax_send.php
<?php
require_once "oid_ax_common.php";
// Starts session (needed for YADIS)
session_start();
function getOpenIDURL() {
// Render a default page if we got a submission without an openid
// value.
if (empty($_GET['openid_identifier'])) {
$error = "Expected an OpenID URL.";
include './index.php';
exit(0);
}
return $_GET['openid_identifier'];
}
function run() {
// https://www.google.com/accounts/o8/id
// $openid = 'http://openid-provider.appspot.com/';
$openid = 'https://www.google.com/accounts/o8/id';
// $openid .= getOpenIDURL();
$consumer = getConsumer();
// Begin the OpenID authentication process.
$auth_request = $consumer->begin($openid);
// Create attribute request object
// See http://code.google.com/apis/accounts/docs/OpenID.html#Parameters for parameters
// Usage: make($type_uri, $count=1, $required=false, $alias=null)
$attribute[] = Auth_OpenID_AX_AttrInfo::make('http://axschema.org/contact/email',2,1, 'email');
$attribute[] = Auth_OpenID_AX_AttrInfo::make('http://axschema.org/namePerson/first',1,1, 'firstname');
$attribute[] = Auth_OpenID_AX_AttrInfo::make('http://axschema.org/namePerson/last',1,1, 'lastname');
// Create AX fetch request
$ax = new Auth_OpenID_AX_FetchRequest;
// Add attributes to AX fetch request
foreach($attribute as $attr){
$ax->add($attr);
}
// Add AX fetch request to authentication request
$auth_request->addExtension($ax);
// No auth request means we can't begin OpenID.
if (!$auth_request) {
displayError("Authentication error; not a valid OpenID.");
}
/* $sreg_request = Auth_OpenID_SRegRequest::build(
// Required
array('nickname'),
// Optional
array('fullname', 'email'));
if ($sreg_request) {
$auth_request->addExtension($sreg_request);
} */
$policy_uris = null;
if (isset($_GET['policies'])) {
$policy_uris = $_GET['policies'];
}
$pape_request = new Auth_OpenID_PAPE_Request($policy_uris);
if ($pape_request) {
$auth_request->addExtension($pape_request);
}
// Redirect the user to the OpenID server for authentication.
// Store the token for this authentication so we can verify the
// response.
// For OpenID 1, send a redirect. For OpenID 2, use a Javascript
// form to send a POST request to the server.
if ($auth_request->shouldSendRedirect()) {
$redirect_url = $auth_request->redirectURL(getTrustRoot(),
getReturnTo());
// 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.
header("Location: ".$redirect_url);
}
} else {
// Generate form markup and render it.
$form_id = 'openid_message';
$form_html = $auth_request->htmlMarkup(getTrustRoot(), getReturnTo(),
false, array('id' => $form_id));
// Display an error if the form markup couldn't be generated;
// otherwise, render the HTML.
if (Auth_OpenID::isFailure($form_html)) {
displayError("Could not redirect to server: " . $form_html->message);
} else {
print $form_html;
}
}
}
run();
?>
oid_ax_receive.php
<?php
require_once "oid_ax_common.php";
// Starts session (needed for YADIS)
session_start();
function escape($thing) {
return htmlentities($thing);
}
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) {
// Get registration informations
$ax = new Auth_OpenID_AX_FetchResponse();
$obj = $ax->fromSuccessResponse($response);
// Print me raw
echo '<pre>';
print_r($obj->data);
echo '</pre>';
exit;
$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';
}
run();
?>
Enjoy.
Dante
P.S.: to complete the opera of OpenID, although I solved my problem with user info / login data with Google, I still have one problem with Light OpenID (https://stackoverflow.com/questions/10735708/lightopenid-openid-authurl-does-not-return-any-value).
If you want to help me, we will completely work out and conclude with the OpenID story.