Doorman – Limit access to your Laravel applications through invite codes

Doorman is a Laravel package that allows you to limit access to your Laravel applications by using invite codes.

Once installed you can generate and redeem invites through the Doorman facade and it includes support for Form Request validation.

You can generate new invites like this:

// Generate a single invite
Doorman::generate()->make();

// Generate five invites
Doorman::generate()->times(5)->make();

// Make an invite that expires on a specific date.
$date = Carbon::now('UTC')->addDays(7);
Doorman::generate()->expiresOn($date)->make();

// Make an invite that expires in 14 days.
Doorman::generate()->expiresIn(14)->make();

// Or even bind it to a specific person
Doorman::generate()->for('me@example.org')->make();

Redeeming is just as simple:

Doorman::redeem('ABCDE');
// or
Doorman::redeem('ABCDE', 'me@example.org');

If you’d like to start a private invite system to your app check out the Doorman package on Github.

Source: Laravel News

MarkdownMail – A Web App to Create Laravel Markdown Email Themes

MarkdownMail is a new web app that allows you to create markdown email themes for you Laravel apps. You register and login with Github and create a new theme. Next, it gives you a demo email and options on the left side to edit the colors:

Once you are satisfied you can export as HTML or a Laravel Theme.

MarkdownMail is free to use and will save you a lot of time in building those emails. Give it a try!

Source: Laravel News

Manage permissions with zend-permissions-rbac

In our previous post, we
covered authentication of a user via Expressive middleware. In that post, we
indicated that we would later discuss authorization, which is the activity of
checking if an authenticated user has permissions to perform a specific
action, from within the context of a middleware application.

Before we do that, however, we thought we’d introduce
zend-permissions-rbac,
our lightweight role-based access control (RBAC) implementation.

Installing zend-permissions-rbac

Just as you would any of our components, install zend-permissions-rbac via
Composer:

$ composer require zendframework/zend-permissions-rbac

The component has no requirements at this time other than a PHP version of at
least 5.5.

Vocabulary

In RBAC systems, we have three primary items to track:

  • the RBAC system composes zero or more roles.
  • a role is granted zero or more permissions.
  • we assert whether or not a role is granted a given permission.

zend-permissions-rbac supports role inheritance, even allowing a role to inherit
permissions from multiple other roles. This allows you to create some fairly
complex and fine-grained permissions schemes!

Basics

As a basic example, we’ll create an RBAC for a content-based website. Let’s
start with a "guest" role, that only allows "read" permissions.

use ZendPermissionsRbacRbac;
use ZendPermissionsRbacRole;

// Create some roles
$guest= new Role('guest');
$guest>addPermission('read');

$rbac = new Rbac();
$rbac->addRole($guest);

We can then assert if a given role is granted specific permissions:

$rbac->isGranted('guest', 'read'); // true
$rbac->isGranted('guest', 'write'); // false

Unknown roles

One thing to note: if the role used with isGranted() does not exist, this
method raises an exception, specifically a
ZendPermissionsRbacExceptionInvalidArgumentException, indicating the
role could not be found.

In many situations, this may not be what you want; you may want to handle
non-existent roles gracefully. You could do this in a couple ways. First, you
can test to see if the role exists before you check the permissions, using
hasRole():

if (! $rbac->hasRole($foo)) {
    // failed, due to missing role
}
if (! $rbac->isGranted($foo, $permission)) {
    // failed, due to missing permissions
}

Alternately, wrap the isGranted() call in a try/catch block:

try {
    if (! $rbac->isGranted($foo, $permission)) {
        // failed, due to missing permissions
    }
} catch (RbacInvalidArgumentException $e) {
    if (! strstr($e->getMessage(), 'could be found')) {
        // failed, due to missing role
    }

    // some other error occured
    throw $e;
}

Personally, I don’t like to use exceptions for application flow, so I
recommend the first solution. That said, in most cases, you will be working
with a role instance that you’ve just added to the RBAC.

Role inheritance

Let’s say we want to build on the previous example, and create an "editor" role
that also incorporates the permissions of the "guest" role, and adds a "write"
permission.

You might be inclined to think of the "editor" as inheriting from the "guest"
role — in other words, that it is a descendent or child of it.
However, in RBAC, inheritance works in the opposite direction: a parent
inherits all permissions of its children. As such, we’ll create the role as
follows:

$editor = new Role('editor');
$editor->addChild('guest');
$editor->addPermission('write');

$rbac->addRole($editor);

$rbac->isGranted('editor', 'write'); // true
$rbac->isGranted('editor', 'read');  // true
$rbac->isGranted('guest',  'write'); // false

Another role might be a "reviewer" who can "moderate" content:

$reviewer = new Role('reviewer');
$reviewer->addChild('guest');
$reviewer->addPermission('moderate');

$rbac->addRole($reviewer);

$rbac->isGranted('reviewer', 'moderate'); // true
$rbac->isGranted('reviewer', 'write');    // false; editor only!
$rbac->isGranted('reviewer', 'read');     // true
$rbac->isGranted('guest',    'moderate'); // false

Let’s create another, an "admin" who can do all of the above, but also has
permissions for "settings":

$admin= new Role('admin');
$admin->addChild('editor');
$admin->addChild('reviewer');
$admin->addPermission('settings');

$rbac->addRole($admin);

$rbac->isGranted('admin',    'settings'); // true
$rbac->isGranted('admin',    'write');    // true
$rbac->isGranted('admin',    'moderate'); // true
$rbac->isGranted('admin',    'read');     // true
$rbac->isGranted('editor',   'settings'); // false
$rbac->isGranted('reviewer', 'settings'); // false
$rbac->isGranted('guest',    'write');    // false

As you can see, permissions lookups are recursive and collective; the RBAC
examines all children and each of their descendants as far down as it needs to
determine if a given permission is granted!

Creating your RBAC

When should you create your RBAC, exactly? And should it contain all roles and
permissions?

In most cases, you will be validating a single user’s permissions. What’s
interesting about zend-permissions-rbac is that if you know that user’s role,
the permissions they have been assigned, and any child roles (and their
permissions) to which the role belongs, you have everything you need. This means
that you can do most lookups on-the-fly.

As such, you will typically do the following:

  • Create a finite set of well-known roles and their permissions as a global RBAC.
  • Add roles (and optionally permissions) for the current user.
  • Validate the current user against the RBAC.

As an example, let’s say I have a user Mario who has the role "editor", and also
adds the permission "update". If our RBAC is already populated per the above
examples, I might do the following:

$mario= new Role('mario');
$mario->addChild('editor');
$mario->addPermission('update');

$rbac->addRole($mario);

$rbac->isGranted($mario,   'settings'); // false; admin only!
$rbac->isGranted($mario,   'update');   // true; mario only!
$rbac->isGranted('editor', 'update');   // false; mario only!
$rbac->isGranted($mario,   'write');    // true; all editors
$rbac->isGranted($mario,   'read');     // true; all guests

Assigning roles to users

When you have some sort of authentication system in place, it will return some
sort of identity or user instance generally. You will then need to map this
to RBAC roles. But how?

Hopefully, you can store role information wherever you persist your user
information. Since roles are essentially stored internally as strings by
zend-permissions-rbac, this means that you can store the user role as a discrete
datum with your user identity.

Once you have, you have a few options:

  • Use the role directly from your identity when checking permissions: e.g.,
    $rbac->isGranted($identity->getRole(), 'write')
  • Create a ZendPermissionsRbacRole instance (or other concrete class) with
    the role fetched from the identity, and use that for permissions checks:
    $rbac->isGranted(new Role($identity->getRole()), 'write')
  • Update your identity instance to implement
    ZendPermissionsRbacRoleInterface, and pass it directly to permissions
    checks: $rbac->isGranted($identity, 'write')

This latter approach provides a nice solution, as it then also allows you to
store specific permissions and/or child roles as part of the user data.

The RoleInterface looks like the following:

namespace ZendPermissionsRbac;

use RecursiveIterator;

interface RoleInterface extends RecursiveIterator
{
    /**
     * Get the name of the role.
     *
     * @return string
     */
    public function getName();

    /**
     * Add permission to the role.
     *
     * @param $name
     * @return RoleInterface
     */
    public function addPermission($name);

    /**
     * Checks if a permission exists for this role or any child roles.
     *
     * @param  string $name
     * @return bool
     */
    public function hasPermission($name);

    /**
     * Add a child.
     *
     * @param  RoleInterface|string $child
     * @return Role
     */
    public function addChild($child);

    /**
     * @param  RoleInterface $parent
     * @return RoleInterface
     */
    public function setParent($parent);

    /**
     * @return null|RoleInterface
     */
    public function getParent();
}

The ZendPermissionsRbacAbstractRole contains basic implementations of most
methods of the interface, including logic for querying child permissions, so we
suggest inheriting from that if you can.

As an example, you could store the permissions as a comma-separated string and
the parent role as a string internally when creating your identity instance:

use ZendPermissionsRbacAbstractRole;
use ZendPermissionsRbacRoleInterface;
use ZendPermissionsRbacRole;

class Identity extends AbstractRole
{
    /**
     * @param string $username
     * @param string $role
     * @param array $permissions
     * @param array $childRoles
     */
    public function __construct(
        string $username,
        array $permissions = [],
        array $childRoles = []
    ) {
        // $name is defined in AbstractRole
        $this->name = $username;

        foreach ($this->permissions as $permission) {
            $this->addPermission($permission);
        }

        $childRoles = array_merge(['guest'], $childRoles);
        foreach ($this->childRoles as $childRole) {
            $this->addChild($childRole);
        }
    }
}

Assuming your authentication system uses a database table, and a lookup returns
an array-like row with the user information on a successful lookup, you might
then seed your identity instance as follows:

$identity = new Identity(
    $row['username'],
    explode(',', $row['permissions']),
    explode(',', $row['roles'])
);

This approach allows you to assign pre-determined roles to individual users,
while also allowing you to add fine-grained, individual permissions!

Custom assertions

Sometimes a static assertion is not enough.

As an example, we may want to implement a rule that the creator of a content
item in our website always has rights to edit the item. How would we implement
that with the above system?

zend-permissions-rbac allows you to do so via dynamic assertions. Such
assertions are classes that implement
ZendPermissionsRbacAssertionInterface, which defines the single method
public function assert(Rbac $rbac).

For the sake of this example, let’s assume:

  • The content item is represented as an object.
  • The object has a method getCreatorUsername() that will return the same
    username as we might have in our custom identity from the previous example.

Because we have PHP 7 at our disposal, we’ll create the assertion as an
anonymous class:

use ZendPermissionsRbacAssertionInterface;
use ZendPermissionsRbacRbac;
use ZendPermissionsRbacRoleInterface;

$assertion = new class ($identity, $content) implements AssertionInterface {
    private $content;
    private $identity;

    public function __construct(RoleInterface $identity, $content)
    {
        $this->identity = $identity;
        $this->content = $content;
    }

    public function assert(Rbac $rbac)
    {
        return $this->identity->getName() === $this->content->getCreatorUsername();
    }
};

$rbac->isGranted($mario, 'edit', $assertion); // returns true if $mario created $content

This opens even more possibilities than inheritance!

Summary

zend-permissions-rbac is quite simple to operate, but that simplicity hides a
great amount of flexibility and power; you can create incredibly fine-grained
permissions schemes for your applications using this component!

Next week, Enrico will cover using the component within a middleware stack; stay
tuned!

Save the date!

Want to learn more about Expressive and Zend Framework? What better location
than ZendCon 2017! ZendCon will be hosted 23-26 October 2017 in Las Vegas,
Nevada, USA. Visit the ZendCon website for more
information
.

Source: Zend feed

PHP Roundtable – Laravel Edition

Today the PHP Roundtable had a Laravel inspired edition featuring Taylor Otwell, Mohamed Said, Jeffrey Way, Adam Wathan, and Dries Vints.

The crew discussed the overall mission with Laravel, getting started with the framework, the ecosystem and more. You can watch it on YouTube below or on your podcast of choice once they get it all compressed down.

Source: Laravel News

Middleware authentication

Many web applications require restricting specific areas to authenticated
users, and may further restrict specific actions to authorized user roles.
Implementing authentication and authorization in a PHP application is often
non-trivial as doing so requires altering the application workflow. For
instance, if you have an MVC design, you may need to change the dispatch logic
to add an authentication layer as an initial event in the execution flow, and
perhaps apply restrictions within your controllers.

Using a middleware approach is simpler and more natural, as middleware easily
accommodates workflow changes. In this article, we will demonstrate how to
provide authentication in a PSR-7 middleware application using
Expressive and
zend-authentication. We
will build a simple authentication system using a login page with username and
password credentials.

Since the content of this post is quite long, we’ll detail authorization
in a separate blog post.

Getting started

This article assumes you have already created an Expressive application. For the
purposes of our application, we’ll create a new module, Auth, in which we’ll
put our classes, middleware, and general configuration.

First, if you have not already, install the tooling support:

$ composer require --dev zendframework/zend-expressive-tooling

Next, we’ll create the Auth module:

$ ./vendor/bin/expressive module:create Auth

With that out of the way, we can get started.

Authentication

The zend-authentication component offers an adapter-based authentication
solution, with both a number of concrete adapters as well as mechanisms for
creating and consuming custom adapters.

The component exposes ZendAuthenticationAdapterAdapterInterface, which
defines a single authenticate() method:

namespace ZendAuthenticationAdapter;

interface AdapterInterface
{
    /**
     * Performs an authentication attempt
     *
     * @return ZendAuthenticationResult
     * @throws ExceptionExceptionInterface if authentication cannot be performed
     */
    public function authenticate();
}

Adapters implementing the authenticate() method perform the logic necessary to
authenticate a request, and return the results via a
ZendAuthenticationResult object. This Result object contains the
authentication result code and, in the case of success, the user’s identity.
The authentication result codes are defined using the following constants:

namespace ZendAuthentication;

class Result
{
    const SUCCESS = 1;
    const FAILURE = 0;
    const FAILURE_IDENTITY_NOT_FOUND = -1;
    const FAILURE_IDENTITY_AMBIGUOUS = -2;
    const FAILURE_CREDENTIAL_INVALID = -3;
    const FAILURE_UNCATEGORIZED = -4;
}

If we want to implement a login page with username and password
authentication, we can create a custom adapter such as the following:

// In src/Auth/src/MyAuthAdapter.php:

namespace Auth;

use ZendAuthenticationAdapterAdapterInterface;
use ZendAuthenticationResult;

class MyAuthAdapter implements AdapterInterface
{
    private $password;
    private $username;

    public function __construct(/* any dependencies */)
    {
        // Likely assign dependencies to properties
    }

    public function setPassword(string $password) : void
    {
        $this->password = $password;
    }

    public function setUsername(string $username) : void
    {
        $this->username = $username;
    }

    /**
     * Performs an authentication attempt
     *
     * @return Result
     */
    public function authenticate()
    {
        // Retrieve the user's information (e.g. from a database)
        // and store the result in $row (e.g. associative array).
        // If you do something like this, always store the passwords using the
        // PHP password_hash() function!

        if (password_verify($this->password, $row['password'])) {
            return new Result(Result::SUCCESS, $row);
        }

        return new Result(Result::FAILURE_CREDENTIAL_INVALID, $this->username);
    }
}

We will want a factory for this service as well, so that we can seed the
username and password to it later:

// In src/Auth/src/MyAuthAdapterFactory.php:

namespace Auth;

use InteropContainerContainerInterface;
use ZendAuthenticationAuthenticationService;

class MyAuthAdapterFactory
{
    public function __invoke(ContainerInterface $container)
    {
        // Retrieve any dependencies from the container when creating the instance
        return new MyAuthAdapter(/* any dependencies */);
    }
}

This factory class creates and returns an instance of MyAuthAdapter.
We may need to pass some dependencies to its constructor, such as a database
connection; these would be fetched from the container.

Authentication Service

We can now create a ZendAuthenticationAuthenticationService
that composes our adapter, and then consume the AuthenticationService in
middleware to check for a valid user. Let’s now create a factory for the
AuthenticationService:

// in src/Auth/src/AuthenticationServiceFactory.php:

namespace Auth;

use InteropContainerContainerInterface;
use ZendAuthenticationAuthenticationService;

class AuthenticationServiceFactory
{
    public function __invoke(ContainerInterface $container)
    {
        return new AuthenticationService(
            null,
            $container->get(MyAuthAdapter::class)
        );
    }
}

This factory class retrieves an instance of the MyAuthAdapter service and use
it to return an AuthenticationService instance. The AuthenticationService
class accepts two parameters:

  • A storage service instance, for persisting the user identity. If none is
    provided, the built-in PHP session mechanisms will be used.
  • The actual adapter to use for authentication.

Now that we have created both the custom adapter, as well as factories for the
adapter and the AuthenticationService, we need to configure our application
dependencies to use them:

// In src/Auth/src/ConfigProvider.php:

// Add the following import statement at the top of the classfile:
use ZendAuthenticationAuthenticationService;

// And update the following method:
public function getDependencies()
{
    return [
        'factories' => [
            AuthenticationService::class => AuthenticationServiceFactory::class,
            MyAuthAdapter::class => MyAuthAdapterFactory::class,
        ],
    ];
}

Authenticate using a login page

With an authentication mechanism in place, we now need to create middleware to
render the login form. This middleware will do the following:

  • for GET requests, it will render the login form.
  • for POST requests, it will check for credentials and then attempt to
    validate them.

    • for valid authentication requests, we will redirect to a welcome page
    • for invalid requests, we will provide an error message and redisplay the
      form.

Let’s create the middleware now:

// In src/Auth/src/Action/LoginAction.php:

namespace AuthAction;

use AuthMyAuthAdapter;
use InteropHttpServerMiddlewareDelegateInterface;
use InteropHttpServerMiddlewareMiddlewareInterface as ServerMiddlewareInterface;
use PsrHttpMessageServerRequestInterface;
use ZendAuthenticationAuthenticationService;
use ZendDiactorosResponseHtmlResponse;
use ZendDiactorosResponseRedirectResponse;
use ZendExpressiveTemplateTemplateRendererInterface;

class LoginAction implements ServerMiddlewareInterface
{
    private $auth;
    private $authAdapter;
    private $template;

    public function __construct(
        TemplateRendererInterface $template,
        AuthenticationService $auth,
        MyAuthAdapter $authAdapter
    ) {
        $this->template    = $template;
        $this->auth        = $auth;
        $this->authAdapter = $authAdapter;
    }

    public function process(ServerRequestInterface $request, DelegateInterface $delegate)
    {
        if ($request->getMethod() === 'POST') {
            return $this->authenticate($request);
        }

        return new HtmlResponse($this->template->render('auth::login'));
    }

    public function authenticate(ServerRequestInterface $request)
    {
        $params = $request->getParsedBody();

        if (empty($params['username'])) {
            return new HtmlResponse($this->template->render('auth::login', [
                'error' => 'The username cannot be empty',
            ]));
        }

        if (empty($params['password'])) {
            return new HtmlResponse($this->template->render('auth::login', [
                'username' => $params['username'],
                'error'    => 'The password cannot be empty',
            ]));
        }

        $this->authAdapter->setUsername($params['username']);
        $this->authAdapter->setPassword($params['password']);

        $result = $this->auth->authenticate();
        if (!$result->isValid()) {
            return new HtmlResponse($this->template->render('auth::login', [
                'username' => $params['username'],
                'error'    => 'The credentials provided are not valid',
            ]));
        }

        return new RedirectResponse('/admin');
    }
}

This middleware manages two actions: rendering the login form, and
authenticating the user’s credentials when submitted via a POST request.

You will also need to ensure that you have:

  • Created a login template.
  • Added configuration to map the auth template namespace to one or more
    filesystem paths.

We leave those tasks as an exercise to the reader.

We now need to create a factory to provide the dependencies for this
middleware:

// In src/Auth/src/Action/LoginActionFactory.php:

namespace AuthAction;

use AuthMyAuthAdapter;
use InteropContainerContainerInterface;
use ZendAuthenticationAuthenticationService;
use ZendExpressiveTemplateTemplateRendererInterface;

class LoginActionFactory
{
    public function __invoke(ContainerInterface $container)
    {
        return new LoginAction(
            $container->get(TemplateRendererInterface::class),
            $container->get(AuthenticationService::class),
            $container->get(MyAuthAdapter::class)
        );
    }
}

Map the middleware to this factory in your dependencies configuration witin the
ConfigProvider:

// In src/Auth/src/ConfigProvider.php,

// Update the following method to read as follows:
public function getDependencies()
{
    return [
        'factories' => [
            ActionLoginAction::class => ActionLoginActionFactory::class,
            AuthenticationService::class => AuthenticationServiceFactory::class,
            MyAuthAdapter::class => MyAuthAdapterFactory::class,
        ],
    ];
}

Use zend-servicemanager’s ReflectionBasedAbstractFactory

If you are using zend-servicemanager in your application, you could skip the
step of creating the factory, and instead map the middleware to
ZendServiceManagerAbstractFactoryReflectionBasedAbstractFactory.

Finally, we can create appropriate routes. We’ll map /login to the
LoginAction now, and allow it to react to either the GET or POST methods:

// in config/routes.php:
$app->route('/login', AuthActionLoginAction::class, ['GET', 'POST'], 'login');

Alternately, the above could be written as two separate statements:

// in config/routes.php:
$app->get('/login', AuthActionLoginAction::class, 'login');
$app->post('/login', AuthActionLoginAction::class);

Authentication middleware

Now that we have the authentication service and its adapter and the login
middleware in place, we can create middleware that checks for authenticated
users, having it redirect to the /login page if the user is not authenticated.

// In src/Auth/src/Action/AuthAction.php:

namespace AuthAction;

use InteropHttpServerMiddlewareDelegateInterface;
use InteropHttpServerMiddlewareMiddlewareInterface as ServerMiddlewareInterface;
use PsrHttpMessageServerRequestInterface;
use ZendAuthenticationAuthenticationService;
use ZendDiactorosResponseRedirectResponse;

class AuthAction implements ServerMiddlewareInterface
{
    private $auth;

    public function __construct(AuthenticationService $auth)
    {
        $this->auth = $auth;
    }

    public function process(ServerRequestInterface $request, DelegateInterface $delegate)
    {
        if (! $this->auth->hasIdentity()) {
            return new RedirectResponse('/login');
        }

        $identity = $this->auth->getIdentity();
        return $delegate->process($request->withAttribute(self::class, $identity));
    }
}

This middleware checks for a valid identity using the hasIdentity() method of
AuthenticationService. If no identity is present, we redirect the redirect
configuration value.

If the user is authenticated, we continue the execution of the next middleware,
storing the identity in a request attribute. This facilitates consumption of the
identity information in subsequent middleware layers. For instance, imagine you
need to retrieve the user’s information:

namespace AppAction;

use InteropHttpServerMiddlewareDelegateInterface;
use InteropHttpServerMiddlewareMiddlewareInterface as ServerMiddlewareInterface;
use PsrHttpMessageServerRequestInterface;

class FooAction
{
    public function process(ServerRequestInterface $request, DelegateInterface $delegate)
    {
        $user = $request->getAttribute(AuthAction::class);
        // $user will contains the user's identity
    }
}

The AuthAction middleware needs some dependencies, so we will need to create
and register a factory for it as well.

First, the factory:

// In src/Auth/src/Action/AuthActionFactory.php:

namespace AuthAction;

use InteropContainerContainerInterface;
use ZendAuthenticationAuthenticationService;
use Exception;

class AuthActionFactory
{
    public function __invoke(ContainerInterface $container)
    {
        return new AuthAction($container->get(AuthenticationService::class));
    }
}

And then mapping it:

// In src/Auth/src/ConfigProvider.php:


// Update the following method to read as follows:
public function getDependencies()
{
    return [
        'factories' => [
            ActionAuthAction::class => ActionAuthActionFactory::class,
            ActionLoginAction::class => ActionLoginActionFactory::class,
            AuthenticationService::class => AuthenticationServiceFactory::class,
            MyAuthAdapter::class => MyAuthAdapterFactory::class,
        ],
    ];
}

Like the LoginActionFactory above, you could skip the factory creation and
instead use the ReflectionBasedAbstractFactory if using zend-servicemanager.

Require authentication for specific routes

Now that we built the authentication middleware, we can use it to protect
specific routes that require authentication. For instance, for each route that
needs authentication, we can modify the routing to create a pipeline that
incorporates our AuthAction middleware early:

$app->get('/admin', [
    AuthActionAuthAction::class,
    AppActionDashBoardAction::class
], 'admin');

$app->get('/admin/config', [
    AuthActionAuthAction::class,
    AppActionConfigAction::class
], 'admin.config');

The order of execution for the middleware is the order of the array elements.
Since the AuthAction middleware is provided as the first element, if a user is
not authenticated when requesting either the admin dashboard or config page,
they will be immediately redirected to the login page instead.

Conclusion

There are many ways to accommodate authentication within middleware
applications; this is just one. Our goal was to demonstrate the ease with which
you may compose authentication into existing workflows by creating middleware
that intercepts the request early within a pipeline.

You could certainly make a number of improvements to the workflow:

  • The path to the login page could be configurable.
  • You could capture the original request path in order to allow redirecting to
    it following successful login.
  • You could introduce rate limiting of login requests.

These are each interesting exercises for you to try!

As noted in the introduction, this article demonstrates only authentication.
Stay tuned for a future article that will demonstrate authorization middleware
using zend-permissions-rbac.

Save the date!

Want to learn more about Expressive and Zend Framework? What better location
than ZendCon 2017! ZendCon will be hosted 23-26 October 2017 in Las Vegas,
Nevada, USA. Visit the ZendCon website for more
information
.

Source: Zend feed

Manage your application with zend-config-aggregator

With the rise of PHP middleware, many developers are creating custom
application architectures, and running into an issue many frameworks already
solve: how to allow runtime configuration of the application.

configuration is often necessary, even in custom applications:

  • Some configuration, such as API keys, may vary between environments.
  • You may want to substitute services between development and production.
  • Some code may be developed by other teams, and pulled into your application
    separately (perhaps via Composer), and require
    configuration.
  • You may be writing code in your application that you will later want to share
    with another team, and recognize it should provide service wiring information
    or allow for dynamic configuration itself.

Faced with this reality, you then have a new problem: how can you configure your
application, as well as aggregate configuration from other sources?

As part of the Expressive initiative, we now offer a standalone solution for
you: zend-config-aggregator

Installation

First, you will need to install zend-config-aggregator:

$ composer require zendframework/zend-config-aggregator

One feature of zend-config-aggregator is the ability to consume multiple
configuration formats via zend-config.
If you wish to use that feature, you will also need to install that package:

$ composer require zendframework/zend-config

Finally, if you are using the above, and want to parse YAML files, you will need
to install the YAML PECL extension.

Configuration providers

zend-config-aggregator allows you to aggregate configuration from configuration
providers. A configuration provider is any PHP callable that will return an
associative array of configuration.

By default, the component provides the following providers out of the box:

  • ZendConfigAggregatorArrayProvider, which accepts an array of configuration
    and simply returns it. This is primarily useful for providing global defaults
    for your application.
  • ZendConfigAggregatorPhpFileProvider, which accepts a glob pattern
    describing PHP files that each return an associative array. When invoked, it
    will loop through each file, and merge the results with what it has previously
    stored.
  • ZendConfigAggregatorZendConfigProvider, which acts similarly to the
    PhpFileProvider, but which can aggregate any format
    zend-config supports, including
    INI, XML, JSON, and YAML.

More interestingly, however, is the fact that you can write providers as simple
invokable objects:

namespace Acme;

class ConfigProvider
{
    public function __invoke()
    {
        return [
            // associative array of configuration
        ];
    }
}

This feature allows you to write configuration for specific application
features, and then seed your application with it. In other words, this feature
can be used as the foundation for a modular
architecture
,
which is exactly what we did with Expressive!

Generators

You may also use invokable classes or PHP callables that define generators as
configuration providers! As an example, the PhpFileProvider could
potentially be rewritten as follows:

use ZendStdlibGlob;

function () {
    foreach (Glob::glob('config/*.php', Glob::GLOB_BRACE) as $file) {
        yield include $file;
    }
}

Aggregating configuration

Now that you have configuration providers, you can aggregate them.

For the purposes of this example, we’ll assume the following:

  • We will have a single configuration file, config.php, at the root of our
    application which will aggregate all other configuration.
  • We have a number of configuration files under config/, including YAML, JSON,
    and PHP files.
  • We have a third-party "module" that exposes the class
    UmbrellaConfigProvider.
  • We have developed our own "module" for re-distribution that exposes the class
    BlanketConfigProvider.

Typically, you will want aggregate configuration such that third-party
configuration is loaded first, with application-specific configuration merged
last, in order to override settings.

Let’s aggregate and return our configuration.

// in config.php:
use ZendConfigAggregatorConfigAggregator;
use ZendConfigAggregatorZendConfigProvider;

$aggregator = new ConfigAggregator([
    UmbrellaConfigProvider::class,
    BlanketConfigProvider::class,
    new ZendConfigProvider('config/*.{json,yaml,php}'),
]);

return $aggregator->getMergedConfig();

This file aggregates the third-party configuration provider, the one we expose
in our own application, and then aggregates a variety of different configuration
files in order to, in the end, return an associative array representing the
merged configuration!

Valid config profider entries

You’ll note that the ConfigAggregator expects an array of providers as the
first argument to the constructor. This array may consist of any of the
following:

  • Any PHP callable (functions, invokable objects, closures, etc.) returning an
    array.
  • A class name of a class that defines __invoke(), and which requires no
    constructor arguments.

This latter is useful, as it helps reduce operational overhead once you
introduce caching, which we discuss below. The above example demonstrates this
usage.

zend-config and PHP configuration

The above example uses only the ZendConfigProvider, and not the
PhpFileProvider. This is due to the fact that zend-config can also consume
PHP configuration.

If you are only using PHP-based configuration files, you can use the
PhpFileProvider instead, as it does not require additionally installing the
zendframework/zend-config package.

Globbing and precedence

Globbing works as it does on most *nix systems. As such, you need to pay
particular attention to when you use patterns that define alternatives, such
as the {json,yaml,php} pattern above. In such cases, all JSON files will be
aggregated, followed by YAML files, and finally PHP files. If you need them
to aggregate in a different order, you will need to change the pattern.

Caching

You likely do not want to aggregate configuration on each and every application
request, particularly if doing so would result in many filesystem hits.
Fortunately, zend-config-aggregator also has built-in caching features.

To enable these features, you will need to do two things:

  • First, you need to provide a second argument to the ConfigAggregator
    constructor, specifying the path to the cache file to create and/or use.
  • Second, you need to enable caching in your configuration, by specifying a
    boolean true value for the key ConfigAggregator::ENABLE_CACHE.

One common strategy is to enable caching by default, and then disable it via
environment-specific configuration.

We’ll update the above example now to enable caching to the file
cache/config.php:

use ZendConfigAggregatorArrayProvider;
use ZendConfigAggregatorConfigAggregator;
use ZendConfigAggregatorPhpFileProvider;
use ZendConfigAggregatorZendConfigProvider;

$aggregator = new ConfigAggregator(
    [
        new ArrayProvider([ConfigAggregator::ENABLE_CACHE => true]),
        UmbrellaConfigProvider::class,
        BlanketConfigProvider::class,
        new ZendConfigProvider('config/{,*.}global.{json,yaml,php}'),
        new PhpFileProvider('config/{,*.}local.php'),
    ],
    'cache/config.php'
);

return $aggregator->getMergedConfig();

The above adds an initial setting that enables the cache, and tells it to cache
it to cache/config.php.

Notice also that this example changes the ZendConfigProvider, and adds a
PhpFileProvider entry. Let’s examine these.

The ZendConfigProvider glob pattern now looks for files named global with
one of the accepted extensions, or those named *.global with one of the
accepted extensions. This allows us to segregate configuration that should
always be present from environment-specific configuration.

We then add a PhpFileProvider that aggregates local.php and/or *.local.php
files specifically. An interesting side-note about the shipped providers is that
if no matching files are found, the provider will return an empty array; this
means that we can have this additional provider that is looking for separate
configurations for the "local" environment! Because this provider is aggregated
last, the settings it exposes will override any others.

As such, if we want to disable caching, we can create a file such as
config/local.php with the following contents:

<?php
use ZendConfigAggregatorConfigAggregator;

return [ConfigAggregator::ENABLE_CACHE => false];

and the application will no longer cache aggregated configuration!

Clear the cache!

The setting outlined above is used to determine whether the configuration
cache file should be created if it does not already exist.
zend-config-aggregator, when provided the location of a configuration cache
file, will load directly from it if the file is present.

As such, if you make the above configuration change, you will first need to
remove any cached configuration:

$ rm cache/config.php

This can even be made into a Composer script:

"scripts": {
    "clear-config-cache": "rm cache/config.php"
}

Allowing you to do this:

$ composer clear-config-cache

Which allows you to change the location of the cache file without needing to
re-learn the location every time you need to clear the cache.

Auto-enabling third-party providers

Being able to aggregate providers from third-parties is pretty stellar; it means
that you can be assured that configuration the third-party code expects is
generally present — with the exception of values that must be provided by the
consumer, that is!

However, there’s one minor problem: you need to remember to register these
configuration providers with your application, by manually editing your
config.php file and adding the appropriate entries.

Zend Framework solves this via the zf-component-installer Composer
plugin
. If your
package is installable via Composer, you can add an entry to your package
definition as follows:

"extra": {
    "zf": {
        "config-provider": [
            "UmbrellaConfigProvider"
        ]
    }
}

If the end-user:

  • Has required zendframework/zend-component-installer in their application (as
    either a production or development dependency), AND
  • has the config aggregation script in config/config.php

then the plugin will prompt you, asking if you would like to add each of the
config-provider entries found in the installed package into the configuration
script.

As such, for our example to work, we would need to move our configuration script
to config/config.php, and likely move our other configuration files into a
sub-directory:

cache/
    config.php
config/
    config.php
    autoload/
        blanket.global.yaml
        global.php
        umbrella.global.json

This approach is essentially that taken by Expressive.

When those changes are made, any package you add to your application that
exposes configuration providers will prompt you to add them to your
configuration aggregation, and, if you confirm, will add them to the top of the
script!

Final notes

First, we would like to thank Mateusz Tymek, whose
prototype ‘expressive-config-manager’ project became zend-config-aggregator.
This is a stellar example of a community project getting adopted into the
framework!

Second, this approach has some affinity to a proposal from the folks who brought
us PSR-11, which defines the ContainerInterface used within Expressive for
allowing usage of different dependency injection containers. That same group is
now working on a service provider
proposal that would standardize how standalone libraries expose services to
containers; we recommend looking at that project as well.

We hope that this post helps spawn ideas for configuring your next project!

Save the date!

Want to learn more about Expressive and Zend Framework? What better location
than ZendCon 2017! ZendCon will be hosted 23-26 October 2017 in Las Vegas,
Nevada, USA. Visit the ZendCon website for more
information
.

Source: Zend feed

Caching middleware with Expressive

Performance is one of the key feature for web application. Using a middleware
architecture makes it very simple to implement a caching system in PHP.

The general idea is to store the response output of a URL in a file (or in
memory, using memcached) and use it for subsequent
requests. In this way we can bypass the execution of the previous middlewares
starting from the second request.

Of course, this technique can only be applied for static contents, that does not
require update for each HTTP request.

Implement a caching middleware

Imagine we want to create a simple cache system with Expressive.
We can use an implementation like that:

namespace AppAction;

use InteropHttpServerMiddlewareDelegateInterface;
use InteropHttpServerMiddlewareMiddlewareInterface as ServerMiddlewareInterface;
use PsrHttpMessageServerRequestInterface;
use ZendDiactorosResponseHtmlResponse;

class CacheMiddleware implements ServerMiddlewareInterface
{
    protected $config;

    public function __construct(array $config)
    {
        $this->config = $config;
    }

    public function process(ServerRequestInterface $request, DelegateInterface $delegate)
    {
        $url  = str_replace('/', '_', $request->getUri()->getPath());
        $file = $this->config['path'] . $url . '.html';
        if ($this->config['enabled'] && file_exists($file) &&
            (time() - filemtime($file)) < $this->config['lifetime']) {
            return new HtmlResponse(file_get_contents($file));
        }

        $response = $delegate->process($request);
        if ($response instanceof HtmlResponse && $this->config['enabled']) {
            file_put_contents($file, $response->getBody());
        }
        return $response;
    }
}

In this example, we used the PSR-15
proposal to implement the Middleware interface using the process() function.
This is the suggested way to implement middleware in Expressive 2.0.

The idea of this middleware is quite simple. If the caching system is enabled
and if the requested URL matches an existing cache file, we return the cache
content as HtmlResponse,
ending the execution flow.

If the requested URL path does not exist in cache, we process the delegate
middleware (basically we continue with the normal workflow) and we store the
response in the cache, if enabled.

Configure the cache system

To manage the cache, we used a configuration key cache to specify the path of
the cache files, the lifetime in seconds and the enabled value to turn on
and off the caching system.

Since we used a file to store the cache content, we can use the file
modification time to manage the lifetime of the cache. We used the filemtime
function of PHP to retrieve the modification file time.

Note: if you want to use memcached instead of file you need to replace the
file_get_contents and file_put_contents functions with Memcached::get
and Memcached::set. Moreover, you do not need to check for lifetime
because when you set a content in memcached you can specify the expiration
directly.

In order to pass the $config dependency, we can use a simple factory class.
This is an example:

namespace AppAction;

use InteropContainerContainerInterface;
use Exception;

class CacheFactory
{
    public function __invoke(ContainerInterface $container)
    {
        $config = $container->get('config');
        if (isset($config['cache']) && isset($config['cache']['enabled'])) {
            if ($config['cache']['enabled']) {
                if (!isset($config['cache']['path'])) {
                    throw new Exception('The cache path is not configured');
                }
                if (!isset($config['cache']['lifetime'])) {
                    throw new Exception('The cache lifetime is not configured');
                }
            }
        }
        return new CacheMiddleware($config['cache']);
    }
}

Following the folder structure of Expressive, we can store this configuration in
a simple PHP file in the config/autoload directory. For instance, we can store
it in config/autoload/cache.local.php file, as follows:

return [
    'cache' => [
      'enabled'  => true,
      'path'     => __DIR__ . '/../../data/cache/',
      'lifetime' => 3600 // in seconds
    ]
];

We used the folder /data/cache for storing the caching file. The content of
this folder should be omitted in the version control. For instance, using git
you can omit the content putting a .gitignore file inside the cache folder
with the following content:

*
!.gitignore

Finally, in order to activate the caching system we need to add the
CacheMiddleware class as service. In our example, we used zend-servicemanager
as service container. To add the cache system we can use a configuration file
(e.g. /config/autoload/cache.global.php) with the following content:

return [
    'dependencies' => [
        'factories' => [
            AppActionCacheMiddleware::class => AppActionCacheFactory::class
        ]
    ]
];

How enable the cache for specific routes

We mentioned early that this caching mechanism works fine for static content.
That means we need a way to enable the cache only for specific routes.

We can simply add the CacheMiddleware class as first middleware to be executed
for all the routes representing static contents.

For instance, imagine to have a /about route that show an about page of your
web site. We can add the CacheMiddleware as follow:

use AppAction;

$app->get('/about', [
    ActionCacheMiddleware::class,
    ActionAboutAction::class
], 'about');

The middleware actions to be excuted for the /about URL are CacheMiddleware
and AboutAction in this order. The $app object is the instance of ZendExpressiveApplication,
the main class that manages the execution of an Expressive application.

Conclusion

In this brief article we showed how to build a caching system for a PHP
application based on PSR-7 and PSR-15. A middleware architecture facilitates the
design of a cache layer because it uses the same workflow, an HTTP request as
input and an HTTP response as output. In this way, we can manage the HTTP
request, get the HTTP response for any middlewares and store the result for
caching, all in one place.

In this article we used the zendframework/zend-expressive-skeleton application
as example. For more information about Expressive, visit the documentation.

Save the date!

Want to learn more about Expressive and Zend Framework? What better location
than ZendCon 2017! ZendCon will be hosted 23-26 October 2017 in Las Vegas,
Nevada, USA. Visit the ZendCon website for more
information
.

Source: Zend feed

1 2