rulururu

post An Attempt at Restricted Auto-Login

July 4th, 2008

Filed under: Code,PHP — Brenton Alker @ 16:33

The system I have been building is a direct marketing system (don’t hate me, it’s opt-in) and to be compliant with their ethics policy it requires “2 click unsubscribe” functionality from all its email campaigns; 1 click on the link in the email, and 1 click on a big “Don’t Ever Send Me Email Again” button. So people actually have an option to opt out at any time, as any good (and I use that word in the relative sense) email marketing system should.

The problem this poses for me though, is how can I let a member unsubscribe without authenticating themselves? Authentication would take more than 2 clicks! The obvious solution is to not require authentication by simply adding the members identifier (email address, user name, database id, whatever can identify them uniquely) to the link. So I would have a URL something like:

http://example.com/member/unsubscribe?member=1234

And simply make all the options on that page act on the member identified by the identifier. Great! Until a malicious netizen comes along, seeing the scheme decides to systematically unsubscribe all my members. This would be achieved easily by guessing the identifiers, made even easier because they’re sequential, and clicking the unsubscribe button.

The initial solution is to use some other “key” in the link, one that is not so easy to guess. So a key was added, giving the url a form like:

http://example.com/member/unsubscribe?member=1234&key=SECRETKEY

Were SECRETKEY is a key they is generated randomly when the user signs up and stored with their account details. Using this, the system would allow a user to log in simply by clicking the link, they could then unsubscribe.

The problem being, of course, that by simply logging the user into their account anyone who has the link has full access to the account without needing to know any more information. So they could then read (and change) email addresses, passwords etc. Not ideal.

My solution has been to take the key a step further, and limit it to only the intended page. In this case the unsubscribe page. So my new url looks like this:

http://example.com/member/unsubscribe?token=1234:HASH

I’ve removed the member variable and combined it into a delimited token. This was mainly because I thought it looked a little nicer, it would function just as well as a separate variable. The real change is in the HASH. The new hash still uses the SECRETKEY that was used in the previous iteration, except it is now combined with the url that I want to give them access to, and an added salt so all tokens can be invalidated if required. In PHP, this looks something like this:

$allowedUrl = '/member/unsubscribe';
$hash = md5($salt . $allowedUrl . ':' . $secretKey);
$token = $id . ':' . $hash;

On the page, to allow access, the token is decomposed, the member’s identifier extracted, and their key retrieved. Their key is then used in the same process to generate a hash for the URL they are requesting. If the hashes match, they have access. To make it a little more user friendly, the allowed URL is added to their session, so they still have access to the page even if they lose the token from the URL. If they hit any other page with the restricted URL in their session they are logged out and sent back to re-authenticate.

One shortfall that I am aware of, and that was pointed out in a discussion on #phpc, is the members secret keys should ideally be rotated, so it can only be used once. This would mean that stealing a link would at worst allow one login, and only to one page. This may be implemented if it doesn’t impact too much on usability (that classic trade-off, security vs. convenience).

Now, I am not a security expert and as such don’t recommend anyone take my advice (is this good enough for a disclaimer), but apart from the one caveat mentioned, I think this solution meets the requirements without forfeiting too much in security. Any comments or advice on the technique are, as always, appreciated.

post Updated Extension to Zend Framework’s ViewRenderer to Add Layouts

September 19th, 2007

Filed under: Code,PHP,Zend Framework — Brenton Alker @ 13:33

A few months back, when I was first starting with the Zend Framework, I posted my extension to the ViewRenderer helper. This is the helper that the Controller uses to work with the View. My extension was in order to implement site-wide and controller-wide layouts, allowing a consistent look and feel in an application.

I have been fairly happily using this extension since then, more recently though, I got back to fixing some problems with it. One problem I noted (and updated the previous post to reflect), was it’s double calling of the action. After further investigation, it turns out it wasn’t calling it twice, but had an image with an empty src tag in the layout, causing the browser to request the page twice.

However, It still gave me an excuse to have another look at it, and fix up some other issues. So here I am posting the revised code. If you are using the old one, it isn’t backwards compatible, but there isn’t much to change and I think it’s a much nicer implementation. It uses a stack to render the layouts in order, and is therefore much more extensible to multi-level layouts.

class Custom_Controller_Action_Helper_ViewRenderer extends Zend_Controller_Action_Helper_ViewRenderer
{
    /**
     * Defaults stack of layout scripts, listed with the innermost
     * layout first.
     *
     * @var array
     */
    protected $_defaultStack = array(
        ':controller/layout',
        'layout',
    );

    /**
     * The stack of layout scripts, listed with the innermost first.
     *
     * @var array
     */
    protected $_stack = null;

    /**
     * If the layouts should be rendered or not
     *
     * @var boolean
     */
    protected $_renderLayout = true;

    /**
     * Constructor
     *
     * Set the viewSuffix to "tpl.php" unless a viewSuffix option is
     * provided in the $options parameter. And set the stack to the default
     *
     * @param  Zend_View_Interface $view
     * @param  array $options
     * @return void
     */
    public function __construct(Zend_View_Interface $view = null, array $options = array())
    {
        if (!isset($options['viewSuffix'])) {
            $options['viewSuffix'] = 'tpl.php';
        }
        parent::__construct($view, $options);

        $this->_stack = $this->_defaultStack;
    }

    /**
     * Add a layout to the stack
     *
     * Add a layout to be rendered inside the current stack
     * of layouts
     *
     * @see Zend_Controller_Action_Helper_ViewRenderer::_translateSpec()
     *
     * @param	string	The filename, possibly using variables as described for _translateSpec(...)
     *
     * @return	boolean	The same as array_unshift
     */
    public function addLayout($script)
    {
        return array_unshift($this->_stack, $script);
    }

    /**
     * Clears the layout stack, removing the default stack and any
     * layouts that have been added.
     *
     * @return array	The previous layout stack
     */
    public function clearLayout()
    {
        $stack = $this->_stack;
        $this->_stack = array();
        return $stack;
    }

    /**
     * Render the action script, then each of the layouts in the stack in
     * order, assigning the content of each to the content variable in
     * the next. Append the result to the Response's body.
     *
     * @param string $script
     * @param string $name		The response segment to append to
     */
    public function renderScript($script, $name = null)
    {
        $this->view->baseUrl = $this->_request->getBaseUrl();
        if (null === $name) {
            $name = $this->getResponseSegment();
        }

        // get the content of the action
        $content = $this->view->render($script);
        $this->view->content = $content;

        if ($this->_renderLayout) {
            foreach ($this->_stack as $layout) {
                $layoutScript = $this->_translateSpec($layout.'.:suffix');
                $content = $this->view->render($layoutScript);
                $this->view->content = $content;
	        }
        }

        $this->getResponse()->appendBody($content, $name);
    }

    /**
     * Enable, or disable the rendering of layouts
     *
     * @param boolean	Whether the layouts should be rendered or not
     */
    public function setLayoutEnabled($enabled = true)
    {
        $this->_renderLayout = $enabled;
    }
}

The implementation in the view script is very similar to the previous incarnation, except the view is no longer responsible for rendering the children itself, this is done beforehand, and is passed to the layout in the "content" variable. Leaving the layout to look something like:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title><?php echo (isset($this->title)) ? $this->escape($this->title) : 'Untitled'; ?></title>
</head>
    <body>
        <?php echo $this->content; ?>
    </body>
</html>

And, unlike the previous version, all levels of layout work the same way. So the controller layout would look like this:

<h1>Default Controller</h1>
<h2><?php echo $this->escape($this->title); ?></h2>
<?php echo $this->content; ?>

To use these layouts, they can be added to the stack, like so (from the controller):

$this->_helper->viewRenderer->clearLayout(); // clear the existing layouts
$this->_helper->viewRenderer->addLayout(':controller/layout');
$this->_helper->viewRenderer->addLayout('layout');

But this is the default anyway.

Until the Zend framework standardizes the layout situation, with Zend_View_Enhanced or Zend_Layout, or any combination thereof, this method will feature in my applications.

post Extending Zend Framework’s ViewRenderer Helper to Allow Application and Controller Page Layouts

June 26th, 2007

Filed under: Code,PHP,Zend Framework — Brenton Alker @ 01:48

I intend to do a write-up of my experiences choosing a PHP framework, but for now, I just thought I would share this.

One of the out-of-the-box features that the Zend Framework is missing is "layouts". These are the templates that contain the elements that are present on every (or at least almost every) page of the application. Things like headers, main menu’s, footers etc.

I looked at a number of different ways to implement this in Zend, the most obvious idea involves adding header and footer calls (possible a helper) in every view. While this will work, it is a lot of duplicated code.

Maugrim the Reaper’s blog contains a fairly comprehensive investigation (in 6 parts so far, the 7th hopefully coming soon) into "Complex Views". Unfortunately, there is not (as yet) any solid implementation of most of the concepts available there, but it does provide much to think about.

The most elegant implementation (IMHO) of a layout system to meet my needs that I have found (and believe me I’ve looked) comes from Akra’s Devnotes and involves extending the ViewRenderer Action Helper to render the layout template.

This works very similarly to my initial stab at an implementation, but does so in a much cleaner way (I initially had separate top and bottom templates, instead of the call to render the content in the layout). However, it does lack one feature that my implementation had, it only allows application level layouts. I also implemented controller level layouts; A 3-level view structure.

This allows the controllers to contain their own structure within the applications main structure. I extended Rob’s class (as in added to, not in the OO sense) to incorporate this 3-level view structure.

My current code looks like this:

<?php
class Custom_Controller_Action_Helper_ViewRenderer extends Zend_Controller_Action_Helper_ViewRenderer
{
    /**
     * Name of layout script to render. Defaults to 'layout'.
     *
     * @var string
     */
    protected $_layoutScript = 'layout.tpl.php';

    /**
     * Constructor
     *
     * Set the viewSuffix to "tpl.php" unless a viewSuffix option is
     * provided in the $options parameter.
     *
     * @param  Zend_View_Interface $view
     * @param  array $options
     * @return void
     */
    public function __construct(Zend_View_Interface $view = null,
                                array $options = array())
    {
        if (!isset($options['viewSuffix'])) {
            $options['viewSuffix'] = 'tpl.php';
        }
        parent::__construct($view, $options);
    }

    /**
     * Set the layout script to be rendered.
     *
     * @param string $script
     */
    public function setLayoutScript($script)
    {
        $this->_layoutScript = $script;
    }

    /**
     * Retreive the name of the layout script to be rendered.
     *
     * @return string
     */
    public function getLayoutScript()
    {
        return $this->_layoutScript;
    }

    /**
     * Render the action script and assign the the view for use
     * in the layout script. Render the layout script and append
     * to the Response's body.
     *
     * @param string $script
     * @param string $name
     */
    public function renderScript($script, $name = null)
    {
        $this->view->baseUrl = $this->_request->getBaseUrl();
        if (null === $name) {
            $name = $this->getResponseSegment();
        }

        //assign controller script name to view
        $this->view->controllerScript = $this->_translateSpec(':controller/' . $this->_layoutScript);

        // assign action script name to view.
        $this->view->actionScript = $script;

        // render layout script and append to Response's body
        $layoutScript = $this->getLayoutScript();
        $layoutContent = $this->view->render($layoutScript);
        $this->getResponse()->appendBody($layoutContent, $name);

        $this->setNoRender();
    }
}

As an example of its use:

The Application Layout (views/scripts/layout.tpl.php) looks like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title><?php echo (isset($this->title)) ? $this->escape($this->title) : 'Untitled'; ?></title>
</head>
    <body>
        <?php echo $this->render($this->controllerScript); ?>
    </body>
</html>

The Controller (for the default "index" controller) layout (views/scripts/index/layout.tpl.php) looks like this:

<h1>Default Controller</h1>
<h2><?php echo $this->escape($this->title); ?></h2>
<?php echo $this->render($this->actionScript); ?>

And that of course leaves the action’s view to only display the items specific to that action.

UPDATE:
This code is broken. During some debugging, I discovered that this method of calling the render function from the view causes the action function to be run twice. It also prevents the action function (or view) from manipulating variables that can be used by the layout script, so preventing things like the action requesting javascript or stylesheet includes in the html head section.

I have re-worked the script to overcome these problems, and will post it soon.

ruldrurd
« Previous PageNext Page »
Powered by WordPress, Web Design by Laurentiu Piron Monitored by SiteUpTime
Entries (RSS) and Comments (RSS)