php prestashop cookie - php

how to access prestashop cookie?
the directory structure islike this
/
|
|-index.php
|
|-prestashop/
|
|-(presta shop files)
I manage to do a login from the index.php.
but i cannot access the cookie to check if the user logged in or not.
any way to check it or get the user name

For Prestashop 1.6 its different now, there is no $smarty and no $cookie, all in Context.
How to access the Context?
From inside a Controller subclass, an AdminTab subclass or a Module subclass, the Context should be called with this shortcut: $this->context.
From anywhere else, you can get the Context instance by calling Context::getContext().
Old way
$cookie->id_lang;
New way
$this->context->language->id;
More about this in docs here http://doc.prestashop.com/display/PS16/Using+the+Context+Object#UsingtheContextObject-WhatistheContextobject?

Prestashop maintains a global $cookie variable which is an object of type Cookie. As long as you're bootstrapping Prestashop in your external index.php file, then you should be able to access it:
function myfunction()
{
global $cookie;
if ($cookie->isLogged)
echo 'Here be dragons.';
}
Without knowing how you're accessing the Prestashop core to perform the login though it's hard to give specific advice...

Related

SimpleSMLphp Custom Module Authentication Triggering Twice

Background: I am trying to set up single sign on (SSO) for users such that they can authenticate to my website and not have to authenticate a second time to our third-party MSP's website. Ideally, the user clicks a link on our website and is taken to the third-party site already logged in and landing on the dashboard (if the account doesn't exist, it is created during this step). We are not using SAML for authentication as a security feature, so all that we need the SAML code for is just producing cookies that prevent the user from having to log in again when he/she gets to our vendor's site. This third party MSP does not support authentication via API or web service and therefore I have been tasked with implementing SAML, their only supported SSO method. I am new to SAML (but not PHP or development) and have been learning as I go. I am told it will support the goals described above.
I initially tried using LDAP as the authentication source as this is what I use for authentication to my website, but this resulted in me getting directed to a login page with no discernible way to instead just pass parameters to SimpleSAMLphp to tell it "the user is already authenticated, all I need you to do is give me valid cookies so I can get past the third party website's authentication checks".
So I switched to writing a custom authentication module. I opened up the GitHub for SimpleSAMLphp and used the "UserPassBase" class as an example to create my own authentication module that inherits from the "Source" class. Because I don't need to re-authenticate the user against LDAP a second time since they're already logged in to our website, I created a simple "authenticate" function that just sets the $state['Attributes'] array.
Here is the code for my custom module:
<?php
namespace SimpleSAML\Module\productauth\Auth\Source;
use SimpleSAML\Auth;
/**
Author: Joey
Class developed to be used as a custom authentication module for simpleSAMLphp. This class will take an existing session from a product website and use it to create a SAML session and redirect to a website.
**/
class ProductAuth extends \SimpleSAML\Auth\Source {
const STAGEID = '\SimpleSAML\Module\productauth\Auth\ProductAuth.state';
const AUTHID = '\SimpleSAML\Module\productauth\Auth\ProductAuth.AuthId';
private $user;
public function __construct($info, $config) { // parameters aren't used, just filler from base class
$info = array("AuthId" => "productauth");
parent::__construct($info, $config);
}
public function login($user, $redirectURL) {
$this->user = $user; // normally I'd set this in the constructor, but the overload has my hands tied as far as function definitions go
$this->initLogin($redirectURL); // calls authenticate function and then, if no exceptions, parent::loginCompleted which redirects to the given URL
}
public function authenticate(&$state) { // called by parent::initLogin
$state[self::AUTHID] = $this->authId;
$state['Attributes'] = [
'uid' => [$this->user->uid],
'givenName' => [$this->user->givenName],
'sn' => [$this->user->sn],
'mail' => [$this->user->mail]
];
$id = Auth\State::saveState($state, self::STAGEID);
}
}
?>
I am calling it from a controller class on my website:
private function goToTrainingSite() {
require_once("../third-party-libs/simplesamlphp/_include.php");
global $TRAINING_URL;
$user = $_SESSION['subject']->user;
$samlObj = new SimpleSAML\Module\productauth\Auth\Source\ProductAuth(array(), array());
$samlObj->login($user, $TRAINING_URL);
}
I mimicked the flow of the "UserPassBase" class (https://github.com/simplesamlphp/simplesamlphp/blob/master/modules/core/lib/Auth/UserPassBase.php), but it seems that despite all of my authentication working and setting a SimpleSAMLAuth cookie, when the parent::loginCompleted function in the "Source" class (https://github.com/simplesamlphp/simplesamlphp/blob/master/lib/SimpleSAML/Auth/Source.php) runs, it redirected me to the third party site. I then see the following in the logs:
SAML2.0 - IdP.SSOService: incoming authentication request: [REDACTED DATA]
Session: 'productauth' not valid because we are not authenticated.
I have been trying for 3 days to figure out why it seems as though despite setting SimpleSAML session cookies with a completed, successful authentication, that upon receiving the auth request from the SP, my SimpleSAMLphp code just pretends to not know about the completed auth and tries to authenticate again... but because it is not being called from my code, it doesn't have access to the $user variable which contains all of the attributes I need to place on the user when he/she authenticates to this third party website. It seems that when it receives an authentication request, my SimpleSAMLphp installation starts a new session and tries a brand new authentication.
I have delved into a lot of the code of SimpleSAMLphp and tried to understand what is going on, but it seems that there is just no reasonable way to authenticate by calling an authentication source from PHP code and being able to skip the SP-initiated authentication. I have tried:
Using the SimpleSAML API (https://simplesamlphp.org/docs/stable/simplesamlphp-sp-api) to call my authentication source, but there seems to be no way to pass that $user variable I need the attributes from.
Trying to load the cookies in the "Session" class when it is checking for valid sessions... but it seems like the cookies from the successful auth session initiated by my code are just gone and nowhere to be found.
I decided to stop focusing on trying to get the $user variable and the data I needed to the second authentication, and instead focus on WHY the second authentication was even happening. I looked at the cookies and thought about how the data was being retrieved, and made a correct hunch that our application's custom session handler might be at fault for SimpleSAMLphp's inability to recognize the first authentication. Our custom session handler stores our sessions in the database, but SimpleSAMLphp expects to use the default PHP session handler to manage its session. Therefore, my first authentication was being sent to the database and when SimpleSAMLphp started looking for it where PHP sessions are usually stored, it didn't see it and assumed it needed to kick off another authentication session from scratch.
Using SimpleSAMLphp's documentation for service providers and a lot of my own debugging, I changed the function in my controller like so:
private function goToTrainingSite() {
require_once ("../third-party-libs/simplesamlphp/_include.php");
global $TRAINING_URL;
$joeySiteSession = $_SESSION;
$user = $_SESSION ['subject']->user; // save user to variable before the Joey's Site session is closed
session_write_close (); // close Joey's Site session to allow SimpleSAMLphp session to open
session_set_save_handler ( new SessionHandler (), true ); // stop using SessionHandlerJoey and use default PHP handler for SimpleSAMLphp
$samlObj = new SimpleSAML\Module\joeysiteauth\Auth\Source\JoeySiteAuth ( array (), array () );
$samlObj->login ( $user, function () { return;} ); // use custom authentication module to set atttributes and everything SimpleSAMLphp needs in the auth session/cookie
$session = \SimpleSAML\Session::getSessionFromRequest ();
$session->cleanup (); // must call this function when we are done with SimpleSAMLphp session and intend to use our Joey's Site session again
session_write_close ();
$_SESSION = $joeySiteSession; // restore Joey's Site session
header ( "Location: {$TRAINING_URL}" );
}

Loading phpBB in Laravel code conflicts

I am trying to access some of the functions within phpBB from my Laravel application, this is for actions such as adding a user when a registration happens on my main site and autologins.
PhpBB is installed under /public/forums and I have updated .htaccess to allow it. I am able to access and use it just fine.
I have a helper that was originally constructed for codeigniter but should translate in to the laravel world. I am loading it as a helper by putting it under app, loading it using
use App\Helpers\phpBBHelper;
and I access the functions as such
$ph = new phpBBHelper();
$ph->addPhpbb3User('dave','password','dave#dave.com');
At the top of my helper I have this constructor
public function __construct() {
// Set the variables scope
global $phpbb_root_path, $phpEx, $cache, $user, $db, $config, $template, $table_prefix;
define('IN_PHPBB', TRUE);
define('FORUM_ROOT_PATH', 'forum/');
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : FORUM_ROOT_PATH;
$phpEx = substr(strrchr(__FILE__, '.'), 1);
// Include needed files
include($phpbb_root_path . 'common.' . $phpEx);
// Initialize phpBB user session
$user->session_begin();
$auth->acl($user->data);
$user->setup();
// Save user data into $_user variable
$this->_user = $user;
}
When i execute the code I get a server 500 error
PHP Fatal error: Call to a member function getScriptName() on null in
/home/ubuntu/workspace/public/forum/phpbb/session.php on line 50
which is this line
$script_name = $request->escape($symfony_request->getScriptName(), true);
I have found a post on stack overflow that exactly refers to my issue but the resolution of that issue was never posted
Laravel conflicting
In that thread it was suggested that because both phpBB and Laravel both use composer it was causing a conflict when loading the classes. I am not sure if that is true.
But Laravel is certainly affecting phpBB when I call the $user->session_begin();.
I would suggest to not reinvent the wheel and use already coded extension like lara-auth-bridge. The registration is simply inserting the right rows in the right tables, not familiar with phpBB3 in particular, but you could see the changes in the database after a new account is created.
Edit: You can surround the problematic code in try {} catch {} block in case that the error is not fatal for the registration itself so the server will not end up with 500.
When two applications had to communicates, I updated the twice. PhpBB is written to be upgradable with extension. You can develop a phpBB extension which is an API to create a new user.
Your new extension uses XML-RPC over HTTP for all communications between your laravel app and the forum system. You define a route which receives informations about the new users and then you analyse the creation process in phpbb. This way is easier because you're inside the phpBB/symfony Framework.
In your laravel application, you have to call the API to start communications.
The error clearly indicates that the symfony_request object is null. By browsing the source code a bit, I found that that variable (and many others) are expected to exist globally.
It seems like you have to include the phpBB/app.php file. It creates most of the objects needed.
update:
Actually, you are including the common file which does most of the initial setup. Maybe just making a global
$symfony_request = $phpbb_container->get('symfony_request');
will work. (I can't test it myself now, just throwing ideas)
(If possible, though, I'd try another library. I don't like those globals. Nobody does. It makes tracing stuff and debugging harder, as this question shows)
To be able to get the session request, you have to be sure both the PhpBB forum and your Laravel application use the same kind of cookie :
Same domain
Same path
Same secure flag
Are these settings ok?

Joomla 3! Module Parameters

I have a Joomla website where I have a custom module with mod_myModuleName.php and mod_myModuleName.xml files and a folder where there are several PHP scripts that add special functionality to my module. There is a config.php file in the folder that holds an associative array with variables and their values hard-coded. The module works just fine.
What I want though is to provide administrator area for the values of the variables in the array, so that I can put values in administrator panel and get their values in config.php. In my mod_myModuleName.php I use <?php echo $params->get('param')?> and it works like a charm.
But when I try to use the same technique in the config.php it breaks my code. I tried to get the values in mod_myModuleName.php and then include it in config.php and use the variables but it does not work either. I have not got so much experience in php and cannot understand what can be the reason.
It sometimes gives me an error of something non object and I guess it must be something connected with object oriented php, am I right? And if so is there a way to overcome this without object orientation or how can I solve my problem?
The problem will be with the way you're using your config.php.
When your modules entry point file mod_myModuleName.php is loaded by Joomla the $params object is already available in that context, you need to provide it to your scripts.
If you look at something like the mod_articles_latest module you will notice that the helper class is included with this line:
require_once __DIR__ . '/helper.php';
And then helper class is has it's getList() method called statically with the $params passed into it, so that $params is available to class context:
$list = ModArticlesLatestHelper::getList($params);
Inside the helper class ModArticlesLatestHelper you will notice that the getList() expects the $params to be passed in.
public static function getList(&$params)
{
...
}
I would strongly recommend reading the articles in the Modules section of Developers Portal on the Joomla Doc's.
Try the "Creating a simple module" article.

Get stored Zend_Auth data from outside the zend project (in an extern non-zend-project)

I'm working on a Zend project where I need to include another project, which isn't using ZF. This other project is stored in the public directory in the folder of the zend project.
For this other project I need the logindata from the zend project (zend auth is used for this). There are 2 ways to accomplish this i think.
Just get the stored login sessionvariable. But where/what variable?
Or try to get the data with zend methodes in the other project. But how? Without changing the structure of this other project.
Or maybe (probably) there's an other/better solution?!
Hope it's clear.
Tnx
$authNamespace = new Zend_Session_Namespace('Zend_Auth');
$authNamespace->user = "myusername";
Just include pathToZendProjectDirectory\Zend\Session.php from your 'nonzend` project
The login data is in SESSION variable. But we can't access the session data directly outside the project, because the SESSION contain some Zend objects. When we start the session it race an error __PHP_Incomplete_Class has no unserializer.
To over come this add the code in starting of the page.
function __autoload($class) { // required files load automatically
require_once "pathToZendProjectDirectory/PathToZendLibrary/$class.php";
}

PHP Unit Testing with Zend Auth and Zend ACL

I have an application that is behind a login and utilizes zend_acl and zend_auth.
During pre-dispatch I have an ACL plugin that creates all the rules out for the ACL. I also have an Auth plugin that checks if you're logged in or not and if so if you have access to the requested resource according to the ACL.
As the application is entirely behind a login the ACL is only created if you're logged in.
Unit testing this appears to be impossible, or rather more likely I'm missing something obvious.
In my unit test setup method I simulate a successful login that returns a zend_auth instance. Tests that do pass indicate that this login was successful.
However, if I then through tests attempt to dispatch to another location, or assess if the logged in user has access to a given resource it is always rejected by the plugin as they're still not logged in. I am not sure why this is, can anyone advise?
For example this passes:
public function testLoggedIn()
{
$this->assertTrue( Zend_Auth::getInstance()->hasIdentity() );
}
This fails as it's rejected by the plugin:
public function testUserAccess()
{
$this->dispatch('/home');
$this->assertResponseCode(200);
$this->assertQueryContentContains('#nav_side');
$this->resetRequest()
->resetResponse();
}
This, I have found still seems to be redirecting back to the login page as the plugins don't know the user is logged in.
Any help much appreciated.
Here is another way of creating a stub to replace your ACL Plugin (or any plugin) during testing. Put this in your ControllerTestCase and call it in the test case setUp.
public function doLogin ()
{
// create a fake identity
$identity = new stdClass();
$identity->Username = 'PHPUnit';
Zend_Auth::getInstance()->getStorage()->write($identity);
// remove the autoloaded plugin
$front = Zend_Controller_Front::getInstance();
$front->unregisterPlugin('My_Controller_Plugin_Acl');
// create the stub for the Acl class
$mockaAcl = $this->getMock(
'My_Controller_Plugin_Acl',
array('preDispatch'),
array(),
'My_Controller_Plugin_AclMock'
);
// register the stub acl plugin in its place
$front->registerPlugin($mockAcl);
}
This way your stub preDispatch method is called instead, which will bypass your actual access control checks.
The Problem you describe happens a lot with the usage of global variables and the OOP global variable (the Singleton Pattern).
There is an article by the author of PHPUnit that describes how you can avoid that by using Dependency Injection and what other possibilities you've got and since it's very descriptive, I just suggest you to read it :) http://sebastian-bergmann.de/archives/882-Testing-Code-That-Uses-Singletons.html
As an ugly alternative (if you need a quick result) you could create a stub of Zend_Auth (describe in the link) and use the PHP 5.3 reflection API to set the Zend_Auth instance variable to your stub.
Hope that helps (as the question lived 4h without an other answer)

Categories