• Contact Us
  • About Us
  • Privacy policy
  • Disclaimer and Limitation of Liability
Subscribe RSS
Home » Cakephp » Auth Component of Cakephp Demystified Part-1

Auth Component of Cakephp Demystified Part-1

July 21, 2012 Posted by kaswan under Cakephp
No Comments

In today’s Internet era most of the web developers tries to provide a log in/signup based feature for web clients in their web applications. Mostly this type of feature is needed only when you want to categories your users a very common example is Guest users and Registered Users. Guest users can access less content on web app while registered users enjoys more privileges.

In cakephp this attribute is implemented mostly with the Auth component of this framework. Auth component is a very powerful, robust and can be customized as par the needs of web application. Auth component allows you to quickly set up
secure areas in your app. In this series we will be building a complex authentication system. As this is part 1 and starting of this series, in this part we will implement a very basic but fully working authentication scheme.

Getting ready

First of all we need to create a users table in our database to store username and password (hashed version of user’s password). This hashing is done automatically by Auth component using it’s method hashPasswords() when it finds password in $data.

Run below sql to create users table.

1
2
3
4
5
6
CREATE TABLE `users` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`username` VARCHAR(255) NOT NULL,
`password` CHAR(40) NOT NULL,
PRIMARY KEY(`id`)
);

List of all files we will be creating in this post.

  • AppController.php in /app/ folder
  • UsersController.php in /app/controllers/ folder
  • login.ctp in /app/views/users/ folder
  • signup.ctp in /app/views/users/ folder


AppController.php File

This file mainly contains global data which is used by all controllers of the application, in our case we have only users controller. This file will be containing below code.

1
2
3
4
5
6
7
<?php
class AppController extends Controller {
       var $components = array('Session','Auth');
       var $helpers=array('Session');
 
}
?>

Explanation :

It has two variables one is $components and other one is $helpers. $components variable holds all the components utilized by all controllers, so we specified Auth component. Session component and Session helper is basically used to set session messages and show those messages in view respectively.

UsersController.php File

This is the heart of our logic. It contains functionality of login, signup and logout. Content of this file is…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
class UsersController extends AppController {
    
    function beforeFilter() {
            parent::beforeFilter();
            $this->Auth->allow('signup');
      }
    function login() {}
 
    function logout()
    {
        $this->Session->setFlash('You are logged out!');
        $this->redirect($this->Auth->logout());
    }
    function signup()
    {
        if (!empty($this->data)) {
              $this->User->create();
              if ($this->User->save($this->data)) {
              $this->Session->setFlash('User saved!');
              $this->redirect(array('action'=>'login'));
            }
       else {
               $this->Session->setFlash('User not saved! There were some errors. Please rectify them and retry.');
             }
 
            }
      
          }
 
}
?>

Explanation :

First of all, as it is inheriting from AppController, it will have Auth component loaded by default which will process all requests of client. Auth component only allows to access only login function, so to access signup() for adding new users we need beforeFilter() to give that instruction to Auth component to allow signup(). The main thing here to learn is that before Auth component start it’s working, beforeFilter() is invoked. In this we are invoking two beforeFilters one of users controller and other on of app controller by using parent::beforeFilter();

Second function is login(), which is basically called if you put http://www.your_domain_name.com/users/login/ in your URL of browser or if you try to access a restricted area of application. When you submit your data by login.ctp file which is view file for this login function then Auth component starts working. First of all it hashes the password field of $data and passes this $data variable to Users Model. Then Model checks and results back to controller. If a valid user is found then Auth adds it in session and grants access to all functions to which it is authorized which is checked by isAuthorized(). But if it finds invalid user, it redirects back to login().

Third function is logout(), in this function we sets a session’s flash message to let user know that he/she has been logged out. On second line of this function we calling redirect method of controller, which is taking argument from $this->Auth->logout() which is a string containing url to login method.

Our last method is signup(), this is created to add new users. In this we are using create() and save() methods of User Model. Create method initializes the model for writing a new record, loading the default values for those fields that are not defined in $data, and clearing previous validation
errors. Especially helpful for saving data in loops. Save method saves model data (based on white-list, if supplied) to the database. By default, validation occurs before save.

login.ctp File

It holds presentation code.Code is…

1
2
3
4
5
6
7
<?php
 
echo $this->Form->create(array('action'=>'login));
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('Login');
?>

Explanation :

This view file utilizes Form Helper to create form elements.

signup.ctp File

It also holds presentation code.In this we have a form so user could submit it with data to create new user…

1
2
3
4
5
6
7
<?php
 
echo $this->Form->create(array('action'=>'signup));
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('Signup');
?>

Jump to Auth Component of Cakephp Demystified Part-2

If you liked this post then plz share on these sites
  • Myspace
  • Tweet
Posts that you may find interesting...
Check username availability using jquery in cakephp
Verify password and confirm password fields are equal or not in cakephp
Integrating cakephp with OpenId
Tags: Auth Component, Cakephp
« Create posts template in photoshop for your blog
Steps Of Ethical Hacking »
  • Latest Posts
  • Random Posts
  • Top 3 Command Prompt Tricks and Hacks
  • how to increase Alexa Rank
  • scrapebox cracked
  • List of top Directories For Backlinks
  • Scrapebox download
  • Scrapebox
  • How to Earn Money through Facebook Fan page
  • Wiki List Scraper for Free
  • How to recover a Facebook stoled page ?
  • Security in terms of Hacking
  • Speeding Up Windows Vista - Easy Ways To Accomplish This
  • How to spy on a cell phone
  • File System Table (FSTAB) in Linux
  • A simple c project
  • wordpress Compromised
  • What is rapidleech ? A simple guide
  • GNIIT course some real insights
  • Facebook Trick
  • Destructors in c++
  • namespace in c plus plus
  • Categories
  • Latest Comments
  • Blogging
  • C and C++ Interview questions
  • C++ Stuff
  • C-related Stuff
    • c tutorials for beginners
    • simple c tutorial
  • Cakephp
  • Campus Placement
  • Cloud Computing
  • College Projects
  • Data Structures
  • Digital Forensic
  • Facebook
  • Google Technology
  • GSM
  • Hacking
    • ABC of Hacking
    • ARP Poisoning
    • Command Prompt
    • Cross Site Request Forgery
    • DNS Poisoning
    • Facebook hacking
    • HBCD
    • Mobile hacking
      • Tethering
    • SQl injection
    • Truecrypt
    • Wireshark
  • Internet
  • Jquery
  • knowledge
  • linux
  • Mobile World
  • My notes On Education
  • N computing
  • Networking
  • Photoshop
  • Search Engine Optimization
  • SEO
  • Software Knowledge
  • Tips and tricks
  • Uncategorized
  • Web Design
  • Web Services



Recent Posts
  • Top 3 Command Prompt Tricks and Hacks
  • how to increase Alexa Rank
  • scrapebox cracked
  • List of top Directories For Backlinks
  • Scrapebox download
Recent Comments
  • Brad Haccer on How to Bypass Facebook Phone Verification
  • How to bye pass Firewall 2 - CrazyLearner.com on How to bye pass Firewall
  • Ethical Hacking Overview - CrazyLearner.com on Types of hacker
  • Nicholas Marturano on How to hack mobile number
  • cycoshas on What is rapidleech ? A simple guide
© CrazyLearner 2013 • Designed by Adhya Solutions