CakeDC Blog

TIPS, INSIGHTS AND THE LATEST FROM THE EXPERTS BEHIND CAKEPHP

How To: CakePHP, CakeDC Users and Amaz...

Long time ago, in 2010, CakeDC Users plugin for CakePHP was released for CakePHP 1.3. Almost nine years has passed and the initial code has changed dramatically, offering new and exciting features. In 2011 the team released the first version to be compatible with the new CakePHP 2.0. At this moment we focused in keeping the same features and only adding support for the new version of the framework. When CakePHP 3.0 arrived in 2015 we decided to refactor Users plugin completely, making it easier to use but also adding terrific features out of the box like:

  • Social login with most popular providers
  • RBAC permissions
  • Superuser
  • And much more..
It continued evolving and today we will show how to use the latest provider we have added to the social login feature in the plugin, Amazon Cognito. Let’s talk first about it. We'll use Amazon Cognito basically as an Oauth 2.0 Server. It'll let you manage your user groups and users. It provides a simple interface to sign up, sign-in and also use many social providers like Facebook, Google and Amazon. It also allows using SAML 2.0 providers and they promise it may scale to millions of users. You can also fully customize form and buttons. Best of all, it is free for the first 50,000 logins. Let's start configuring Amazon Cognito in AWS Panel. We must first create a user pool. You could have different user pools and each of them having an exclusive set of features.     Now we need to customize our new pool adding a pool name, etc. We can use default settings for testing purposes. If you want to customize fields you should then go through steps.     Once we check everything is okay we can click on Create Pool.     Now, it's time to setup App Clients. If you are familiar with OAuth and another services it is like creating a Facebook or Twitter App.     And then click on Add an app client.  Just add a name and save.   Remember to write down your client ID and client secret because they will be needed later to configure Users plugin. The next step is to setup app client settings. We need to configure:
  • Callback url: set it to /auth/cognito if you want to use plugin defaults.
  • The flow to Authorization code grant and the scopes you must select at least email and openid. You can select profile in case you want to get all the user information from cognito.
      Finally we need to configure a domain name for the user pool. Use a custom domain or a subdomain from Cognito.     Now that we are ready with Cognito setup, let’s easily create a new CakePHP app, to connect with Amazon Cognito. First, we need a new CakePHP app: composer create-project --prefer-dist cakephp/app users-app Remember to create a new empty database. Now we can go to users-app folder and run: composer require cakedc/users After CakeDC Users plugin is installed, we need to install Oauth 2 Cognito provider package: composer require cakedc/oauth2-cognito CakeDC Users plugin configuration is pretty easy: $this->addPlugin('CakeDC/Users'); public function pluginBootstrap() { parent::pluginBootstrap(); Configure::load('users'); }
  • Load the Users Plugin bin/cake plugin load CakeDC/Users
  • If you prefer to do this manually, add this line at the end of your src/Application.php bootstrap() method
  • Add the following line into AppController::initialize() method $this->loadComponent('CakeDC/Users.UsersAuth');
  • Add the following code to your src/Application.php pluginBootstrap() method to ensure we override the plugin defaults
  • Add the file config/users.php with your specific configuration, including
  • return [ 'Users.Social.login' => true, 'OAuth.providers.cognito.options.clientId' => 'CLIENT_ID', 'OAuth.providers.cognito.options.clientSecret' => 'CLIENT_SECRET', 'OAuth.providers.cognito.options.cognitoDomain' => 'DOMAIN', 'OAuth.providers.cognito.options.region' => 'REGION', ];
In case you used a custom domain for you user pool, you can replace cognitoDomain option by using hostedDomain option (including protocol): 'OAuth.providers.cognito.options.hostedDomain' => 'YOUR DOMAIN', Scope option defaults to email openid . If you selected another scopes, you may want to add them as well: 'OAuth.providers.cognito.options.scope' => 'email openid profile', Finally we just need to go to /login.     and click on Sign in with Cognito. If everything is setup correctly you should see the following screen:   You can previously create a user in AWS panel or just click signup on that screen. After login you will be redirected to homepage in CakePHP App. As you can see, the setup for both Cognito and App are simple if you use default settings. However after testing defaults, you can start customizing forms, fields, adding third party apps. You have no limits.  

Last words

We create and maintain many open source plugins as well as contribute to the CakePHP Community as part of our open source work in CakeDC. While developing this provider, we've also published a generic Oauth2 Amazon Cognito repository. Reference  

Boost CakePHP using RoadRunner Plugin

https://github.com/CakeDC/cakephp-roadrunner was just released! Some time ago we developed a bridge for the PHP Process Manager, and now we've integrated with another alternative, a fast, go based, PHP application server (see https://github.com/spiral/roadrunner) Using this approach, and configuring nginx + roadrunner + cakephp, we're getting ~1500 requests per second for a typical index operation (including database access), and over 2200 (!) requests per second using a cached resultset. Here's what you need to do:

  • composer require cakedc/cakephp-roadrunner
  • Download roadrunner binary and place the file in your filesystem, for example under /usr/local/bin/rr
  • Create a RoadRunner worker file, or use the example worker provided
cp vendor/cakedc/cakephp-roadrunner/worker/cakephp-worker.php . cp vendor/cakedc/cakephp-roadrunner/worker/.rr.json . Note the configuration is stored in .rr.json file, check all possible keys here https://github.com/spiral/roadrunner/wiki/Configuration
  • Start the server, either using your own configuration or the sample configuration provided in the plugin
/usr/local/bin/rr serve   Check plugin details here > https://github.com/CakeDC/cakephp-roadrunner

Last words

Please let us know if you use it, we are always improving our plugins - And happy to get issues and pull requests for our open source plugins. As part of our open source work in CakeDC, we maintain many open source plugins as well as contribute to the CakePHP Community.

Integrating Users and ACL plugins in C...

In previous posts, we saw how CakeDC Users plugin can help you to build an application that manages everything related to users: registration, social login, permissions, etc. Recently it has been noted by the team that there are some use cases where a deeper control of permissions is needed - more than is offered in RBAC. Today we’ll go into this using the ACL approach. ACL or Access Control List, refers to the application using a detailed list of objects to decide who can access what. It can be as detailed as particular users and rows through to specifying which action can be performed (i.e user XX has permissions to edit articles but does not have permissions to delete articles). One of the big features of ACL is that both the accessed objects; and objects who ask for access, can be organized in trees. There’s a good explanation of how ACL works in the CakePHP 2.x version of the Book. ACL does not form part of CakePHP core V 3.0 and can be accessed through the use of the cakephp/acl plugin. Let’s just refresh the key concepts of ACL:

  • ACL: Access Control List (the whole paradigm)
  • ACO: Access Control Object (a thing that is wanted), e.g. an action in a controller: creating an article
  • ARO: Access Request Object (a thing that wants to use stuff), e.g. a user or a group of users
  • Permission: relation between an ACO and an ARO
For the purpose of this article - we shall use this use case: You are using CakeDC/users plugin and now want to implement ACL in your application.

Installation

Starting with a brand new CakePHP app: composer selfupdate && composer create-project --prefer-dist cakephp/app acl_app_demo && cd acl_app_demo We are going to use CakeDC/users and cakephp/acl plugins. In a single step we can install them with composer: composer require cakedc/users cakephp/acl Create a DB and set its name and credentials in the config/app.php file of the just created app (in the Datasources/default section). This command can help you out if you are using MySQL: mysql -u root -p -e "create user acl_demo; create database acl_demo; grant all privileges on acl_demo.* to acl_demo;" Plugins will be loaded always with the app. Let’s set them on the bootstrap file: bin/cake plugin load -br CakeDC/Users
bin/cake plugin load -b Acl Now let’s insert a line in bootstrap.php before Users plugin loading, so cakedc/users will read the configuration from the config/users.php file of our app. Configure::write('Users.config', ['users']); This file does not exist yet. The plugin provides a default file which is very good to start with. Just copy it to your app running: cp -i vendor/cakedc/users/config/users.php config/ Also, let’s copy the permissions file the same way to avoid warnings in our log files: cp -i vendor/cakedc/users/config/permissions.php config/ We need to change cakedc/users config: remove RBAC, add ACL. In cakephp/acl there’s ActionsAuthorize & CrudAuthorize. We’ll start just using ActionsAuthorize. We will tell ActionsAuthorize that actions will be under the 'controllers/' node and that the users entity will be MyUsers (an override of the Users entity from the plugin). Edit the Auth/authorize section of config/users.php so that it sets: 'authorize' => [ 'CakeDC/Auth.Superuser', 'Acl.Actions' => [ 'actionPath' => 'controllers/', 'userModel' => 'MyUsers', ], ], Add calls to load components both from Acl & Users plugin in the initialize() method in AppController: class AppController extends Controller { public function initialize() { parent::initialize(); // (...) $this->loadComponent('Acl', [ 'className' => 'Acl.Acl' ]); $this->loadComponent('CakeDC/Users.UsersAuth'); // (...) } // (...) }

Database tables

Some tables are required in the database to let the plugins work. Those are created automatically just by running their own migrations: bin/cake migrations migrate -p CakeDC/Users
bin/cake migrations migrate -p Acl One table from the Acl plugin needs to be fixed because Users migration creates users.id as UUID (CHAR(36)) and Acl migrations creates AROs foreing keys as int(11). Types must match. Let’s fix it adapting the aros table field: ALTER TABLE aros CHANGE foreign_key foreign_key CHAR(36) NULL DEFAULT NULL; Now, it’s time to set our own tables as needed for our app. Let’s suppose we are developing a CMS app as specified in the CMS Tutorial from the CakePHP book. Based on the tutorial, we can create a simplified articles table: CREATE TABLE articles ( id INT AUTO_INCREMENT PRIMARY KEY, user_id CHAR(36) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL, title VARCHAR(255) NOT NULL, body TEXT, published BOOLEAN DEFAULT FALSE, created DATETIME, modified DATETIME, FOREIGN KEY user_key (user_id) REFERENCES users(id) ); Note: Specify CHARACTER SET and COLLATE for user_id only if the table CHARACTER SET and COLLATE of the table differ from users.id (than may happen running migrations). They must match. Roles will be dynamic: admin will be allowed to manage them. That means that they has to be stored in a table. CREATE TABLE roles ( id CHAR(36) NOT NULL PRIMARY KEY, name VARCHAR(100) NOT NULL, created DATETIME, modified DATETIME ); Association between users and roles bill be belongsTo, so we’ll need a foreign key in the users table instead of a role varchar field: ALTER TABLE users ADD role_id CHAR(36) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL AFTER role, ADD INDEX role_id (role_id), ADD FOREIGN KEY (role_id) REFERENCES roles(id); ALTER TABLE users DROP role;

Baking

Time to think about what will be ACOs and AROs. In most cases, Users will be the only AROs. To do that, we need to link the Users entity and table to the ACL plugin. In this case that we are using CakeDC/users plugin, we first need to extend the plugin as it is explained in the docs. We will also add the behavior and parentNode() as shown in the cakephp/acl readme file, so at the end we’ll need to create those files: src/Model/Entity/MyUser.php: <?php namespace App\Model\Entity; use CakeDC\Users\Model\Entity\User; /** * Application specific User Entity with non plugin conform field(s) */ class MyUser extends User { public function parentNode() { return ['Roles' => ['id' => $this->role_id]]; } } src/Model/Table/MyUsersTable.php: <?php namespace App\Model\Table; use CakeDC\Users\Model\Table\UsersTable; class MyUsersTable extends UsersTable { public function initialize(array $config) { parent::initialize($config); $this->addBehavior('Acl.Acl', ['requester']); $this->belongsTo('Roles'); $this->hasMany('Articles'); } } Run bin/cake bake controller MyUsers (beware of case) Then, edit the top of src/Controller/MyUsersController.php as: <?php namespace App\Controller; use App\Controller\AppController; use CakeDC\Users\Controller\Traits\LinkSocialTrait; use CakeDC\Users\Controller\Traits\LoginTrait; use CakeDC\Users\Controller\Traits\ProfileTrait; use CakeDC\Users\Controller\Traits\ReCaptchaTrait; use CakeDC\Users\Controller\Traits\RegisterTrait; use CakeDC\Users\Controller\Traits\SimpleCrudTrait; use CakeDC\Users\Controller\Traits\SocialTrait; class MyUsersController extends AppController { use LinkSocialTrait; use LoginTrait; use ProfileTrait; use ReCaptchaTrait; use RegisterTrait; use SimpleCrudTrait; use SocialTrait; // CRUD methods ... To generate the template files for MyUsers we can run: bin/cake bake template MyUsers Next, just let Cake bake all objects for articles and roles: bin/cake bake all Articles
bin/cake bake all Roles Add behavior to their tables. ArticlesTable will act as controlled because it will represent ACOs: class ArticlesTable extends Table { public function initialize(array $config) { parent::initialize($config); // (...) $this->addBehavior('Acl.Acl', ['controlled']); // (...) The case of RolesTable will be similar but it will act as requester, as it will represent AROs: class RolesTable extends Table { public function initialize(array $config) { parent::initialize($config); // (...) $this->addBehavior('Acl.Acl', ['requester']); // (...) Create the parentNode() method in both entities: Article and Role. public function parentNode() { return null; }

Testing

Ok, time to test the whole system! At this point, the app should be ready to use. At least, for an administrator. Let’s quickly create one: it is as easy as running bin/cake users add_superuser. New credentials will appear on screen. When accessing our app in the URL that we installed it, a login form will appear. Log as the just created admin. First, let’s create some roles. Go to /roles in your app’s URL. Then, click on "New Role". Create the roles:
  • Author
  • Editor
  • Reader
Then, we can create two users an author and a reader. Head to /my-users and add them. Remember to select the Active checkbox and the proper role in the dropdown menu. Because MyUsers has the AclBehavior, AROs has been automatically created while creating users, along with the created roles. Check it out with bin/cake acl view aro Aro tree: --------------------------------------------------------------- [1] Roles.24c5646d-133d-496d-846b-af951ddc60f3 [4] MyUsers.7c1ba036-f04b-4f7b-bc91-b468aa0b7c55 [2] Roles.5b221256-0ca8-4021-b262-c6d279f192ad [3] Roles.25908824-15e7-4693-b340-238973f77b59 [5] MyUsers.f512fcbe-af31-49ab-a5f6-94d25189dc78 --------------------------------------------------------------- Imagine that we decided that authors will be able to write new articles and readers will be able to view them. First, let’s create the root node for all controllers: bin/cake acl create aco root controllers Then, let’s inform ACL that there are such things as articles: bin/cake acl create aco controllers Articles Now, we will tell that there are 5 actions related to Articles: bin/cake acl create aco Articles index bin/cake acl create aco Articles view bin/cake acl create aco Articles add bin/cake acl create aco Articles edit bin/cake acl create aco Articles delete We can see the first branch of the ACOs tree here: bin/cake acl view aco Aco tree: --------------------------------------------------------------- [1] controllers [2] Articles [3] index [4] view [5] add [6] edit [7] delete --------------------------------------------------------------- ACL knows that articles can be added, so let’s tell who can do that. We can check which aro.id belongs to role Author with: mysql> select id from roles where name like 'Author'; +--------------------------------------+ | id | +--------------------------------------+ | 24c5646d-133d-496d-846b-af951ddc60f3 | +--------------------------------------+ 1 row in set (0.00 sec) And the same with the Reader role:: mysql> select id from roles where name like 'Reader'; +--------------------------------------+ | id | +--------------------------------------+ | 25908824-15e7-4693-b340-238973f77b59 | +--------------------------------------+ 1 row in set (0.00 sec) So, if we look up this id in the bin/cake acl view aro output, it turns out that aro.id 1 is Author and that aro.id 3 is Reader. If we want to let authors (ARO 1) add articles (ACO 5), we must grant permission to Articles/add to editors by running: bin/cake acl grant 1 5 And we'll grant readers (ARO 3) view articles (ACO 4) with: bin/cake acl grant 3 4 Don't forget to grant access to Articles/index for all roles, or nobody would access /articles: bin/cake acl grant 1 3 bin/cake acl grant 2 3 bin/cake acl grant 3 3 Note: Obviously, it would be easier to set a "super role" which includes the 3 roles and grant access to index to it, but we don't want to add too many steps in this tutorial. You can try it for yourself. Then, aros_acos table becomes: mysql> select * from aros_acos; +----+--------+--------+---------+-------+---------+---------+ | id | aro_id | aco_id | _create | _read | _update | _delete | +----+--------+--------+---------+-------+---------+---------+ | 1 | 1 | 5 | 1 | 1 | 1 | 1 | | 2 | 3 | 4 | 1 | 1 | 1 | 1 | | 3 | 1 | 3 | 1 | 1 | 1 | 1 | | 4 | 2 | 3 | 1 | 1 | 1 | 1 | | 5 | 3 | 3 | 1 | 1 | 1 | 1 | +----+--------+--------+---------+-------+---------+---------+ 5 rows in set (0.00 sec) Let’s create a new article as the first user. To do that:
  • Log out (we are still logged in as superadmin) going to /logout
  • Log in as the first created user
  • Go to /articles
  • Create an article
Right now, author can add an article but not view it, since we only set the add permission. Check it out clicking in View next to the article. Log in as a reader to check how the reader can really view the article. Obviously, more than a couple of permissions have to be grant in a big app. This tutorial served just as an example to start.

Last words

That's all for now related to the use of ACL in a webapp made with CakePHP. A lot more can be done with ACL. Next step would be to use CrudAuthorize to specify which CRUD permissions are granted for any ARO to any ACO. Keep visiting the blog for new articles! This tutorial has been tested with:
  • CakePHP 3.5.10
  • CakeDC/users 6.0.0
  • cakephp/acl 0.2.6
An example app with the steps followed in this tutorial is available in this GitHub repo. Please let us know if you use it, we are always improving on them - And happy to get issues and pull requests for our open source plugins. As part of our open source work in CakeDC, we maintain many open source plugins as well as contribute to the CakePHP Community. Reference

Using a vagrant box as quick environme...

We've decided to create a simple vagrant box with all the required packages to improve the environment setup step in our free Getting Started with CakePHP training session. We used other tools in the past, but we hope vagrant will help users to install a common environment before the session to get the most of it.

Requirements

Setup

  • Create a new folder where the code will be located
  • Create a new file called Vagrantfile with the following contents
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure("2") do |config| config.vm.box = "cakedc/cakephp-training" config.vm.network :forwarded_port, guest: 8765, host: 8765 config.vm.provider "virtualbox" do |vb| vb.memory = "1024" vb.customize ['modifyvm', :id, '--cableconnected1', 'on'] end end
  • Run vagrant up
  • Wait (download could take several minutes depending on your internet connection)
  • Run vagrant ssh
Now you have ssh access to a training ubuntu (16.04) based virtual machine, with all the requirements to run your training CakePHP application.
  • Setup a new CakePHP project
cd /vagrant composer create-project cakephp/app
  • Start the local server
cd /vagrant/app php bin/cake.php server --host 0.0.0.0
  • From your host machine, open a browser and navigate to http://localhost:8765
  • You should be able to see the CakePHP welcome page
  We think this VM will enable faster environment setups, and an easier entry point to the training session. Please let us know if you find issues with this process.

Boosting your API with CakePHP API and...

A couple days ago AlexMax commented in CakePHP's IRC channel about the https://github.com/php-pm/php-pm project and it rang a bell for us. We did a couple tests internally and found this could be a great companion to our API plugin, so we wrote a new Bridge for CakePHP and ran some benchmarks.

The Cast

We put all together and created a sample application (1 posts table with 30 records) to do some benchmarks.

Benchmark configuration

We are not aiming to provide detailed or production figures, just a reference of the results obtained for your comparison. Results are generated from a development box, using PHP 7.1.12-3+ubuntu16.04.1+deb.sury.org+1 with xdebug enabled on ubuntu xenial, 8x Intel(R) Core(TM) i7-4771 CPU @ 3.50GHz We baked the application using the latest CakePHP 3.5.10, and set application debug to false, and log output to syslog. As we are interested in boosting API response times the most, we tested the following scenarios
  • A) CakePHP json output, served from nginx+phpfpm
  • B) CakePHP + API Plugin Middleware integration json output, served from nginx+phpfpm
  • C) CakePHP + API Plugin Middleware integration json output, served from php-pm
Benchmark figures were obtained using ab -n 5000 -c 100 URL

Results

Scenario requests/second avg time
A) CakePHP json output, served from nginx+phpfpm using php7.1 372.97 [#/sec] (mean) 268.120 [ms] (mean)
B) CakePHP + API Plugin Middleware integration json output, served from nginx+phpfpm using php7.1 399.79 [#/sec] (mean) 250.133 [ms] (mean)
C) CakePHP + API Plugin Middleware integration json output, served from php-pm using php7.1 911.95 [#/sec] (mean) 109.656 [ms] (mean)
D) CakePHP + API Plugin Middleware integration json output, served from php-pm using php7.2 1811.66 [#/sec] (mean) 55.198 [ms] (mean)
  These results for a NOT OPTIMIZED CakePHP application are promising, and the improvement using PHP-PM is huge in this case. There are some important considerations though:
  • PHP-FPM is mature and stable, PHP-PM is still in early development, although there is a 1.0 version released already.
  • Processes need monitoring, specially regarding memory leaks, we would need to manage a restart policy and be able to hot-restart individual workers
  • System integration, init scripts are not provided, even if this is something easy to manage nowadays via systemd or monit, would be good to have for production
  • Application bootstrapping should not be affected by the request. If your application bootstrapping depends on the request params, or logged in user, you'll need to refactor your code
  • Session handling was not tested, issues are reported for PHP-PM for other frameworks. We were aiming to stateless API's so we don't know if this would be an issue for a regular application
Performance is always a concern for the API developer, applying proven paradigms like the event driven development (https://reactphp.org/) to your existing code would be the way to go and ensure backend frameworks like CakePHP will perform as required when dealing with the peaks we all love and hate. Edit: We've added a php7.2 based benchmark, with a huge performance improvement.

Giving back to the community

This Plugin's development has been sponsored by the Cake Development Corporation. Contact us if you are interested in:      

Why an independent code review is impo...

Passbolt recently contacted us about doing a code review so we thought now would be a great time to share more about our code review process with you. While in-house and peer reviews are important to maximise code quality, it is still incredibly important to get an independent third party to review your code - that is where CakeDC can step in. Passbolt is free, open-source, self hosted password manager for teams which makes collaboration and sharing company account credentials within a team much easier. It's based on open security standards and uses OpenPGP to authenticate users and verify secrets server side. Passbolt consists of server side web app built in CakePHP providing web interface and API, and Chrome extension for client side. The overall aspects that are reviewed in our code review include a review of quality, implementation, security, performance, documentation and test coverage. When looking into quality, the team reviews aspects concerning the code following CakePHP conventions, coding standards and coding quality. Overall, passbolt’s code review revealed that CakePHP conventions and coding standards are largely followed, no concerns were detected. Implementation outlines key issues with framework use and approach. It includes reviewing the code for framework usage, separation of concerns as well as code reuse and modularity. Key recommendations are outlined at this point and guidance is given into how to solve any issues. For the Passbolt review, bigger or concerning issues were uncovered, but improvements were recommended and outlined within the closing documentation. The security portion of the code review deals with how secure the code is in terms of CakePHP usage. No security flaws were found in the passbolt code review. Our in depth code review focuses on performance, specifically investigating any bottlenecks in the code base and database as well as indexes optimization. For the full passbolt code review results, check out the Code review results. Passbolt has also posted about their review, check out their post here. If you or your company has a CakePHP application and you aren’t sure if its running at the optimum, then get in touch - Code reviews can offer insights and learning into how to improve your application.

Errors to fix today on your site

Running a website can lead to massive success for you business, however, without the proper maintenance, you can be losing out. Some errors your site can be suffering from may be minor, such as spelling mistakes, however, there may be errors that can have significant impacts such as pending security updates. Let's take a quick look at some that you should fix today! Basic HTTP errors If there are HTTP errors lurking on your site, your visitors are probably getting frustrated. Make sure to constantly review your website for these errors. Some of the more common ones include 401, 404 and 500 errors. Spelling errors, basic content duplication and broken links These are all easy and minor errors to fix, however they can lead to your visitors losing trust in your company or brand. Invalid HTML Your website’s HTML needs to follow the published HTML standards and if not, will lead to invalid HTML. Having invalid HTML leads to a multitude of things including impacted/lower SEO rankings, reduced accessibility for visitors using screen readers and other assistive technologies and browser compatibility. Pending security updates and version updates Having pending updates can open you up to malicious activity such as website defacing or stealing of confidential information. If you have an update pending, quickly update today! Incorrectly inserted analytics tags Be sure to double check that your analytics tags have been added to your code correctly. You may be missing out on valuable information that will help you improve your website. Not sure what you are doing wrong? Google offers guidelines and tutorials to get any issues sorted out quickly. Lastly, be sure to ask yourself - Have you tested? Testing is another key part to the success of your new site’s launch. Be sure to not miss this step. Not sure how to properly test your site? Here’s a great checklist to check out. From how to test elements such as HTML, CSS, security and performance through to SEO and accessibility, this checklist will guide you along best practices when it comes to testing. Another important tool to make use of is the W3 Markup validator.  

Why Mobile web design is important

With mobile traffic continuing to dominate, its just as important to get your mobile web design up to scratch. The stats for 2017 show that mobile searches once again took the lead at 50% with desktop sitting at around 45%. When designing your web application, it is key to not only consider mobile web development, but to prioritise it. Can you afford to lose over half of your web traffic due to poor design? Search engines have started prioritizing mobile friendly websites - what does this mean for you? Google has understood this shift in user behaviour, and with their mobile-first search index already kicking in, now is the time to get the mobile version of your site in tip top shape. If your mobile site lacks the same detailed information as your desktop site, you will get hurt by this indexing. Not providing key detail on your pages will shift your overall SEO rankings. Mobile optimized web design provides a better user experience for mobile users. With such a high percentage of mobile traffic, ensuring that these users get the best user experience possible on your site is vital. By ensuring that your mobile web design is functional, you provide the user with key functional aspects such as readable fonts and headers, easy-to-click links and faster load times. There are a variety of free tools out there to help you assess whether your site will rank well or not. If you are optimising your SEO and web design efforts for Google, then take a look at these three key tools that are vital to all developers. Google’s mobile-friendly test allows you to simply enter in your website URL and run a quick check to determine if you site is mobile friendly. While this tool is great for seeing how Google ranks your site, it doesn’t provide any detail in the site’s strengths and weaknesses. Google’s page speed insights tool allows you to assess the load speed times of your site. As well as providing a score, it also provides detail into how you can go about fixing the page speed. Google’s webmaster tools mobile usability test shows you even more detail into the usability of your mobile site. With many great free resources, as well as many insightful blog posts, you too can get your mobile site optimized for your user. CakeDC provides both development and consulting services, ensuring that you are left with the best web application solution. If you are in need of a full scoped development project or are simply looking for guidance and expert knowledge for your application, CakeDC is the team to contact.

Tips for building custom apps

Sometimes all your website needs is a bit of added functionality and increased interactivity. Custom applications can make or break your user experience, here are some of the key things you should look out for when getting your custom applications developed. Consider tooltips to guide users Sometimes custom applications require certain actions from the user. Tooltips allow you to help the user along without cluttering the interface. Include progress notifications Tell the user if something has been processed successfully. Including feedback notifications such as “loading” or “please wait” can help your users understanding of your application. Keep familiar patterns and navigation within your application Users will find the experience of using your custom application if a similar navigation is used - keeping familiar patterns can be achieved through various methods such as keeping information in the same areas on every page. Keep pop-ups to a minimum or have none at all! Pop ups distract and interfere with a user's experience. Limit the use of these to a minimum - only including key and critical information if used. Ensure log-in or entry information simple and easy If your application requires a user to log in or provide certain information before accessing the content, it's important to keep this requirement simple. Having high entry barriers or information required can stop a user from actually using your application. Design your custom application for your target audience Who do you see as the ideal user of your application? Avoid technical jargon or unfamiliar terms or processes. Are you designing a shopping cart for users accustomed to online shopping? Then keep up-to-date with the latest best practices from top ecommerce sites and follow their lead. Are you looking for a custom application? Contact CakeDC, the experts behind CakePHP.  

Simplicity is important - here’s why

When it comes to web design, simplicity is not valued enough. Simplicity is important - but why? Simplicity reduces navigation confusion, makes the website look more sophisticated and can help in increasing site conversions (sign ups, contacts). All too often, web designers tend to miss the point of simplicity and over do the amount of information given on a single page - the need to get everything across at once can seriously hinder how much a website visitor is able take in. Over complicated pages can lead to higher than average bounce rates or lower on-page conversions. We thought we’d share with you some top tips to simplify your website.

  • Keep things along the 80-20 rule
    • Use the Pareto principle which is that 80% of the effects come from 20% of the causes. This means taking away as much as you can from your design that will not lead to any type of conversion. Take things back to the bare essentials and make those work properly
  • Embrace few colors in your theme
    • Does a monochrome color scheme work for you? If not, try out as few colors as possible. Work towards a design that requires less effort for your website visitor to process. Fewer colors will also give your site a sleek, classic look
  • Keep copy short and sweet
    • Embrace compelling copy but keep things shorter and to the point. Make your point quickly and keep things easy-to-read by sticking to a few key points. Use shorter sentences, and keep paragraphs to a maximum of 3-4 sentences for easy reading.
  • Fix your navigation
    • Often many sites have over complicated and lengthy navigation options. Remember to include navigation to your list of things to simplify today. Keep important and key pages in your navigation bar. Remove excess clutter and keep all navigation menus visible. Other key things to keep in mind is the use of universal icons as well as ensuring a sitemap in your footer - these are all standard items that visitors look for.

How Much Does it Cost to Design a Site?

If you are in the market for a website or application, it can sometimes be daunting. Being unsure of where to start, which development firm to use or how much the whole process is going to cost you can be truly overwhelming. And then there are those horror stories of others, who selected a developer based solely on cost (the cheapest quote perhaps) and ended up majorly down the hole with their budgets, while owning a unfinished website. Whether you are in the market for a website application with a specific outline and goal, or have a rough idea of what you need your application to do, how do you go about finding the best selection for you? And then how do you know that whoever you select is going to deliver what you want and in the time frame that you need it? And then, not knowing how to code yourself, you can land up frustrated at not understanding the process - especially if your development team gives you the runaround. At CakeDC, we are committed to a transparent workflow - we've created our own git workflow (MIT license) and we've used it successfully with our clients for 3+ years and dozens of projects. We use it to accelerate growth and innovation providing the highest quality application development. What sets CakeDC apart from others is that our experts listen closely to your needs. Second, we formulate a roadmap of milestones based on your specifications. Third, we offer guidance while delivering the highest quality results in a fraction of other developer’s time, by doing things The Right Way™ So how much is it going to cost you? Well this is of course dependent on what you project scope includes, however, we will work with you in determining the best package to suit your requirements. You can check out all of our rates and packages here. Ready to get your project started? Reach out to our experts today to see how easy it can be to get your application up and running.

What your website users are trying to ...

Every visitor to your website has a goal in mind - this may not be a conscious goal, but they are visiting your site for a reason. So listening to your users feedback is key to meeting their expectations! As a business owner, be sure to keep these in consideration and as a developer, be sure to pass these recommendations through to your clients. What are some things that users are trying to tell you and how do you find out? What and why is it Often people forget about the basics and fail to include what their product, service or business is. By excluding this vital information there will be users who will not know what the purpose of the page that they have stumbled upon is, but what to do next - and therefor bounce quickly off of your site. Where is your pricing information? If you are trying to sell something - a product or a service - be sure to include the price information as this is used by your visitor to determine their next action. Even if you are providing resources in return for their details, it is important to be clear. Where are those testimonials or reviews? Have others tried it People like to know that whatever they are investing money into is worth it - reviews or customer testimonials help to show your visitors what you can do. Be sure to add this information in a way that is easy for you visitors to find. Where can I sign up or contact you Another vital piece of information that many often forget is to let your visitors know how to signup and contact you. Perhaps you have chosen to hide your contact information due to spam bots or other issues faced, however, if you are in the business of recruiting clients, then be sure to have some form of contact information easily available to your visitors.
Not sure if you are missing anything? CakeDC, the experts behind CakePHP, offer a range of services including consulting, guiding you through the best practices with your CakePHP application.

Payment integration, E-commerce made easy

With ecommerce trending, it may be the next step for your business. However, it can seem daunting - so where do you start?   Starting with basics, you need a website that will serve as a platform for your products - a good starting point is key. Perhaps your website is up and running, but you aren’t happy with it - why not do a redesign at the same time as doing payment integration. Be sure to discuss your needs with your development team.   Next is to ensure your product list is up to date and aligned with your ecommerce goals. With the ecommerce industry becoming so competitive, it's important to stand out - both with your products as well as with the overall user experience.   So your products stand out on your website, things are looking good! But having a functional payment processor is key to making those sales! Here are some key tips to ask your development team today!  

  • Before considering technical aspects, take consideration of the payment processing fees but be sure to pick a provider that is trusted by customers
  • Reference check your selection of payment gateway with your development team, will they be comfortable integrating this third party service with your site or do they have an alternative solution
  • Are you selecting a payment gateway that has been certified as safe and secure? By choosing one that is popular and trusted with customers will keep you on track for this requirement.
  • Is the payment gateway capable of accepting different payment methods such as credit cards, debit cards and others
  • Where are you planning to sell geographically via your ecommerce store? Is your payment gateway compatible with this geographical location? Some payment gateways are limited to certain countries - be sure to double check this before implementing the integration.
  • Should you chose to scale your business in the future, will your payment gateway be able to grow with you?
  Just remember, that whatever you choose to do with your ecommerce site, your payment integration should be as secure and smooth as possible. Chat to the expert team behind CakePHP today, to discuss how we can take your ecommerce integration to the next level. CakeDC is here to lead, so you can lead.  

Launching your new site? Read this first!

As exciting as launching a brand new website is, there are a lot of expectations that can be built up around it. Here are some top tips to not fall into the easy traps of launching your website   Don’t be a perfectionist It can be easy for some people to take the perfectionist view point when launching a new site. Rather focus on launching your website to its best and get feedback from testing and website visitors.   Doing it all yourself With the launch of your new site, it's important to delegate - make sure you have a expert team behind you so that you can manage your business and end goals. CakeDC, the experts behind CakePHP, believe in this philosophy - we lead, so you can lead.   Create a launch plan, now! If you do not have a plan for your launch, then the time is now! With research and strategy building, your launch will have direction, while reaching the right audience. Write everything down and be sure to share it with your team.   Linking to all Social media platforms With social media becoming an important way to reach out and talk to potential clients, it is key to ensure that you link your social media accounts to your websites and visa versa.   Have you tested? Testing is another key part to the success of your new site’s launch. Be sure to not miss this step. Not sure how to properly test your site? Here’s a great checklist to check out. From how to test elements such as HTML, CSS, security and performance through to SEO and accessibility, this checklist will guide you along best practices when it comes to testing.   Relax and execute your plan Lasty, relax and execute your plan! The final step to your new site’s launch is rollout. Things should be set up and in place which allow you to roll out your launch with minimal hassle.   At CakeDC, our goal is to help you, as a business leader, develop, achieve and maintain your competitive leadership in your market. Contact us to find out more about how we can create your custom application today.

Do you ever code for free? Contributin...

If you have ever taken a moment to contribute to open source, then you would know that it can be quite rewarding. But perhaps you are involved in an open source community, but aren’t necessarily contributing - yet! Maybe you are too nervous to contribute or you make a list of excuses as to why you aren't able to commit the time.   If you aren’t contributing just yet, here are some great benefits to you to start today.   Meet others in the community who are interested in similar things The CakePHP Community is welcoming and warm - by getting involved in the forums, online chats or through other participation, you can get to know others with similar interests.   Finding mentors within the community Get to know the community by getting involved - is there someone in the community who you think does an amazing job doing what they do? Chat to them, learn from them. There are some incredible mentors in the open source world - and they are normally down to earth and approachable.   Grow your knowledge and skill set base By contributing to open source, it gives you the opportunity to practise your skills. Through community involvement, you will learn new ways of doing things or suggest ways to improve on how things are done.   Help others - sense of giving Find reward in helping others solve the problems that have been troubling them. Giving back to the community brings in many rewards and a sense of achievement can be gained by helping out.   And now you may be asking - but how do I start? Easy! Just go ahead and find some issues that you can help out with, or simply join the support forums around the community and answer some questions - people appreciate the help and you never know, you could find help by helping others!   At CakeDC, time is committed to open source contributions. From our open source plugins through to support on community platforms, CakeDC ensures that time is committed to ongoing community support.

Why free website builders are hinderin...

Perhaps you are budget conscious or you are not computer savvy, and website builders look appealing to you. When getting a website developed for your business, key questions to ask yourself include: can it be managed effectively; will you be able to drive your brand online; will it be safe and secure? While website builders may seem like a good option, it can cause your business harm. Here’s a look at some of the cons of website builders.   You do not own your website Should you choose to leave your website builder, the website you have designed and any elements remain the property of the builder. You will essentially need to start over. From your content through to your domain name, all of this may need to be given up (as you are not the owner).   Website URL is not fully customizable When making use of a website builder, you are limited to the options that are provided. Some website builders offer different tiers, depending on your monthly subscription fee, however, you may need or want to do something that is out of the standard template.   Use of templates and outdated coding practises The use of templates is standard when building a website using a website builder. However, the use of outdated, unresponsive and badly designed templates can seriously hamper your brand (and website’s) ability to speak to your potential clients. These templates can use clunky, old fashioned and simple design.   SEO can be problematic With only basic SEO tactics employed by website builders, caution needs to be taken! Lacking SEO functionality can hamper your website’s ability to be found by potential clients - not appearing in search results and a lack of visibility can be damaging to your business.   Options, such as 3rd party integrations, are not available If you are looking to integrate 3rd party options, then think again - with only a limited options available, the ones you may want could not be available. For some business owners, this realisation may come too late and only after the website has been established, leaving them caught in a bad situation.
  Customized website application solutions are the way to go if you want to properly represent your business online. From increased functionality options, to fully scalable solutions that will grow with you and your business. CakeDC, the experts behind CakePHP, can offer you solutions that will answer every problem you have previously encountered with cheaper and less secure development solutions.

Building an RBAC based application in ...

This is the second article about RBAC in CakePHP series (2/2). In our previous post we did a quick introduction to RBAC and how to setup CakeDC/Auth plugin in an example project, dealing with basic array based rules. Today we'll talk about how to debug rules, and provide complex Auth rules to check permissions. We'll also discuss how to encapsulate the rules logic into `Rules` classes, and how to deal with RBAC in big projects.  

Debugging rules

Notice when debug is enabled, a detailed trace of the matched rule allowing a given action is logged into debug.log For example: 2017-10-04 23:58:10 Debug: For {"prefix":null,"plugin":null,"extension":null,"controller":"Categories","action":"index","role":"admin"} --> Rule matched {"role":"*","controller":"*","action":["index","view"],"allowed":true} with result = 1 This log could save you some time while debugging why a specific action is granted.

Callbacks for complex authentication rules

Let's imagine a more complex rule, for example, we want to block access to the articles/add action if the user has more than 3 articles already created. In this case we are going to use a callback to define at runtime the result of the allowed key in the rule. [ 'role' => '*', 'controller' => 'Articles', 'action' => 'add', 'allowed' => function (array $user, $role, \Cake\Http\ServerRequest $request) { $userId = $user['id'] ?? null; if (!$userId) { return false; } $articlesCount = \Cake\ORM\TableRegistry::get('Articles')->findByUserId($userId)->count(); return $articlesCount <= 3; } ],

Rules example

As previously discussed, we have the ability to create complex logic to check if a given role is allowed to access an action, but we could also extend this concept to define permission rules that affect specific users. One common use case is allowing the owner of the resource access to a restricted set of actions, for example the author of a given article could have access to edit and delete the entry. This case was so common that we've included a predefined Rule class you can use after minimal configuration. The final rule would be like this one: [ 'role' => '*', 'controller' => 'Articles', 'action' => ['edit', 'delete'], 'allowed' => new \CakeDC\Auth\Rbac\Rules\Owner(), ], The Owner rule will use by default the user_id field in articles table to match the logged in user id. You can customize the columns, and how the article id is extracted. This covers most of the cases where you need to identify the owner of a given row to assign specific permissions.

Other considerations

Permissions and big projects

Having permission rules in a single file could be a solution for small projects, but when they grow, it's usually hard to manage them. How could we deal with the complexity?
  • Break permission file into additional configuration files
  • Per role, usually a good idea when you have a different set of permissions per role. You can use the Configure class to append the permissions, usually having a defaults file with common permissions would be a good idea, then you can read N files, one per role to apply the specific permissions per role.
  • Per feature/plugin, useful when you have a lot of actions, and a small set of roles, or when the roles are mostly the same regarding permissions, with a couple changes between them. In this case you will define the rules in N files, each one covering a subset of the actions in your application, for example invoices.php file would add the pemissions to the Invoices plugin. In the case you work with plugins, keep in mind you could write the permission rules inside each plugin and share/distribute the rules if you reuse the plugin in other apps (as long as the other apps will have similar roles).
  • QA and maintenance
  • It's always a good idea to think about the complexity of testing the application based on the existing roles. Automated integration testing helps a lot, but if you are planning to have some real humans doing click through, each role will multiply the time to pass a full regression test on the release. Key question here is "Do we really need this role?"
  • Having a clear and documented permissions matrix file, with roles vs actions and either "YES" | "NO" | "RuleName" in the cell value will help a lot to understand if the given role should be allowed to access to a given action. If it's a CSV file it could be actually used to create a unit test and check at least the static permission rules.
  • Debugging and tracing is also important, for that reason we've included a trace feature in CakeDC/Auth that logs to debug.log the rule matched to allow/deny a specific auth check.

About performance

Performance "could" become an issue in the case you have a huge amount of rules, and some of them would require database access to check if they are matching. As a general recommendation, remember the following tips:
  • Rules are matched top to bottom
  • Try to leave the permission rules reading the database to the end of the file
  • Cache the commonly used queries, possibly the same query will be used again soon
  • Note cache invalidation is always fun, and could lead to very complex scenarios, keep it simple
  • If you need too much context and database interaction for a given rule, maybe the check should be done elsewhere. You could give some flexibility and get some performance in return

Last words

We've collected some notes about the implementation of a RBAC based system in CakePHP using our CakeDC/Auth plugin. As stated before, there are many other ways, but this is ours, worked well on several projects and we thought it was a good idea to share it with other members of the CakePHP community to expose a possible solution for their next project Authorization flavor. Please let us know if you use it, we are always improving on them - And happy to get issues and pull requests for our open source plugins. As part of our open source work in CakeDC, we maintain many open source plugins as well as contribute to the CakePHP Community. Reference

Building an RBAC based application in ...

This is the first post of a small series covering how to setup, organize and implement an RBAC based authorization system in CakePHP using the CakeDC/Auth Plugin. We'll cover the basic concepts, setup and implementation of the basic permission rules in part 1.

What does RBAC mean in this context?

We'll use RBAC as "Role Base Access Control", meaning your app will be using the following concepts to define who can access what:
  • "Who" is an existing user, mainly identified as his role in the system, such as an "admin" or "writer", etc.
  • "What" is a specific action in your application, identified as the associated routing params, for example ['controller' => 'Posts', 'action' => 'add'].
  • A permission in this context would be a link between who, and what.

Why not ACL?

ACL is a really good choice when your answer is 'yes' to any of the following questions:
  • Do we need to let users create new roles on the fly?
  • Do we need the roles to inherit permissions (tree structure)?
  • Do we need to assign permissions NOT based on controller actions? For example CRUD based permissions, checked on the model layer for each operation on a given row.
If your answer is yes, you should consider using cakephp/acl. It provides a very powerful, reliable and flexible way to configure your permissions, but with greater power comes a bigger maintenance burden, that is keeping the acl data in your tables. Specially if you have several environments to maintain, you'll need to write migrations to populate your acl tables, then create import/export scripts and utilities to reproduce permission issues from live environments, and so on. Not an impossible task, but could increase the complexity of your project in a significant way...

Setting up CakeDC/Auth

There are other plugins you could use, but this one will cover everything you'll need, so let's go. CakeDC/Auth usually comes installed from within CakeDC/Users (a complete solution covering many more features) but today we'll set it up alone. composer require cakedc/auth bin/cake plugin load CakeDC/Auth And last, but not least, add the RBAC Auth to the list of Authorize objects. Here is a working configuration based on the blog tutorial. We'll be using the blog tutorial described in the book as an example application Change AppController.php Auth related configuration to: $this->loadComponent('Auth', [ 'authorize' => ['CakeDC/Auth.SimpleRbac'], 'loginRedirect' => [ 'controller' => 'Articles', 'action' => 'index' ], 'logoutRedirect' => [ 'controller' => 'Pages', 'action' => 'display', 'home' ] ]); With this change, we'll be using only the rules defined in config/permissions.php file. If this file is not present, default permissions will be in place. Default permissions will grant access to admin role to all actions. To override permissions, you can copy the default permissions to your project and fix the rules: cp vendor/cakedc/auth/config/permissions.php config/ Then edit this file and check the provided examples and defaults.

Using CakeDC/Auth

The core of the RBAC system is the ability to define permission rules that will match one given role with the actions granted. Rules are defined in an array, but you can extend the AbstractProvider class to retrieve the rules from somewhere else (database?). By default, nothing will be granted. Rules are evaluated top to bottom. The first rule matched will stop the evaluation, and the authentication result will be provided by the value of the allowed key. Note we can use a callback to implement complex rules, or encapsulate the rules into classes that we could reuse across projects, like the Owner rule class provided. This is an example rule [ 'role' => '*', 'plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => ['profile', 'logout'], ], We could read this rule as follows: "For any role, we grant access to actions 'profile' and 'logout' in the Users controller in plugin CakeDC/Users". Note default allowed value is true, we can use an array, or a string to determine the role, plugin, controller and action. We can also use * in the value to match anything or use * at the start of the key to match anything but the values, for example '*controller' => 'Users', would match all the controllers but 'Users'.

Simple Rules

As our first objective, we are going to grant access to all the index and view pages, using the rule [ 'role' => '*', 'controller' => '*', 'action' => ['index', 'view'], ],
Stay tuned for the second post, where we'll deal with complex rules, rule classes and implementation tips for complex applications...

Has your website been hacked? Learn mo...

If you have a website and have not made the necessary security precautions, then you may become victim to hacking.   Besides the obvious defacing that can take place once your website has fallen victim, here are some other signs you have been hacked:

  • Your website redirects to another site, not your own.
  • Google or Bing notifies you.
  • Your browser indicates that your site is not secure.
  • You notice a change in your website traffic, especially from different countries.
  So you’ve been hacked - what do you do? Where do you start?   We’ve put together a few things that you need to look into as soon as possible!  
  • Do you have a support team? Contact them!
In this situation, it is best to immediately contact your technical support - your web developers who have experience in how to handle these situations. From what to shut down, what to look for and where to check. Someone without the technical expertise to help you is going to have difficulty properly fixing things!  
  • Get together all of the information required for your support team
Your support team will need all the access information, so start putting this together - things they will need access to include your CMS; hosting provider and login details; web logs, FTP/sFTP access credentials as well as any back ups you may have. If you have never been hacked or do not have regular back ups running - here’s a good place to start.  
  • Temporarily take your website down
If you haven’t already done so, make sure to take your site down temporarily. While you are doing this, it is also important to check all your servers and computers for malware, spyware or trojans. And if you have a virtual server, it may be in the best interest to start over - some attacks leave software that may not be visible or you may not know what to look for.  
  • Change your passwords
Make sure to change your passwords! Not sure what to use? For the best security, make use of a password generator that includes both letters and numbers of more than 12.
  For expert development and consultation services, give CakeDC a call - we lead, so you can lead.

We Bake with CakePHP