Archive for 'Coding'

Facebook: Upgrading to OAuth 2.0

As Facebook has beaten into me via my RSS reader over the last few months:

All apps must migrate to OAuth 2.0 for authentication and expect an encrypted access token. The old SDKs, including the old JS SDK and old iOS SDK will no longer work.

<digression> In the spirit of typical Facebook developer documentation, even this ostensibly unambiguous statement raises questions.  See, I have been using the “new” Graph API to authenticate for many months now, but not with the oauth flag set to true.  (In other words, I am on Oauth 1.0?)  Does this mean my code will break on Oct. 1st?  Or when they say that legacy authentication will break on Oct. 1st, do they mean that only the really old legacy auth will break?  In either case, I may as well upgrade to the latest and greatest now. </digression>

Here are the changes I had to make to get my stuff working with the oauth flag set to true.  They are mostly field and param name changes.  There may be other changes important to you, but this is what I needed to modify to upgrade.

1. Add ‘oauth: true‘ to FB.init()

So change this:

FB.init({ appId : XXXXXX });

to this:

FB.init({ appId : XXXXXX, oauth : true });

I infer from Facebook (which is usually dangerous) that this flag will be enabled for everyone on Oct. 1st.

2. Change ‘perms‘ to ‘scope

Anywhere you request permissions for your app upon Facebook login, you must change the ‘perms’ field to ‘scope’. So for a typical XFBML implementation, change this:

<fb:login-button perms=”offline_access”></fb:login-button>

to this:

<fb:login-button scope=”offline_access”></fb:login-button>

For a typical JS implementation, change this:

FB.login(function(response) { }, { perms : ‘offline_access’ });

to this:

FB.login(function(response) { }, { scope : ‘offline_access’ });

For a typical non-JS, server-side (PHP) implementation, change this:

<a href=”<?php echo $facebook->getLoginUrl(array(‘req_perms’ => ‘offline_acces's’)); ?>”>Connect with Facebook</a>

to this:

<a href=”<?php echo $facebook->getLoginUrl(array(‘scope’ => ‘offline_acces's’)); ?>”>Connect with Facebook</a>

3. Update JavaScript response object

Functions like FB.login() and FB.getLoginStatus() accept a callback that gets passed a response object from Facebook after an authentication attempt.  The previous response looked like this:

response = { perms : ‘offline_access’, 
             session : { 
               access_token : ‘XXXXXX’, 
               base_domain : ‘mydomain.com’, 
               expires : ‘0’, 
               secret : ‘XXXXXX’, 
               session_key : ‘XXXXXX’, 
               sig : ‘XXXXXX’, 
               uid : ‘XXXXXX’ }, 
             status : ‘connected’ };

The new response looks like this:

response = { authResponse : { 
               accessToken : ‘XXXXXX’, 
               expiresIn : 0, 
               signedRequest : ‘XXXXXX’, 
               userID : ‘XXXXXX’ }, 
             status : ‘connected’ };

You must update your JS authentication logic accordingly.

4. Change server-side PHP call getSession() to getUser()

Versions of the PHP SDK prior to 3.0 had both a getSession() and a getUser() method. After 3.0, there is only the getUser() call.  If you were using getSession() to check for authentication previously, you must use getUser() now.  If you don’t care about the internals of the new SDK, then getUser() functions the same as before and returns the Facebook ID of the currently logged in user, or 0 if there is none.

If you do care about the new SDK, then the reason for this is because Facebook has done away with the session concept and embraced the OAuth2 signed_request concept instead.  For example, the JSON-ified session array is no longer passed back to your callback URL in the query string upon authentication.  Now, an encoded signed_request is passed back in the query string, which contains the same info (user ID, access token, expiration time, etc.)

5. Change server-side PHP Facebook class constructor

The new PHP Facebook class no longer accepts a cookie flag in the constructor.  If you don’t care about the internals of the new SDK, then remove the cookie flag and you’re done.

If you do care about the new SDK, then the reason for this – well, I’m not sure what the reason is.  Perhaps a commenter could enlighten me.  Best as I can tell, they have removed overlapping features of the the JS SDK and PHP SDK. Prior to OAuth2, both SDKs had cookie flags, and both could set and read the session cookie, which could be confusing, especially if you were persisting your own authentication cookie.  Now, the JS can still set and read the signed_request cookie, but the PHP library has gotten out of the cookie game (although it can still read a signed_request cookie set by JS, and now it stores the signed_request data in the PHP session).

One more note about cookie: the new Facebook cookie begins with ‘fbsr_’ and not ‘fbs_’.

Conclusion

That’s it. As I said, these worked for me, but YMMV. Happy upgrading!

Slides from tek11

Here are my slides from my two talks at PHP 2011 tek conference in Chicago, IL.  Slide PDFs and any demo code are on GitHub.  Recap to follow!

Of (PHP) Sessions, Cookies, and Authentication

Do you know the difference between the PHP config directives session.gc_maxlifetime and session.cookie_lifetime? Have you wrestled with implementing a “Remember Me” button on your login page? Learn how popular sites, such as Twitter and Facebook, keep you logged in (apparently) forever and the security risks of such methods.

Who’s Using Your Software?

Software is only successful if someone can use it. Good developers need to do more than just follow specifications, they need to visualize the people who will use it and understand what they need. Get to know your users and the questions you need to ask to make your implementation a success on all fronts.

I recently came up a very steep learning curve using the Zend Framework (version 1.11.3). I had used components of ZF in the past with success, but this was the first time I had used Zend_Application for my core MVC.  I am no stranger to MVC frameworks in general, but I struggled with Zend.

My biggest source of confusion was the bootstrap process.  Namely, the autoloading of resources.  Yes, I followed the Zend Framework Quick Start and got my app up and running. Unfortunately, I didn’t actually know what was happening.  Finally, I came across this great question on Stackoverflow about bootstrapping the layout resource that pointed me in the right direction:

The line from application.ini

resources.layout[] = 

is equivalent to:

_initLayout() {}

in Bootstrap.php

Aha!  So now it was clear. There are two ways to initialize a resource in Zend:

  1. By adding one or more mysterious lines to your application.ini, or
  2. By constructing them with good old fashion code in a method that begins with “_init” in Bootstrap.php.

Option #1 bothers me.  Yes, it’s really cool that you can bootstrap a whole MVC application with no code and only a config file, but IMO that option should not be the recommended way for beginners and that options should most definitely not be used in any sort of “Quick Start” guide.  That sort of magic should be reserved for advanced users.  With a little more exploring, I found the code that initialized these resources in the non-trivial Zend_Application_Bootstrap_BootstrapAbstract class.  And I found all the built-in Zend resources in Zend/Application/Resource, which let me see which resources had which options and how to bootstrap them. 

On to option #2, my preferred way. If I want to initialize the Front Controller, I’ll just put this in the bootstrap file:

    
protected function _initFrontController()
{
    $front = Zend_Controller_Front::getInstance();
    $front->setControllerDirectory(APPLICATION_PATH . '/controllers');
    return $front;
}

If I want to enable and initialize the layout:

    
protected function _initLayout()
{
    $layout = Zend_Layout::startMvc();
    $layout->setLayoutPath(APPLICATION_PATH . '/layouts/scripts/');
    return $layout;
}

I really don’t mind carrying this around to every project.  Then I can make changes in the PHP, and not in an INI file.

Clearly I am not the only one struggling with this. I googled problems heavily and the top results usually contained 3 or 4 of the same question asked on Stackoverflow, each of which I opened in a tab.  I think Zend would benefit with a re-organization of the documentation from the ground up, at least of the starter docs and Zend_Application. They should also post a big, flashing red link to that Stackoverflow question about bootstrapping layout. 

Eventually, other components became clear: Resources, Plugins, Action Helpers, and View Helpers, Modules.  I see real power in using the Zend Framework now, particularly with Plugins and Modules, but only after much pain.

I have created a starter project for Zend projects that contains Bootstrap.php the way I like it, and some other custom classes for logging and error handling.  There is a branch for a starter project with modules and without modules.  (Modules is a different blog post altogether.)

A Layout Called By Any Other Name…

I am embarrassed to say that only somewhat recently did I figure out truly what a layout-based presentation (a.k.a. two-phase render) was all about. I’ve even used them before, and didn’t know why. 

If you can’t tell someone clearly what is the benefit of two-phase render, go and read the Smarty documentation on it right now.  Smarty calls it template inheritance, but IMO template inheritance, layouts, and two-phase render are all the same pattern.

Choosing A Language

This post, “14 descriptive reasons why Ruby may be better than PHP,” popped up on PHPDeveloper.org yesterday.  These types of lists appear regularly in the blogosphere. I usually don’t feel compelled to respond, but for some reason this time I do.  Perhaps it is the cool graphics.  Perhaps it is because I just wanted to blog.

Speaking as someone who has done a lot of PHP, and very little Ruby or Rails, overall, I agree with the article.  It talks about many of the reasons I wish I could start using Ruby more.  However, I would like to refute a few particular items in the list.  I’ll just cover each one with my input.

1. Human-readable code.

Yukihiro Matsumodo wanted to create a language that was designed for programmer functionality. By keeping naming consistent and keywords sensible, he was able to do so.

Agree.  I think this is more of a result of the object-oriented features of Ruby than anything else, but the names and keywords are indeed nice.

2. Principle of least surprise

it is designed in such a way that the language minimizes confusion for experienced users. Methods for different objects, if they do the same task, are generally named and capitalized the same way. This makes it less necessary to constantly refer to the documentation, which leads to faster coding.

Agree.  The inconsistencies in PHP names are well-documented. 

3. Community maturity

The community is better able to give concise, coherent answers since the community is a little more learned. As it is generally not a first language the people in the community already have experience coding and helping others.

Disagree.  I can’t tell if he is in fact boasting that the Ruby community is in general smarter, but the PHP community includes some of the brightest and veteran software developers in the world.  It is also one of the most diverse, in terms of skillset, and thus is also one of the most welcoming and open technology communities around.  Maybe he means that diversity is a disadvantage, which I also would disagree with.  Anecdotally, the Ruby community is often perceived of as elitist and prone to groupthink.  I believe that these are qualities of a very immature community, one that has not healthily fragmented or penetrated the corporate world.  The PHP community is older and has experienced this fragmentation, which seems to be exactly what the author is criticizing. Just wait, Ruby. Just wait.

4. Rails

Creating a web application complete with database is as easy as typing in a few simple commands. The web app framework community for PHP, on the other hand, is fragmented and far less organized.

Basically agree.  It is true that Ruby as a whole has embraced a single framework thus enjoying the advantages that have resulted.  Would PHP have enjoyed the same benefits had it settled on a single framework early on?  Impossible to know.  I predict that over time, the Ruby web frameworks will become fragmented and less organized as well.

5. Objected Oriented Programming

Ruby was initially designed to be object-oriented. Robust, organized programs are easier to create with an object oriented language.

Basically agree.  It is of course possible to write very good object-oriented code in PHP, but Ruby provides less rope to hang yourself with.

6. ActiveRecord design

using Rails, it is possible to map database records/tables to objects, which makes creating and handling persistent data extremely easy.

Basically agree.  Like point #4 above, there are plenty of good ActiveRecord libraries for PHP, but having a single, agreed-upon ORM to go with your single, agreed-upon MVC framework lends many advantages.

7. Easier to install

Gem makes it extremely easy to download and install different frameworks and applications to use in your code. PHP, however, makes you find, download, install, and configure all extensions yourself.

Disagree.  This should not even be on this list.  I see no real advantages of gem over pear.  Furthermore, I have seen some really hairy gem problems involving paths and multiple installations.

8. MVC

The model view controller architecture is a common system that all software engineers use. Rails is designed around this concept, so it gives future maintainers of your project an advantage when trying to understand your code.

Basically agree.  See points #4 and #6 above.  As I type this, points #4, #6, and #8 could be combined into a single item.

9. JVM support

Whenever there is a JVM installed, you can use JRuby to run your programs. You can also integrate your project into a Java application if you would like. This is especially useful if you are already writing a large application in Java, and are just looking for a scripting language to augment some functionality.

Agree.  I have no experience with either JRuby or Quercus, but JRuby appears to have achieved more maturity and popularity faster than Quercus.

10. Formal namespaces

Organizing code is much easier when you can group classes into namespaces.

Disagree.  PHP 5.3 fully supports namespaces.  Personally, I have always questioned the value of namespacing.  It always seemed more confusing to have identically named entities in different namespaces than to just prefix them and call them different things – which is what you have to do in PHP 5.2.

11. Pre-installed on certain operating systems

It ships with OSX 10.5 (Leopard), so you can get started coding immediately.

Disagree.  It sounds like he is referring to local installations, and not deployed installations, but in either case I would disagree.  OSX comes with PHP as well.  And PHP comes installed on every Linux distro currently made, so I really don’t understand this one at all.   If he is referring to deployed installations, PHP is still installed on more hosting environments than any other language, and it is easier to get running than any other language.  Passenger is slowly mitigating this situation, but PHP still is in front.

12. Interactive shell

It comes default with a robust interactive shell that makes it easy to experiment with code. Instead of typing out some code, saving it to your sever, opening up your internet browser, and navigating to your page, you can just open up the console and type.

Agree.  PHP has `php -a`, but it is no where near as usable as IRB.

13. Maintainability

Less code (assuming the complexity is the same) means there is less to get confused about. Forcing MVC on you (through Rails) also helps developers maintain your code. Unit testing has also been tightly integrated from the beginning of the language, so it is more convenient to create/use unit tests for regression tests.

Basically agree.  I am now combining points #4, #6, #8, and #13.

14. Everything is an object

Not having primitives makes code easier to handle. Instead of making sure something is an object and then executing it’s methods, one can just execute the method.

Agree.  If you start treating everything as an object, your business model starts becoming cleaner.  I’d much rather write “hello world”.lower than strtolower(“hello world”).

:::

Right about now is when I might conclude with: “every situation is different and the proper solution depends on your particular requirements, blah, blah, blah.” I basically agree with that statement, but in my experience, it is missing the point. 

In my experience, one can pretty much do anything with one platform that one can do with another.  One (web) technology may be faster or easier, but in the end, it’s all just web.  In my experience, most people are not equally strong in more than one platform.  Most people are stronger in one language, even if it is because it is the language most recently used. 

So back to the “every situation is different…” statement.  The particular requirements are usually, how can I make the business money?  Then, the proper solution becomes: by using the platform I know the best, and that is already running, formal namespaces be damned.