CakeDC Blog


CakePHP Facebook login using CakeDC Us...

IMPORTANT: This tutorial is old, please check the updated Facebook version for CakeDC Users Plugin 3.1.5
  If you are using an old version, we recommend to migrate to latest version of the plugin. We'll keep this article online for some more time....   The CakeDC Users Plugin provides an easy way to integrate Facebook social login into your application. This is a short how-to tutorial to enable Facebook login. We'll assume you have a brand new CakePHP 3 application already setup.


Use composer to install the CakeDC Users Plugin composer require cakedc/users:~3.1.0 composer require opauth/opauth:1.0.x-dev composer require opauth/facebook:1.0.x-dev Now update your composer.json file adding the following repository override, to use our own fork of the Facebook Strategy, as the main repo is not maintained "repositories": [ { "type": "vcs", "url": "" } ], Note we are using the 3.1 version, matching the CakePHP 3.1 compatible version of the Plugin, check the compatibility matrix to find the right version for your current CakePHP version. Load it from your bootstrap.php file Plugin::load('CakeDC/Users', ['routes' => true, 'bootstrap' => true]); Run migrations to add 2 new tables: 'users' and 'social_accounts' bin/cake migrations migrate -p CakeDC/Users


Load the Component in your src/Controller/AppController.php public function initialize() { parent::initialize(); // // ... // $this->loadComponent('CakeDC/Users.UsersAuth'); } login page output

Create a new Facebook application

  • Go to Facebook developers and log in
  • Create a new Facebook application new Facebook app
  • Click "website" and select some awesome name for your brand new app (yeah, some random name would work too)
  • Pick a Category, complete the quick start form, etc.
  • Once you are done, go to your newly created app and click "settings"
  • In settings, you should add your domain to "App domains" and ensure there is at least one login platform = "Website" defined
  • Copy your App ID and secret

Setup the Plugin to use your Facebook app for login

Now you have a working Facebook app configured, we are going to link the CakeDC Users Plugin to use the app for login. Update your bootstrap.php file to customize the CakeDC Users Plugin Configure::write('Users.config', ['users']);   Plugin::load('CakeDC/Users', ['routes' => true, 'bootstrap' => true]); Create a new "config/users.php" file with contents return [ 'Opauth.Strategy.Facebook.app_id' => 'YOUR APP ID', 'Opauth.Strategy.Facebook.app_secret' => 'YOUR APP SECRET', //etc ]; This file will override any configuration key present in the Plugin, you can check the configuration options here Configuration. You are done! Now the "login with Facebook" link (in "/login" page) will open the Facebook login popup and connect back to your application. If the email is provided by the user, he'll be automatically registered using the default role = 'user'. If no email is provided, the user will be requested to enter an email to complete the registration process in your application. Once his email is validated (link sent via email), he'll be able to login using Facebook.

Read more about CakeDC Users Plugin

Giving back to the community

This Plugin's development has been sponsored by the Cake Development Corporation. Contact us if you are interested in:
  • Professional, commercial CakePHP development and consultancy
  • Professional CakePHP training
  • CakePHP code reviews
We hope you've enjoyed this short tutorial covering the Facebook login, stay tunned for new CakePHP + Users Plugin tutorials coming soon...  

CakeDC Users Plugin for CakePHP 3

IMPORTANT: This tutorial is old, please check the updated CakeDC Users Plugin for CakePHP 3
  If you are using an old version, we recommend to migrate to latest version of the plugin. We'll keep this article online for some more time....   Welcome to our first tutorial covering the new CakeDC Users Plugin for CakePHP 3. In this tutorial we'll setup and configure the Plugin, introducing some of the available features. We'll assume you are starting a new CakePHP 3.1 application, with some existing tables (blog site maybe?).


Easy thing, let's use composer to install the CakeDC Users Plugin composer require cakedc/users:~3.1.0 Note we use 3.1.x branch and tags for the CakePHP 3.1 branch, and 3.0.x and tags for the 3.0 version of the framework. Now ensure the Plugin is loaded from your bootstrap.php file Plugin::load('CakeDC/Users', ['routes' => true, 'bootstrap' => true]); Create some tables to store the users in your database bin/cake migrations migrate -p CakeDC/Users This migration will create 2 tables into your database, "users" where the users and credentials are stored, and "social_accounts" where the tokens for the social login feature will be stored and managed. Now you can register a new user (ensure your CakePHP is able to send emails to get your validation link correctly), or you could use the provided shell to create new users from the command line bin/cake users addSuperuser output for the shell command to generate new superuser This new super user will be granted full administrative permissions (check the src/Auth/SuperuserAuthorize class for more details and configuration)


Load the Component in your src/Controller/AppController.php public function initialize() { parent::initialize(); // // ... // $this->loadComponent('CakeDC/Users.UsersAuth'); } login page output Now you have the Plugin installed and a brand new superuser granted with full permissions, it's time to configure permissions for the rest of the roles you'll need.

Simple role based permission rules

By default, the CakeDC Users Plugin allow users to register, and all new users are assigned role = 'user' by default. Note you can change the default role name assigned to new users, but we'll keep the 'user' role for now. Let's assume you have some controller with a couple actions you want to allow, for example "/posts/view/*" We are going to configure SimpleRBAC to allow the role = 'user' accessing the 'view' action: Create a new file "config/permissions.php" with the following contents return [ 'Users.SimpleRbac.permissions' => [ [ 'role' => 'user', 'controller' => 'Posts', 'action' => ['view'], ], ] ]; Now you've defined your first permission rule, allowing users with role = 'user' to access the /posts/view action, note you can use wildcards '*', and arrays to cofigure your rules. Cool, so now you have users in your application, allowing new users to register, validate their emails, login, change password, and use cookies to remember login. In our next short tutorial we'll cover Facebook login and Twitter login.


What about ownership? We are talking about posts, and possibly you'll need to allow the post author to edit his own post, the good news: this is super easy with CakeDC Users Plugin. Add a new rule to allow only the owner of a given post to edit it. Update your permissions.php file, adding this rule: use Cake\ORM\TableRegistry; use Cake\Utility\Hash; return [ 'Users.SimpleRbac.permissions' => [ [ 'role' => 'user', 'controller' => 'Posts', 'action' => ['view'], ], [ 'role' => 'user', 'controller' => 'Posts', 'action' => ['edit', 'delete'], 'allowed' => function (array $user, $role, Request $request) { $postId = Hash::get($request->params, 'pass.0'); $post = TableRegistry::get('Posts')->get($postId); $userId = Hash::get($user, 'id'); if (!empty($post->user_id) && !empty($userId)) { return $post->user_id === $userId; } return false; } ], ] ]; And we're done, you've configured ownership permissions for your ['edit', 'delete'] actions. Check other examples in the CakeDC Users Plugin Docs

Read more about CakeDC Users Plugin

Giving back to the community

This Plugin's development has been sponsored by the Cake Development Corporation. Contact us if you are interested in: We'll continue working on our open source plugins (like this one) to give back to the amazing CakePHP Community!  

CakePHP 2 Application Cookbook

Today we just released a new book on CakePHP, appropriately titled the CakePHP 2 Application Cookbook. Published by Packt Publishing (ISBN 978-1782160083), and also available on Amazon, Safari and Barnes and Noble, in both printed and e-book formats, this title delivers over 60 tutorials aimed at providing you a nice bite into CakePHP, and getting you familiarized with common approaches and techniques when building applications using the framework. Each tutorial takes you from set up, to implementation, and then an in-depth overview of how it all works, so you can easily jump in on the topics that are most important to you. For a while now the community had been asking for a book on the framework, and earlier this year some of us at CakeDC jumped on the opportunity to accept the challenge. As we didn't want to write a book which was just an echo of the documentation, we took the initiative to determine which issues were really most relevant to the community. We did this by collecting the most popular questions from support sites, such as Stack Overflow, which covered topics such as how to use certain features or perform common actions with the framework. We then ranked those in order of frequency, and proposed solutions for each one, putting together what we consider to be a comprehensive guide as to how to get the job done fast and done right. While we did our best to approach each topic with a rapid and sensible solution, we were constantly aware of the possibility of the uneven level of technical knowledge each reader may have. So, we tried where possible to keep the examples inline with simple or reasonably understandable parameters, to reduce any additional knowledge which could be required for each tutorial. We hope no one feels too far out of their depth! The process itself was somewhat new to us, especially with a serious and noteworthy publisher leading the effort, but we managed to make it through in around 2-3 months of late nights and ridiculous dedication, including various phases of review and corrections. That said, we did all of this while also juggling our professional work at the Cake Development Corporation, our personal lives, and in my case, also organizing CakeFest 2014, the annual CakePHP conference. It's something I would definitely recommend if you love to teach and share your knowledge, whatever topic that may be. So, grab your copy of the book from the Packt online store, or from Amazon, Safari or Barnes and Noble, in either printed or e-book format. We'll be donating 100% of the royalties from sales of the book to the Cake Software Foundation, so that everything you give goes straight to CakePHP, to help keep the project strong. That's how much we love this community! We hope you take something away from the scenarios we take on, and hopefully enjoy working even more with the framework. As always, we're very active in the community, so if you have any feedback or suggestions, feel free to reach out to us. Here's to many more years of delicious cake, it was never a lie!

CakeDC Git Workflow - Working Together

In our previous posts on the CakeDC Git Workflow we shared some insight on how the development strategy works, and how to get the most out of it. But one of the most important benefits it provides is the increased stability and consistency when working alongside others.

Collaboration and Code Review

Working in a team means that you can usually borrow someone else's eyes. In a cooperative and fast-paced environment, you have to. Period. And one situation that typically arises for this case during development is the "code review". $ git checkout -t origin/feature/1234 $ git checkout -b review/1234 $ git push -u origin review/1234 Here, the reviewer fetched the feature/1234 branch, then created and pushed their own review/1234 branch. Then, they may propose some changes to the original code, for example: $ git commit -m "Optimized this and that" Once the review is complete, they'd then simply push their changes, like so: ... rebase ... $ git push Now you can use their branch, separately of your own, to clearly view the proposed changes. $ git checkout -t origin/review/1234 $ git diff review/1234 feature/1234 And when everything is done and ready, just merge those changes in. $ git checkout feature/1234 $ git merge review/1234 ... rebase ... $ git push Finally, don't forget to always do some cleanup. $ git branch -d review/1234 $ git push origin :review/1234 Like this, even that single reviewer's commit (assuming it wasn't squashed in some following rebase) is done in different branch, and clearly tied to the ID of the feature, keeping the story of your code clean and consistent for others.

Maintenance tasks

Using our workflow you'll find that both you and your coworkers will delete remote branches quite often. From time to time, it's good to remove references to non-existing remote branches from your local repository, as you don't want to see redundant branches in your git branch -av list. For this, you can simply prune your branches. $ git remote prune origin And don't be afraid to be completely thorough when cleaning the repository up, go for it all! $ git gc && git clean -dfx && git stash clear

No fast forward merges

Sometimes it's just plain tedious to write --no-ff all the time, especially when we can set up git so we only use --ff when required. Via your project's git configuration file, you can either disable fast forwards for all merges directly, like so: [merge] ff = false Or, just for selected (permanent in this case) branches only: [branch "master"] mergeoptions = --no-ff [branch "stage"] mergeoptions = --no-ff [branch "qa"] mergeoptions = --no-ff [branch "develop"] mergeoptions = --no-ff Then, for those cases where fast forward is desired, just use the --ff switch: $ git checkout develop $ git pull --ff This is especially useful when you're collaborating with others, and those commits are flying around between you. Last thing you want is to get bogged down in merge conflicts!

Users plugin 2.1.0 released

We just released version 2.1.0 of the CakeDC Users plugin for CakePHP, and with it a collection of bug fixes and improvements, an update of the code to 2.5, as well as a reformatting of the documentation inline with the CakeDC Plugin Standard. If you haven't used the Users plugin yet, it's a great addition to any application which requires user registration, log in and management. The plugin also provide simple role handling, as well as user search if you combine it with the CakeDC Search plugin. Including the plugin is as easy as adding it to your application, running the schema or migration to add the tables used by the plugin, then simply navigate to one of the actions provided, for example: /users/users/login You may want to provide more specific routes, inline with your application, for example: Router::connect('/login', array( 'plugin' => 'users', 'controller' => 'users', 'action' => 'login' )); However, you’ll usually want to fine tune the experience for your users, for which you can extend the controller provided with the plugin and override the actions it includes to customize your own logic. class ExampleController extends UsersController { } There are also many configuration options available, if you'd simply want to configure how the plugin behaves. But, if you'd like a more decoupled approach you can also take advantage of the events, which are triggered by the plugin at different points of the user workflow. Features such as sign-up, log in, remember me, account verification and password reset are provided by default with the Users plugin. It also sends tokens to users via email as a security measure for certain actions. Additionally, the plugin comes with a basic user management interface, ready for admins to manage users in your application. As always, our plugins are released as Open Source free of charge, and benefit directly from the numerous contributions made by the CakePHP community. We want to thank all of the contributors to the Users plugin, and hope that future involvement helps keep the framework ecosystem strong, with a host of powerful plugins that keep you all building great applications.

We Bake with CakePHP