CakeDC Blog

TIPS, INSIGHTS AND THE LATEST FROM THE EXPERTS BEHIND CAKEPHP

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?).

Setup

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)

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.

Ownership

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!

 

Latest articles

CakeFest 2019 Recap

Here we are, a couple weeks out of CakeFest 2019. What an experience in Japan!  We didn’t really know what to expect when we decided to finally make the trip to host in Tokyo. We were given great welcoming from the PHP community, and each person we met left us with wonderful memories. Another welcoming surprise was the low price of food, and delicious ramen. Our team definitely utilized all of the free time we had.            Let’s talk about the event, and the workshops. Jorge Gonzalez, Jose Rodriquez, and Mark Story definitely delivered in the knowledge department. The participation was fantastic, although the class size was smaller than in other years. We’ve had a lot of requests for their slides, so those are included in the link below ⬇️ One thing that was different this year, is that we had different venues for the workshops and conference. This makes it difficult for the team, with transferring our equipment in such a busy city (shout out to the quick responding taxi services).  We did try the metro when we had less baggage, and got up close and personal with the locals. Speaking of venues, we cannot thank DMM.com and SmartNews enough. We are still dreaming of an office like DMM’s with live plants growing up the walls and a complete installed watering system.  These venues were overly accommodating, making this one of the best conferences we’ve had.          If you are a PHPer or specifically working with CakePHP, the speakers topics were overflowing with useful information. Like Yuki Kanazawa’s tips for a smooth upgrade to CakePHP 3, or Tadahisa Motooka’s ideas about database replication. Kazuki Higashiguchi helped talk us through painful testing of code, and Sho Ito walked us through an initial OSS with CakePHP. We had such a great lineup this year, and we cannot wait to have some speakers return. Other great talks included David Yell, Daniel Voyce, Jose Gonzalez, and Wim Godden, and superstar core members Mark Story and Jose Rodriguez.  We even had to be confronted with details about life after CakePHP (GASP!) from Andrej Griniuk.    Unfortunately, no event can be executed without some roadblocks, and we aren’t exempt. We had a couple late cancellations (understandable) from speakers, but definitely made up the time with chats and lightning talks. There was so much information exerted during the short 2 days, that we all probably needed and extra day to take notes. Luckily, we did that for you. All of the slides included during CakeFest are available at the link below as well.    So, would we come back and host in Japan again? YES! We hope to do so sooner rather than later. Are there some things we will change on our end? Yes, again.  We hoped for higher numbers for workshops, as the information given is invaluable. We hope that in the future, all conference attendees will take advantage of those sessions as well. You can stay up to date with all things CakeFest at CakeFest.org - we are actually working on adding a history feature to reference past events.      We could not have done all of this without the amazing sponsors we had this year:    Cake Development Corporation  Shizen Energy  Base  Lancers  DMM JetBrains ConneHito  Marks Software SmartNews  ESM   Follow our speakers on Twitter:   Yuki Kanazawa - @yakitori009  Mark Story - @mark_story Jose Rodriguez - @jose_zap Jorge Gonzalez - @steinkelz Tadahisa Motooka - @t_motooka Kazuki Higashiguchi -  @hgsgtk Sho Ito - @itosho David Yell - @Yelldavid Daniel Voyce - @voycey_web Jose Gonzalez - @savant Wim Godden - @wimgtr Andrej Griniuk - @andrej_gr   CLICK HERE to view the CakeFest 2019 workshop and speaker slides.   Now, we want to hear from you! If you attended, what did you think about CakeFest Japan? What did you enjoy the most/least? If you did not attend: what has held you back from joining us? Let us know - email: community@cakephp.org.

How To: CakePHP, CakeDC Users and Amazon Cognito

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'); } 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', ];
  • 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
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.

We Bake with CakePHP