Good evening, I have this code but I need to know if this actually logged but do not make it, that I'm wrong? this scritp not show me any errors: (
$userDetails = array('foo' => 'bar');
$storage = new Zend_Auth_Storage_Session();
// set sorage for Zend_Auth
Zend_Auth::getInstance()->setStorage($storage);
// write data to the storage
Zend_Auth::getInstance()->getStorage()->write($userDetails);
// read data from storage
$c = Zend_Auth::getInstance()->getStorage()->read();
$result = $c->authenticate($userDetails);
echo $this->view->form = var_dump($result);
if (!$result->isValid()){
var_dump('FAILURE');
}else{
$this->_helper->redirector('index','index');
}
You could check session in Zend by,
if (Zend_Auth::getInstance()->hasIdentity()) {
// do user session action
} else {
// redirect to login page
}
To get user info try,
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
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 am having a bit of difficulty with form tokens. I have a global file that i require at the top of all of the controllers.
/*
*----------------------------------------------
* VERIFY FORM TOKENS
*----------------------------------------------
*/
if ($_POST) {
// Define and Sanitize
$formToken = $sanitize->input($utilities->getVar('formToken', 'session'));
$authenticityToken = $sanitize->input($utilities->getVar('authenticityToken'));
// Validate
if ($authenticityToken !== $formToken) {
$errors[] = 'There was a token mismatch error submitting your form. Please try again.';
}
}
// Generate Form Token
$formToken = $forms->token();
$_SESSION['formToken'] = $formToken;
When echo'ing the vars out right after being declared they match. But when i check the db ( I save sessions to db ) every db refresh displays a new formtoken that was saved. I only call the $forms->token(); class once this is what it looks like
class Forms {
public __construct(){}
function token() {
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$token = '';
for ($i = 0; $i < 60; $i++) { $token .= $characters[ rand( 0, strlen( $characters ) - 1 ) ]; }
$hash = substr(str_shuffle($token), 0, 32);
return $hash;
}
}
I have been working on this issue for a while now, i am confused as to why this occurs. I am also using mod_rewrite in my .htaccess file. I read that rewrites affect sessions but all other session data is ok ( session login data etc. ) it is just these tokens that are giving me a hard time.
I think you need to wrap an else around where you generate the token. As you have it, it looks like you get the token, then create a new one each time.
if ($_POST)
{
// Define and Sanitize
$formToken = $sanitize->input($utilities->getVar('formToken', 'session'));
$authenticityToken = $sanitize->input($utilities->getVar('authenticityToken'));
// Validate
if ($authenticityToken !== $formToken)
{
$errors[] = 'There was a token mismatch error submitting your form. Please try again.';
//UPDATE: MAYBE PUT IT HERE TOO:
$formToken = $forms->token();
$_SESSION['formToken'] = $formToken;
}
}
else
{
//----putting in an else so this is not done again on POST--------
// Generate Form Token
$formToken = $forms->token();
$_SESSION['formToken'] = $formToken;
}
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 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.
I am a beginner in Joomla, I want to integrate Facebook login with my website (using Joomla 3.0), I want to know how to store the user info into my database after receiving them from facebook. Any suggestion?
Try this,
If you are using FB SDK for PHP
$path = realpath('.');
require_once($path."/facebook/fbmain.php");
$user = $facebook->getUser();
// print_r($user);
// echo "user<br/>";
// print_r($userInfo);
// echo "<br/>Info<br/>";
// print_r($fqlResult);
// foreach($fqlResult as $key=>$value){
// print_r($value);
// echo '<br>';
// }
// exit;
if ($user){
$fname = $userInfo['first_name'];
$last_name = $userInfo['last_name'];
$username = $userInfo['id'];
$dob = date("d-m-Y",strtotime($userInfo['birthday']));
foreach($fqlResult as $key=>$value);
$user_email = $value['email'];
$profile_image = $value['pic_square'];
$sex = $value['sex'];
$city = $value['hometown_location']['city'];
$state = $value['hometown_location']['state'];
$country = $value['hometown_location']['country'];
$zip = $value['hometown_location']['zip'];
//Then simply call model and write save db query.
$model = $this->getModel('Registration', 'UsersModel');
}
You want to make a FB authentication plugin and then have that pass off the data to the Joomla user plugin if possible. If you want to use a different user table you would need to make your own user plugin as well. Joomla auth first authenticates (authentication plugin), then authorsises, then logs in (user plugin)