Programmatically magento admin connection doesn't work - php

I want to log a user programmatically to magento admin. The admin page is in an iframe and it have to redirect automatically to the admin dashboard without authentication. I used a code found in a ancient post and it matches with the magento core source. The code is :
umask(0);
$app = Mage::app('default');
Mage::getSingleton('core/session', array('name' => 'adminhtml'));
// supply username
$user = Mage::getModel('core/factory')->getModel('admin/user')->loadByUsername($loginadmin);
if (Mage::getSingleton('adminhtml/url')->useSecretKey()) {
Mage::getSingleton('adminhtml/url')->renewSecretUrls();
}
$session = Mage::getSingleton('admin/session');
$session->setIsFirstVisit(false);
$session->setUser($user);
$session->setAcl(Mage::getResourceModel('admin/acl')->loadAcl());
Mage::dispatchEvent('admin_session_user_login_success',array('user'=>$user));
if ($session->isLoggedIn()) {
//Redirection vers le dashboard
$url = "index.php/admico/dashboard";
header('Location: '.$url);
}
When I var_dump()the data, the user exists and it have all the informations like firstname, id, etc and it's all correct. The code go inside the last if and redirect to 'index.php/admico/dashboard' so the $session is correctly logged in. But, anyway, the frontpage display the connection form as if the session was not logged in and not the dashboard of the admin.
Can someone help me to figure out what's wrong please ?

Perhaps when the window is redirected in your last conditional, the iframe cannot access that login session on your website. I see that you are using the PHP header function. The only possible solution that I can think of is by getting the SID of the login session and using that as a URL parameter. So some edited code inside your conditional would look something like this:
$SID=$session->getEncryptedSessionId();
$url = "index.php/admico/dashboard?SID=" . $SID;
If that doesn't work, you can try using the PHP function setcookie() with $session as the stored data and then try the redirect. You can find documentation for that here. That's all that I've got for you. If this doesn't work, try looking at this and see if there is anything that may help you. Best of luck!

I have made two changes in the code and it is working fine for me on firefox, safari and chrome. I also cleared up my cookies before I attempted this code.
test.php
<iframe src="http://localhost.site/test_login.php" width="100%"></iframe>
test_login.php
<?php
require 'app/Mage.php';
umask ( 0 );
Mage::app ( 'admin' );
Mage::getSingleton('core/session', array('name' => 'adminhtml'));
// supply username
$user = Mage::getModel('admin/user')->loadByUsername("USERNAME");
if (Mage::getSingleton('adminhtml/url')->useSecretKey()) {
Mage::getSingleton('adminhtml/url')->renewSecretUrls();
}
$session = Mage::getSingleton('admin/session');
$session->setIsFirstVisit(false);
$session->setUser($user);
$session->setAcl(Mage::getResourceModel('admin/acl')->loadAcl());
Mage::dispatchEvent('admin_session_user_login_success',array('user'=>$user));
if ($session->isLoggedIn()) {
//Redirection vers le dashboard
$url = "/admin/dashboard/";
header('Location: '.$url);
}

Related

Yii loses session after OAuth redirect

I've lost a day and a half now trying to figure out why Yii is deleting all of the session data after I go to Twitter's OAuth page and back to my redirect.
Here is the main SiteController, where I go to Twitter. Here I am trying to save the oauth_token and token_secret values, so I can use them on the redirect controller.
function actionTwitter()
{
$consumerKey = "";
$consumerSecret = "";
$connection = new TwitterOAuth($consumerKey, $consumerSecret);
$request_token = $connection->oauth("oauth/request_token", array("oauth_callback" => "http://127.0.0.1/yii/?r=redirect&type=twitter"));
$oauth_token=$request_token['oauth_token'];
$token_secret=$request_token['oauth_token_secret'];
Yii::app()->session['token'] = $oauth_token; // This doesn't save!!
Yii::app()->session['token_secret'] = $token_secret; // This does not save!!
$url = $connection->url("oauth/authorize", array("oauth_token" => $oauth_token));
$this->redirect($url);
exit(); // some people have said I need to exit the session first after I redirect, but it doesn't help at all.
}
Here is my RedirectController, which is a separate controller and not in the main SiteController:
public function actionIndex()
{
$type = $_GET['type'];
if ($type == "twitter")
{
$token = Yii::app()->session['token'];
print($token);
}
}
I also have the session autostart set to true in my config file.
Thoughts on why it isn't working / stuff I have read about:
Twitter's site is HTTPS, and I am on localhost (which isn't HTTPS). For some reason that I forget this will make the session lose data when I redirect. If this is the case, how do I fix it without using HTTPS?
When I create new CHttpCookies they do not save either, I can't retrieve the value
I have tried Yii::app()->user->setState instead, which isn't working either.
I found the solution. It did not work because I was using 127.0.0.1 for the redirect, instead of the standard localhost. I changed that and all is working now.

Is anything other than unset($_SESSION) needed for logout?

Is there any reason that unsetting the session wouldn't be enough for a logout? Is there some security reason more is needed?
I have a script that uses the facebook login (using PHP). But for some reason, using any of the following messes with the login for some reason. After being logged out using any of the codes below, when trying to login using facebook redirect it it forces you to push the button twice for it to recognize that a facebook session has been created.
if (isset( $_COOKIE[session_name()] )) {
setcookie(session_name(), "", time() -3600, "/" );
}
$_SESSION = array();
session_destroy();
Try something like below:
$params = array('next' => 'http://something.com/logout.php');
$logout = $facebook -> getLogoutUrl($params);
$_SESSION['logout'] = $logout; `

Problems with Drupal login through external php file

I want to login to drupal through an external php file.
My testserver is located at http://develop.dev, the following login script is in a subfolder in the same domain.
/*
* testlogin.php
*
*/
define('DRUPAL_ROOT', '/Applications/XAMPP/xamppfiles/htdocs_develop');
include_once '../includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
global $user;
//just a test -> login as admin
$uid = 1;
$login_array = array ('name' => $user->name);
user_login_finalize($login_array);
echo "user is logged in? ".user_is_logged_in();
This procedure seems to work. I’m logged in as user admin and can execute drupal functions.
However, when I then visit http://develop.dev within the same webbrowser I see that I’m not logged in. Is this a problem with the drupal session? What is my mistake?
Thank you for any hint, rhodes.
I think you have to load the user 1 first and then assign it back to global $user.
$uid = 1;
$account = user_load($uid);
global $user;
$user = $account;
$login_array = array ('name' => $user->name);
user_login_finalize($login_array);

keeping a LDAP user logged in with PHP session

UPDATED According to advice below. But still not working. Any help?
My company uses Active Directory LDAP and I'm using adLDAP to authenticate the user to login to this website.
So far, it works.. but every time they visit the page they must login again. The solution to this, I know is sessions. But I can't figure out what to store in the session in order to keep the user logged in.
This is included at the top of my login.php page:
auth.php
<?php
//include LDAP authenication script
require_once('LDAP/adLDAP.php');
$adldap = new adLDAP();
$username = $_POST['account'];
$password = $_POST['password'];
$authUser = $adldap->authenticate($username, $password);
$userinfo = $adldap->user_info($username, array("*"));
if ($authUser == true) {
$_SESSION['LDAP']['login'] = true
}
?>
Also at top of every page I have this:
<?php
if (empty('LDAP')) session_start();
if (!isset($_SESSION['LDAP']['login'] && $_SESSION['LDAP']['login'] !== true) {
header('Location: login.php');
exit; // dont forget the exit here...
}
?>
Right now, everytime I visit my index page index.php I log in, and I'm redirected to the main page. It works perfectly. But if I refresh the page, I'm asked to login again.
What do I store into a session so I don't have to log in everytime I refresh the page?
I know it starts with:
session_start();
But I don't know what to store in it?
You should only authenticate/include LDAP on your login page..
if success set a $_SESSION['LDAP']['login'] = true;
And check on every page with this.
if (!isset($_SESSION['LDAP']['login'] && $_SESSION['LDAP']['login'] !== true) {
header('Location: login.php');
exit; // dont forget the exit here...
}

Getting SESSION to work after redirect

I am new to PHP and even newer to SESSIONS
I am working with the Instagram API and I am successfully able to authorize an app, and redirect to a page to display content.
My main folder is called Monkey and it has a sub folder called Instagram.
MY callback url for instagram is success.php located in the instagram folder. When I successfully retrieve an access token from Instagram it redirects to the index file in the Monkey folder.
On my success page, I am creating an array full of data called instaArray. I am trying to pass the array from the success.php in the instagram folder, to the index.php in the monkey folder.
My redirect is simply
header( 'Location: ../index.php' );
Because I am new with sessions, I guess I am doing something wrong. I figured it was straight forward, but I suppose not ha.
On the success.php page, after I build the array I have this
session_start();
$_SESSION['instagram'] = $instaArray;
I thought that should create a session that holds my array InstaArray.
Then, on the index.php page in Monkey, I have this
<?php
session_start();
$get_instagram = $_SESSION['instagram'];
print_r($get_instagram);
?>
But absolutely nothing happens. I've even tried to set the session instagram to a simple numerical value or 1, $_SESSION['instagram'] = 1; and get that on the index page, and it doesn't work either.
Am I doing something horribly, terribly wrong? I've read up on sessions, but because it's new, it's still a little confusing.
Thanks for the help, and I hope I was able to explain everything properly.
EDIT: Here is my success.php page in full
<?php
require 'src/db.php';
require 'src/instagram.class.php';
require 'src/instagram.config.php';
// Receive OAuth code parameter
$code = $_GET['code'];
// Check whether the user has granted access
if (true === isset($code)) {
// Receive OAuth token object
$data = $instagram->getOAuthToken($code);
// Take a look at the API response
$username = $data->user->username;
$fullname = $data->user->full_name;
$id = $data->user->id;
$token = $data->access_token;
$user_id = mysql_query("select instagram_id from users where instagram_id='$id'");
if(mysql_num_rows($user_id) == 0) {
mysql_query("insert into users(instagram_username,instagram_name,instagram_id,instagram_access_token) values('$username','$fullname','$id','$token')");
}
//Set Cookie
$Month = 2592000 + time();
setcookie(instagram, $id, $Month);
// Set user access token
$instagram->setAccessToken($token);
// Retrive Data
$instaData = $instagram->getUserFeed();
// Create Instagram Array
$instaArray = array();
$count = 0;
// For each Instagram Post
foreach ($instaData->data as $post) {
$instaArray[$count]['post_id'] = $post->id;
$instaArray[$count]['name'] = $post->user->username;
$instaArray[$count]['profile_img'] = $post->user->profile-picture;
$instaArray[$count]['img_url'] = $post->images->standard_resolution->url;
$instaArray[$count]['caption'] = $post->caption->text;
$instaArray[$count]['like_count'] = $post->likes->count;
$instaArray[$count]['comment_count'] = $post->comments->count;
$instaArray[$count]['created_time'] = $post->created_time; //Unix Format
$count++;
}
// Start Session For Array
session_start();
$_SESSION['instagram'] = serialize($instaArray);
header( 'Location: ../index.php' ) ;
} else {
// Check whether an error occurred
if (true === isset($_GET['error'])) {
echo 'An error occurred: '.$_GET['error_description'];
}
}
?>
Why not use an ID and then cookies rather than sessions + data (which are usually store on the server in text files in a temporary directory)? And keep all data within a database than allow the client to be accessible to the data. Sessions are also temporary.
Note, do you know if you have "globals" on?!
"Please note when working with sessions that a record of a session is not created until a variable has been registered using the session_register() function or by adding a new key to the $_SESSION superglobal array. This holds true regardless of if a session has been started using the session_start() function."
Reference:
http://www.php.net/manual/en/function.session-register.php
make session_start() first line after php
<?php
session_start();
and remove it from anywhere ele on page.
session_start() should be your first line in index.php also as in success.php
Note: The session_start() function must appear BEFORE the tag:
REF : http://www.w3schools.com/php/php_sessions.asp
I think you need to unserialize() your array in index.php.
$get_instagram = unserialize($_SESSION['instagram']);

Categories