Why is Mage_Persistent breaking /api/wsdl?soap - api

I get the following error within Magento CE 1.6.1.0
Warning: session_start() [<a href='function.session-start'>function.session-start</a>]: Cannot send session cookie - headers already sent by (output started at /home/dev/env/var/www/user/dev/wdcastaging/lib/Zend/Controller/Response/Abstract.php:586) in /home/dev/env/var/www/user/dev/wdcastaging/app/code/core/Mage/Core/Model/Session/Abstract/Varien.php on line 119
when accessing /api/soap/?wsdl
Apparently, a session_start() is being attempted after the entire contents of the WSDL file have already been output, resulting in the error.
Why is magento attempting to start a session after outputting all the datums? I'm glad you asked. So it looks like controller_front_send_response_after is being hooked by Mage_Persistent in order to call synchronizePersistentInfo(), which in turn ends up getting that session_start() to fire.
The interesting thing is that this wasn't always happening, initially the WSDL loaded just fine for me, initially I racked my brains to try and see what customization may have been made to our install to cause this, but the tracing I've done seems to indicate that this is all happening entirely inside of core.
We have also experienced a tiny bit of (completely unrelated) strangeness with Mage_Persistent which makes me a little more willing to throw my hands up at this point and SO it.
I've done a bit of searching on SO and have found some questions related to the whole "headers already sent" thing in general, but not this specific case.
Any thoughts?
Oh, and the temporary workaround I have in place is simply disabling Mage_Persistent via the persistent/options/enable config data. I also did a little bit of digging as to whether it might be possible to observe an event in order to disable this module only for the WSDL controller (since that seems to be the only one having problems), but it looks like that module relies exclusively on this config flag to determine it's enabled status.
UPDATE: Bug has been reported: http://www.magentocommerce.com/bug-tracking/issue?issue=13370

I'd report this is a bug to the Magento team. The Magento API controllers all route through standard Magento action controller objects, and all these objects inherit from the Mage_Api_Controller_Action class. This class has a preDispatch method
class Mage_Api_Controller_Action extends Mage_Core_Controller_Front_Action
{
public function preDispatch()
{
$this->getLayout()->setArea('adminhtml');
Mage::app()->setCurrentStore('admin');
$this->setFlag('', self::FLAG_NO_START_SESSION, 1); // Do not start standart session
parent::preDispatch();
return $this;
}
//...
}
which includes setting a flag to ensure normal session handling doesn't start for API methods.
$this->setFlag('', self::FLAG_NO_START_SESSION, 1);
So, it sounds like there's code in synchronizePersistentInf that assumes the existence of a session object, and when it uses it the session is initialized, resulting in the error you've seen. Normally, this isn't a problem as every other controller has initialized a session at this point, but the API controllers explicitly turns it off.
As far as fixes go, your best bet (and probably the quick answer you'll get from Magento support) will be to disable the persistant cart feature for the default configuration setting, but then enable it for specific stores that need it. This will let carts
Coming up with a fix on your own is going to be uncharted territory, and I can't think of a way to do it that isn't terribly hacky/unstable. The most straight forward way would be a class rewrite on the synchronizePersistentInf that calls it's parent method unless you've detected this is an API request.

This answer is not meant to replace the existing answer. But I wanted to drop some code in here in case someone runs into this issue, and comments don't really allow for code formatting.
I went with a simple local code pool override of Mage_Persistent_Model_Observer_Session to exit out of the function for any URL routes that are within /api/*
Not expecting this fix to need to be very long-lived or upgrade-friendly, b/c I'm expecting them to fix this in the next release or so.
public function synchronizePersistentInfo(Varien_Event_Observer $observer)
{
...
if ($request->getRouteName() == 'api') {
return;
}
...
}

Related

ASP.NET Core Application Insights - Track Authenticated User ID

I have read everything I could find, and everything suggests using ITelemetryInitializer. However, the best I can figure - that only runs once as its a Singleton. It also runs before the user has authenticated, so I don't have the data I need quite yet.
I have added the logic to my client side tracking as that was pretty straightforward:
#if (_userService != null && _userService.IsAuthenticated())
{
<script>
appInsights.setAuthenticatedUserContext('#_userService.GetCurrentUserId()');
</script>
}
Note in this case _userService is a DI service I use to access the currently authenticated user (which for now just uses ClaimsPrincipal).
What I need to do now is add the same setting to the server side telemetry, but I can't seem to figure out how to tie-in to it. Anyone out there figured this out?
So I guess this falls into the bucket of "as soon as you as StackOverflow you figure it out yourself".
I don't know what I did wrong, but I do know once I changed my initializer from implementing ITelemetryInitializer to implementing TelemetryInitializerBase, it started working.

Redis-backed session state not saving everything

We are trying to move from server session (IIS) to Redis-backed session. I updated my web.config with the custom sessionState configuration. I'm finding that only SOME of my key/value pairs are being saved. Of the 5 I expect to be in there, there are only 2. I verified all my code is ultimately hitting HttpContext.Current.Session.Add. I verified that my POCOs are marked as serializable. Looking at monitoring, I see that it adds the first two pairs, then everything after that just doesn't make it. No hit, no rejection, no exceptions. Nothing.
Anyone ever see this? Know where I could start to look to resolve?
TIA,
Matt
Update 1: I've switched to using a JSON serializer to store my data. Same thing. Doesn't seem to be a serialization issue.
Update 2: I've now downloaded the source code, compiled and am debugging it. The method SetAndReleaseItemExclusive, which seems to send the session items to Redis, is only hit once, though it should be hit more than once as my web site handle SSO and bounces from page to page to load the user and such. Have to investigate why it's only firing once...
Figured it out. Turns out that my AJAX request to an "API" endpoint without my MVC app did not have the appropriate session state attached. Therefore, the SetAndReleaseItemExclusive was never called. Adding this fixed it:
protected void Application_PostAuthorizeRequest()
{
if (HttpContext.Current.Request.Url.LocalPath == "/api/user/load")
HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
else
HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.ReadOnly);
}

Calling Collection.allow() manually to check permissions

In Meteor JS I want to perform a task before adding an object to my collection. So I created my own method, eg: addObject like so:
Meteor.methods({
...
addObject: function(obj) {
/*
// this is what i'm trying to figure out...
if ( !MyColl.allow('insert', Meteor.userId, obj) )
throw Meteor.Error(403, 'Sorry');
*/
MyColl.update({ ... }}, { 'multi': true });
MyColl.insert(obj);
},
...
});
But I noticed that .allow is no longer being called because it's "trusted" code. The thing is the method is on the server but being called from the client (through ObjectiveDDP) so I still need a way to validate that the client has permissions to call addObject - is there any way to manually call .allow() on a collection from my server code? I tried it but getting an internal server error, and not sure what the syntax should be... couldn't find anything in the Meteor docs.
Edit:
I just found out that this works:
var allowedToInsert = MyColl._validators.insert.allow[0];
if (!allowedToInsert)
throw new Meteor.Error(403, 'Invalid permissions.');
But that's probably a no-no calling private methods such as _validators. Does anyone know of a more 'best practices' way?
You can do validation in the addobject method. For example, if you only want logged in users to be able to add an object, you can write:
if (!Meteor.user()) throw new Meteor.Error();
at the beginning of the addobject method.
Personally I never use allow.
On a related note, the collection2 and simple-schema packages can often help a lot with validation.
The validation pattern you are using might not be the best way to do things.
If you assume that methods can be called from the client, you shouldn't 'hack' it into doing something it's not meant to do.
If you are calling a method that changes data in the database you should check within that method that the currently logged in user has permission to do so.
However, are you sure you want to do this? Meteor also has Collection.allow and Collection.deny methods that you can use to define read/write/update/delete permission with. That's the recommended way to handle permissions, so what you are doing is an anti-pattern. However, perhaps in your case it is strictly necessary? If not, you might want to rethink the use case.
Like another response suggests, using something like Collections or SimpleSchema to validate data structure is also a good idea.

Undefined method stdClass::user() error when using CakePHP Auth

I'm fairly new to CakePHPand am building a site using the Auth component. A couple of times I have tried to do things with this component which have caused the error
Fatal error: Call to undefined method stdClass::user() in /ftphome/site/app/controllers/users_controller.php on line 395
The line it refers to in this case is
$this->User->read(null, $this->Auth->user('id'));
This error does not disappear when I revert the code back to how it was before the error and I only seem to be able to get rid of it by removing some files on the server (I'm not sure which files, when I tried removing all files in the tmp directory the error persisted so I removed the entire site and restored from the latest svn revesion.
In this particular case I think I caused the error by putting the following code in app_controller
class AppController extends Controller {
function beforeRender() {
$this->set('test', $this->Auth->user());
}
}
Which I copied from this thread http://groups.google.com/group/cake-php/browse_thread/thread/ee9456de93d2eece/cff6fe580d13622b?lnk=gst&q=auth
A previous time I caused the issue by attempting to update the Auth user details after updating the user in the database.
I can see I'm somehow removing the user object from the Auth object but I can't understand why I need to delete files in the site to get it back or how the code above removes it - any help would be much appreciated.
Edit
It looks like in the case I mentioned above, the problem was the app_controller.php file which I'd copied into my app/controllers directory. Just having the file with an empty class declaration causes this error - can anyone provide further insight?
Further edit
I've realised I've been a bit silly and the problem was caused by me putting app_controller.php in /app/controllers/app_controller.php when there was already one in /app/app_controller.php - thanks for the input though Andy, it helps me understand a bit more what was happening.
This error is normally thrown when a class instance (in your case an instance of Auth) has been serialised to disk, then re-read/deserialised in another request but the class definition (i.e. Auth) has not been loaded yet, so PHP creates it as an "stdClass" (standard class.)
When you remove your site files, you're removing the session storage (IIRC it's the Cache folder in a CakePHP app) so at the next request, a new session is created from scratch.
It's been a while since I last used CakePHP (I switched to Zend) so I cannot remember if Cake includes files it requires using an __autoload function or not.
On that mailing list post, someone says that you can this $this->Auth->user() in a view, but in the controller, you can use $session->read('Auth.User') to get the user component. Not sure what the difference is, maybe $this->Auth is a view helper, so isn't available in the controller?

Entity Framework: AttachAsModified failure / confusion :)

Ok... I tried google and didn't get many hits. I dont want to abuse So but this is one of the best places to ask and EF isn't well documented.
My fails because the GetOriginal() returns null in UpdateCmsProductCategory. I assume that means currentCmsProductCategory is not in the ChangeSet. Ok... how do I put it in the changeset?
Here is the sequence...
I pull a CmsProductCategory down over Wcf.
I make changes.
I call the Wcf update method...
public void UpdateProductCategory(CmsProductCategory category)
{
domainservice.UpdateCmsProductCategory(category);
}
Which calls the Domain servide method...
public virtual void UpdateCmsProductCategory(CmsProductCategory currentCmsProductCategory)
{
this.Context.AttachAsModified(currentCmsProductCategory,
this.ChangeSet.GetOriginal(currentCmsProductCategory));
}
And that should work - but no, it Exceptions on me when GetOriginal() fails. I feel like I am missing a step between when the code modifies it and I pass it to Wcf.
Any hints / pointers to good documentation?
Thanks!
Your problem is probably that you lose the "context".
When you make the call to update the "this.Context" is not the same as the one you read it from.
WCF has a concept of "per call" and "per session". The "per call" is default your are therefore getting a new instance of the domain service. You may be able to solve it using per session.
Have a look at this link: http://msdn.microsoft.com/en-us/magazine/cc163590.aspx
Also try writing a test to check that what you are doing works without transfering the data over wcf.