How to Services in CakePHP

Services in CakePHP

Authentication

Components are the service layer in CakePHP, Authentication is the process of identifying the correct user. CakePHP supports three types of authentication.

  • FormAuthenticate − It allows you to authenticate users based on form POST data. Usually this is a login form that users enter information into. This is default authentication method.
  • BasicAuthenticate − It allows you to authenticate users using Basic HTTP authentication.
  • DigestAuthenticate − It allows you to authenticate users using Digest HTTP authentication.

Example for FormAuthentication

Make changes in the config/routes.php file as shown in the following code.

config/routes.php

<?php
   use Cake\Core\Plugin;
   use Cake\Routing\RouteBuilder;
   use Cake\Routing\Router;

   Router::defaultRouteClass('DashedRoute');
   Router::scope('/', function (RouteBuilder $routes) {
      $routes->connect('/auth',['controller'=>'Authexs','action'=>'index']);
      $routes->connect('/login',['controller'=>'Authexs','action'=>'login']);
      $routes->connect('/logout',['controller'=>'Authexs','action'=>'logout']);
      $routes->fallbacks('DashedRoute');
   });
   Plugin::routes();

Change the code of AppController.php file as shown in the following program.

src/Controller/AppController.php

<?php
   namespace App\Controller;
   use Cake\Controller\Controller;
   use Cake\Event\Event;
   use Cake\Controller\Component\AuthComponent;

   class AppController extends Controller{
      public function initialize(){
         parent::initialize();
         
         $this->loadComponent('RequestHandler');
         $this->loadComponent('Flash');
         $this->loadComponent('Auth', [
            'authenticate' => [
               'Form' => [
                  'fields' => ['username' => 'username', 'password' => 'password']
               ]
            ],
            'loginAction' => ['controller' => 'Authexs', 'action' => 'login'],
            'loginRedirect' => ['controller' => 'Authexs', 'action' => 'index'],
            'logoutRedirect' => ['controller' => 'Authexs', 'action' => 'login']
         ]);
      
         $this->Auth->config('authenticate', [
            AuthComponent::ALL => ['userModel' => 'users'], 'Form']);
      }
   
      public function beforeRender(Event $event){
         if (!array_key_exists('_serialize', $this=>viewVars) &&
         in_array($this->response=>type(), ['application/json', 'application/xml'])) {
            $this->set('_serialize', true);
         }
      }
   }

Create AuthexsController.php file at src/Controller/AuthexsController.php. Copy the following code in the controller file.

src/Controller/AuthexsController.php

<?php
   namespace App\Controller;
   use App\Controller\AppController;
   use Cake\ORM\TableRegistry;
   use Cake\Datasource\ConnectionManager;
   use Cake\Event\Event;
   use Cake\Auth\DefaultPasswordHasher;

   class AuthexsController extends AppController{
      var $components = array('Auth');
      public function index(){
      }
      public function login(){
         if($this->request->is('post')){
            $user = $this->Auth->identify();
            
            if($user){
               $this->Auth->setUser($user);
               return $this->redirect($this->Auth->redirectUrl());
            } else
            $this->Flash->error('Your username or password is incorrect.');
         }
      }
      public function logout(){
         return $this->redirect($this->Auth->logout());
      }
   }
?>

Create a directory Authexs at src/Template and under that directory create a View file called login.ctp. Copy the following code in that file.

src/Template/Authexs/login.ctp

<?php
   echo $this->Form->create();
   echo $this->Form->input('username');
   echo $this->Form->input('password');
   echo $this->Form->button('Submit');
   echo $this->Form->end();
?>

Create another View file called logout.ctp. Copy the following code in that file.

src/Template/Authexs/logout.ctp

You are successfully loggedout.

Create another View file called index.ctp. Copy the following code in that file.

src/Template/Authexs/index.ctp

You are successfully logged in. 
<?php echo 
   $this->Html->link('logout',["controller" => "Authexs","action" => "logout"]); 
?>

Execute the above example by visiting the following URL.

http://localhost:85/CakePHP/auth

Output

As the authentication has been implemented so once you try to visit the above URL, you will be redirected to the login page as shown below.

Services Authexes

After providing the correct credentials, you will be logged in and redirected to the screen as shown below.

Services Auth

After clicking on the logout link, you will be redirected to the login screen again.

How to Create Validators in CakePHP

Create Validators in CakePHP

Validator can be created by adding the following two lines in the controller.

use CakeValidationValidator; $validator = new Validator();

Validating Data

Once we have created validator, we can use the validator object to validate data. The following code explains how we can validate data for login webpage.

$validator->notEmpty(‘username’, ‘We need username.’)->add(‘username’, ‘validFormat’, [‘rule’ => ’email’,’message’ => ‘E-mail must be valid’]); $validator->notEmpty(‘password’, ‘We need password.’); $errors = $validator->errors($this->request->data());

Using the $validator object we have first called the notEmpty() method which will ensure that the username must not be empty. After that we have chained the add() method to add one more validation for proper email format.

After that we have added validation for password field with notEmpty() method which will confirms that password field must not be empty.

Example

Make Changes in the config/routes.php file as shown in the following program.

config/routes.php

<?php use CakeCorePlugin; use CakeRoutingRouteBuilder; use CakeRoutingRouter; Router::defaultRouteClass(‘DashedRoute’); Router::scope(‘/’, function (RouteBuilder $routes) { $routes->connect(‘validation’,[‘controller’=>’Valids’,’action’=>’index’]); $routes->fallbacks(‘DashedRoute’); }); Plugin::routes();

Create a ValidsController.php file at src/Controller/ValidsController.php. Copy the following code in the controller file.

src/Controller/ValidsController.php

<?php namespace AppController; use AppControllerAppController; use CakeValidationValidator; class ValidsController extends AppController{ public function index(){ $validator = new Validator(); $validator->notEmpty(‘username’, ‘We need username.’) ->add(‘username’, ‘validFormat’, [‘rule’ => ’email’,’message’ => ‘E-mail must be valid’]); $validator->notEmpty(‘password’, ‘We need password.’); $errors = $validator->errors($this->request->data()); $this->set(‘errors’,$errors); } } ?>

Create a directory Valids at src/Template and under that directory create a View file called index.ctp. Copy the following code in that file.

src/Template/Valids/index.ctp

<?php if($errors){ foreach($errors as $error) foreach($error as $msg) echo ‘<font color = “red”>’.$msg.'</font&gtl’; } else { echo “No errors.”; } echo $this->Form->create(“Logins”,array(‘url’=>’/validation’)); echo $this->Form->input(‘username’); echo $this->Form->input(‘password’); echo $this->Form->button(‘Submit’); echo $this->Form->end(); ?>

Execute the above example by visiting the following URL −http://localhost:85/CakePHP/validation

Output

Click on the submit button without entering anything.