Moving on in our Orinoco River project it is time to add authorization to the Zend Framework 2 project.

in composer.json add:


"require": {
       .....
        "bjyoungblood/bjy-authorize":"1.4.*"       
    },

in application.config.php add ‘BjyAuthorize‘ to the modules array and run composer update.

The database schema differs from the one in the BjyAuthorize repository:


CREATE TABLE IF NOT EXISTS `user_role` (
  `id` int(11) NOT NULL auto_increment,
  `role_id` varchar(255) collate utf8_unicode_ci NOT NULL,
  `is_default` tinyint(1) NOT NULL default '0',
  `parent_id` varchar(255) collate utf8_unicode_ci default NULL,
  PRIMARY KEY  (`id`),
  UNIQUE KEY `unique_role` (`role_id`),
  KEY `idx_parent_id` (`parent_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=4 ;

INSERT INTO `user_role` (`id`, `role_id`, `is_default`, `parent_id`) VALUES
(1, 'guest', 1, 'user'),
(2, 'user', 0, 'admin'),
(3, 'admin', 0, '');

CREATE TABLE IF NOT EXISTS `user_role_linker` (
  `user_id` int(10) unsigned NOT NULL,
  `role_id` varchar(255) collate utf8_unicode_ci NOT NULL,
  PRIMARY KEY  (`user_id`,`role_id`),
  KEY `idx_role_id` (`role_id`),
  KEY `idx_user_id` (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `user_role_linker` (`user_id`, `role_id`) VALUES
(1, 'admin'),
(2, 'user')

The role_id is not actually an integer ID but a role name varchar.

In the config/autoload/bjyauthorize.global.php configuration file the identity provider is BjyAuthorize\Provider\Identity\ZfcUserZendDb as we would like this operation Doctrine-free. This setup also relies on controller guards and not route guards. The module works by listening to the MvcEvent::EVENT_ROUTE event.

Now if a user is not authorized for a particular page, an error message is displayed on screen. It is nicer to be able to redirect this user to the login page. This can be done with an adaptation of akrabat/UnauthorizedStrategy.php: in the BjyAuthorize configuration add an unauthorized_strategy as ‘UnauthorizedStrategy‘ and commit the class. This class listens for any MvcEvent::EVENT_DISPATCH_ERROR on which a onDispatchError method is triggered. This method redirects to the login page.

See latest revision

Advertisements