core components

Upload: praksophy4252

Post on 30-May-2018

232 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/14/2019 Core Components

    1/40

    1.2 Collection

    1.1 Collection

    General

    Welcome to The Cookbook

    CakePHP API Docs Bakery Live Forge Trac

    S

    The Manual Core Components

    5 Core Components

    dit Comments (0) History

    akePHP has a number of built-in components. They provide out of the box

    unctionality for several commonly used tasks.

    o learn more about each component see the menu on the left, or learn more

    bout creating your own components.

    ee comments for this section

    5.1 Access Control Listsdit View just this section Comments (2) History

    akePHP's access control list functionality is one of the most oft-discussed,most likely because it is the most sought after, but also because it can be the

    most confusing. If you're looking for a good way to get started with ACLs in

    eneral, read on.

    e brave and stick with it, even if the going gets rough. Once you get the hang

    f it, it's an extremely powerful tool to have on hand when developing your

    pplication.

    ee comments for this section

    5.1.1 Understanding How ACL Worksdit View just this section Comments (0) History

    AclThe Acl component provides an easy to use interface fordatabase and ini based access control lists.

    Auth

    The auth component provides an easy to useauthentication system using a variety of authenticationprocesses, such as controller callbacks, Acl, or Objectcallbacks.

    SessionThe session component provides a storage independent

    wrapper to PHP's sessions.

    RequestHandlerThe request handler allows you to introspect further intothe requests your visitors and inform your applicationabout the content types and requested information.

    SecurityThe security component allows you to set tighter securityand use and manage HTTP authentication.

    EmailAn interface that can be used to send emails using one ofseveral mail transfer agents including php's mail() andsmtp.

    CookieThe cookie component behaves in a similar fashion to theSessionComponent in that it provides a wrapper for PHP's

    native cookie support.

    Table of Contents :Manual

    1 Beginning With

    CakePHP

    2 Basic Principles ofCakePHP

    3 Developing withCakePHP

    4 Common Tasks WCakePHP

    5 Core Component

    5.1 Access ConLists

    5.2 Authenticat

    5.3 Cookies

    5.4 Email

    5.5 Request Ha

    5.6 SecurityComponent

    5.7 Sessions

    6 Core Behaviors

    7 Core Helpers

    8 Core Utility Librar

    9 Core ConsoleApplications

    10 Example Applica

    11 Appendices

    Options

    All in one pageSuggest a new sechere

    Feeds

    Comments for CorComponents

    Change history forComponents

    Login Top Contributors Todo About CakePHP Don

    /book.cakephp.org/complete/170/Core-Components

    http://book.cakephp.org/complete/170/Core-Components#Request-Handling-174http://book.cakephp.org/complete/170/Core-Components#Access-Control-Lists-171http://book.cakephp.org/add/170/Core-Componentshttp://book.cakephp.org/add/170/Core-Componentshttp://book.cakephp.org/complete/170/Core-Components#Understanding-How-ACL-Works-465http://cakephp.org/http://book.cakephp.org/http://bakery.cakephp.org/http://live.cakephp.org/http://cakeforge.org/http://book.cakephp.org/users/loginhttp://book.cakephp.org/statshttp://book.cakephp.org/todohttp://cakephp.org/http://book.cakephp.org/complete/3/The-Manualhttp://book.cakephp.org/http://book.cakephp.org/view/2/x1-2-Collectionhttp://book.cakephp.org/view/304/x1-1-Collectionhttp://book.cakephp.org/view/304/x1-1-Collectionhttp://book.cakephp.org/edit/170/Core-Componentshttp://book.cakephp.org/complete/170/Core-Components#comments-170http://book.cakephp.org/view/4/Beginning-With-CakePHPhttp://book.cakephp.org/history/170/Core-Componentshttp://book.cakephp.org/view/13/Basic-Principles-of-CakePHPhttp://book.cakephp.org/view/13/Basic-Principles-of-CakePHPhttp://book.cakephp.org/view/27/Developing-with-CakePHPhttp://book.cakephp.org/view/124/Common-Tasks-With-CakePHPhttp://book.cakephp.org/complete/170/Core-Components#Core-Components-170http://book.cakephp.org/complete/170/Core-Components#Authentication-172http://book.cakephp.org/complete/170/Core-Components#Cookies-177http://book.cakephp.org/add/170/Core-Componentshttp://book.cakephp.org/complete/170/Core-Componentshttp://book.cakephp.org/complete/170/Core-Componentshttp://cakefoundation.org/pages/donationshttp://cakephp.org/http://book.cakephp.org/todohttp://book.cakephp.org/statshttp://book.cakephp.org/users/loginhttp://book.cakephp.org/changes/170.rsshttp://book.cakephp.org/changes/170.rsshttp://book.cakephp.org/comments/index/170/Core-Components.rsshttp://book.cakephp.org/comments/index/170/Core-Components.rsshttp://book.cakephp.org/add/170/Core-Componentshttp://book.cakephp.org/add/170/Core-Componentshttp://book.cakephp.org/complete/170/Core-Componentshttp://book.cakephp.org/view/221/Appendiceshttp://book.cakephp.org/view/218/Example-Applicationshttp://book.cakephp.org/view/620/Core-Console-Applicationshttp://book.cakephp.org/view/620/Core-Console-Applicationshttp://book.cakephp.org/view/486/Core-Utility-Librarieshttp://book.cakephp.org/view/181/Core-Helpershttp://book.cakephp.org/view/495/Core-Behaviorshttp://book.cakephp.org/complete/170/Core-Components#Sessions-173http://book.cakephp.org/complete/170/Core-Components#Security-Component-175http://book.cakephp.org/complete/170/Core-Components#Security-Component-175http://book.cakephp.org/complete/170/Core-Components#Request-Handling-174http://book.cakephp.org/complete/170/Core-Components#Email-176http://book.cakephp.org/complete/170/Core-Components#Cookies-177http://book.cakephp.org/complete/170/Core-Components#Authentication-172http://book.cakephp.org/complete/170/Core-Components#Access-Control-Lists-171http://book.cakephp.org/complete/170/Core-Components#Access-Control-Lists-171http://book.cakephp.org/complete/170/Core-Components#Core-Components-170http://book.cakephp.org/view/124/Common-Tasks-With-CakePHPhttp://book.cakephp.org/view/124/Common-Tasks-With-CakePHPhttp://book.cakephp.org/view/27/Developing-with-CakePHPhttp://book.cakephp.org/view/27/Developing-with-CakePHPhttp://book.cakephp.org/view/13/Basic-Principles-of-CakePHPhttp://book.cakephp.org/view/13/Basic-Principles-of-CakePHPhttp://book.cakephp.org/view/4/Beginning-With-CakePHPhttp://book.cakephp.org/view/4/Beginning-With-CakePHPhttp://book.cakephp.org/http://book.cakephp.org/toc/170/Core-Components#The-Manual-3http://book.cakephp.org/history/465/Understanding-How-ACL-Workshttp://book.cakephp.org/complete/170/Core-Components#comments-465http://book.cakephp.org/view/465/Understanding-How-ACL-Workshttp://book.cakephp.org/edit/465/Understanding-How-ACL-Workshttp://book.cakephp.org/complete/170/Core-Components#Understanding-How-ACL-Works-465http://book.cakephp.org/comments/index/171http://book.cakephp.org/history/171/Access-Control-Listshttp://book.cakephp.org/complete/170/Core-Components#comments-171http://book.cakephp.org/view/171/Access-Control-Listshttp://book.cakephp.org/edit/171/Access-Control-Listshttp://book.cakephp.org/complete/170/Core-Components#Access-Control-Lists-171http://book.cakephp.org/comments/index/170http://book.cakephp.org/view/62/componentshttp://book.cakephp.org/history/170/Core-Componentshttp://book.cakephp.org/complete/170/Core-Components#comments-170http://book.cakephp.org/edit/170/Core-Componentshttp://book.cakephp.org/complete/170/Core-Componentshttp://book.cakephp.org/complete/3/The-Manualhttps://trac.cakephp.org/http://cakeforge.org/http://live.cakephp.org/http://bakery.cakephp.org/http://book.cakephp.org/http://api.cakephp.org/http://cakephp.org/http://book.cakephp.org/http://book.cakephp.org/view/500/Generalhttp://book.cakephp.org/view/304/x1-1-Collectionhttp://book.cakephp.org/view/2/x1-2-Collection
  • 8/14/2019 Core Components

    2/40

    owerful things require access control. Access control lists are a way to manage

    pplication permissions in a fine-grained, yet easily maintainable and

    manageable way.

    ccess control lists, or ACL, handle two main things: things that want stuff, and

    hings that are wanted. In ACL lingo, things (most often users) that want to

    se stuff are called access request objects, or AROs. Things in the system that

    re wanted (most often actions or data) are called access control objects, or

    COs. The entities are called 'objects' because sometimes the requesting object

    n't a person - sometimes you might want to limit the access certain Cake

    ontrollers have to initiate logic in other parts of your application. ACOs could benything you want to control, from a controller action, to a web service, to a line

    n your grandma's online diary.

    o review:

    ACO - Access Control Object - Something that is wanted

    ARO - Access Request Object - Something that wants something

    ssentiallly, ACL is what is used to decide when an ARO can have access to an

    CO.

    n order to help you understand how everything works together, let's use a

    emi-practical example. Imagine, for a moment, a computer system used by aamiliar group of fantasy novel adventurers from the Lord of the Rings. The

    eader of the group, Gandalf, wants to manage the party's assets while

    maintaining a healthy amount of privacy and security for the other members of

    he party. The first thing he needs to do is create a list of the AROs involved:

    Gandalf

    Aragorn

    Bilbo

    Frodo

    Gollum

    Legolas

    Gimli

    Pippin

    Merry

    Realize that ACL is not the same as authentication. ACL is what happens

    after a user has been authenticated. Although the two are usually used

    in concert, it's important to realize the difference between knowing who

    someone is (authentication) and knowing what they can do (ACL).

    he next thing Gandalf needs to do is make an initial list of things, or ACOs, theystem will handle. His list might look something like:

    Weapons

    The One Ring

    Salted Pork

    Diplomacy

    Ale

    raditionally, systems were managed using a sort of matrix, that showed a

    asic set of users and permissions relating to objects. If this information were

    tored in a table, it might look like the following table:

    Weapons The Ring Salted Pork Diplomacy Ale

  • 8/14/2019 Core Components

    3/40

    t first glance, it seems that this sort of system could work rather well.

    ssignments can be made to protect security (only Frodo can access the ring)

    nd protect against accidents (keeping the hobbits out of the salted pork and

    eapons). It seems fine grained enough, and easy enough to read, right?

    or a small system like this, maybe a matrix setup would work. But for a

    rowing system, or a system with a large amount of resources (ACOs) and

    sers (AROs), a table can become unwieldy rather quickly. Imagine trying to

    ontrol access to the hundreds of war encampments and trying to manage

    hem by unit. Another drawback to matrices is that you can't really logically

    roup sections of users or make cascading permissions changes to groups of

    sers based on those logical groupings. For example, it would sure be nice to

    utomatically allow the hobbits access to the ale and pork once the battle is

    ver: Doing it on an individual user basis would be tedious and error prone.

    aking a cascading permissions change to all 'hobbits' would be easy.

    CL is most usually implemented in a tree structure. There is usually a tree of

    ROs and a tree of ACOs. By organizing your objects in trees, permissions can

    till be dealt out in a granular fashion, while still maintaining a good grip on the

    ig picture. Being the wise leader he is, Gandalf elects to use ACL in his new

    ystem, and organizes his objects along the following lines:

    Fellowship of the RingWarriors

    Aragorn

    Legolas

    Gimli

    WizardsGandalf

    HobbitsFrodo

    Bilbo

    Merry

    Pippin

    VisitorsGollum

    sing a tree structure for AROs allows Gandalf to define permissions that apply

    o entire groups of users at once. So, using our ARO tree, Gandalf can tack on a

    ew group-based permissions:

    Fellowship of the Ring(Deny: all)

    Warriors(Allow : Weapons, Ale, Elven Rations, Salted Pork)

    AragornLegolas

    Gandalf Allow Allow Allow

    Aragorn Allow Allow Allow Allow

    Bilbo Allow

    Frodo Allow Allow

    Gollum Allow

    Legolas Allow Allow Allow Allow

    Gimli Allow Allow

    Pippin Allow Allow

    Merry Allow

  • 8/14/2019 Core Components

    4/40

    Gimli

    Wizards(Allow : Salted Pork, Diplomacy, Ale)

    Gandalf

    Hobbits(Allow : Ale)

    Frodo

    Bilbo

    Merry

    Pippin

    Visitors

    (Allow : Salted Pork)Gollum

    f we wanted to use ACL to see if the Pippin was allowed to access the ale,

    e'd first get his path in the tree, which is Fellowship->Hobbits->Pippin. Then

    e see the different permissions that reside at each of those points, and use

    he most specific permission relating to Pippin and the Ale.

    Since the 'Pippin' node in the ACL tree doesn't specifically deny access to

    the ale ACO, the final result is that we allow access to that ACO.

    he tree also allows us to make finer adjustments for more granular control -

    hile still keeping the ability to make sweeping changes to groups of AROs:

    Fellowship of the Ring(Deny: all)

    Warriors

    (Allow : Weapons, Ale, Elven Rations, Salted Pork)Aragorn(Allow: Diplomacy)

    Legolas

    Gimli

    Wizards(Allow : Salted Pork, Diplomacy, Ale)

    Gandalf

    Hobbits(Allow : Ale)

    Frodo(Allow: Ring)

    BilboMerry(Deny: Ale)

    Pippin(Allow: Diplomacy)

    Visitors(Allow : Salted Pork)

    Gollum

    his approach allows us both the ability to make wide-reaching permissions

    hanges, but also fine-grained adjustments. This allows us to say that all

    obbits can have access to ale, with one exceptionMerry. To see if Merry can

    ccess the Ale, we'd find his path in the tree: Fellowship->Hobbits->Merry andork our way down, keeping track of ale-related permissions:

    ARO Node Perm iss ion I nfo Resu lt

    Fellowship of the Ring Deny all Denying access to ale.

    Hobbits Allow 'ale' Allowing access to ale!

    Pippin -- Still allowing ale!

  • 8/14/2019 Core Components

    5/40

    ee comments for this section

    5.1.2 Defining Permissions: Cake's INI-

    based ACLdit View just this section Comments (0) History

    ake's first ACL implementation was based on INI files stored in the Cake

    nstallation. While it's useful and stable, we recommend that you use the

    atabase backed ACL solution, mostly because of its ability to create new ACOs

    nd AROs on the fly. We meant it for usage in simple applications - and

    specially for those folks who might not be using a database for some reason.

    y default, CakePHP's ACL is database-driven. To enable INI-based ACL, you'll

    eed to tell CakePHP what system you're using by updating the following lines

    n app/config/core.php

    RO/ACO permissions are specified in/ app/ config / acl.ini.php . The basic idea

    that AROs are specified in an INI section that has three properties: groups,

    low, and deny.

    groups: names of ARO groups this ARO is a member of.

    allow: names of ACOs this ARO has access to

    deny: names of ACOs this ARO should be denied access to

    COs are specified in INI sections that only include the allow and deny

    roperties.

    s an example, let's see how the Fellowship ARO structure we've been crafting

    ould look like in INI syntax:

    ARO Node Perm iss ion I nfo Resu lt

    Fellowship of the Ring Deny all Denying access to ale.

    Hobbits Allow 'ale' Allowing access to ale!

    Merry Deny 'ale' Denying ale.

    //Change these lines:

    Configure::write('Acl.classname', 'DbAcl');

    Configure::write('Acl.database', 'default');

    //To look like this:

    Configure::write('Acl.classname', 'IniAcl');

    //Configure::write('Acl.database', 'default');

    ;-------------------------------------

    ; AROs

    ;-------------------------------------[aragorn]

    groups = warriors

    allow = diplomacy

    [legolas]

    groups = warriors

    [gimli]

    groups = warriors

    [gandalf]

    groups = wizards

    [frodo]

    rou s = hobbits

    http://book.cakephp.org/complete/170/Core-Components#Defining-Permissions-Cake-s-INI-based-ACL-466http://book.cakephp.org/edit/466/Defining-Permissions-Cake-s-INI-based-ACLhttp://book.cakephp.org/view/466/Defining-Permissions-Cake-s-INI-based-ACLhttp://book.cakephp.org/complete/170/Core-Components#comments-466http://book.cakephp.org/complete/170/Core-Components#comments-466http://book.cakephp.org/history/466/Defining-Permissions-Cake-s-INI-based-ACLhttp://book.cakephp.org/complete/170/Core-Components#comments-466http://book.cakephp.org/view/466/Defining-Permissions-Cake-s-INI-based-ACLhttp://book.cakephp.org/edit/466/Defining-Permissions-Cake-s-INI-based-ACLhttp://book.cakephp.org/complete/170/Core-Components#Defining-Permissions-Cake-s-INI-based-ACL-466http://book.cakephp.org/comments/index/465
  • 8/14/2019 Core Components

    6/40

    ow that you've got your permissions defined, you can skip along to the section

    n checking permissions using the ACL component.

    ee comments for this section

    5.1.3 Defining Permissions: Cake's

    Database ACLdit View just this section Comments (0) History

    ow that we've covered INI-based ACL permissions, let's move on to the (moreommonly used) database ACL.

    ee comments for this section

    5.1.3.1 Getting Started

    dit View just this section Comments (3) History

    he default ACL permissions implementation is database powered. Cake'satabase ACL consists of a set of core models, and a console application that

    omes with your Cake installation. The models are used by Cake to interact

    ith your database in order to store and retrieve nodes in tree format. The

    onsole application is used to initialize your database and interact with your

    CO and ARO trees.

    o get started, first you'll need to make sure your /app/config/database.php is

    resent and correctly configured. See section 4.1 for more information on

    atabase configuration.

    nce you've done that, use the CakePHP console to create your ACL database

    ables:

    allow = ring

    [bilbo]

    groups = hobbits

    [merry]

    groups = hobbits

    deny = ale

    [pippin]

    groups = hobbits

    [gollum]groups = visitors

    ;-------------------------------------

    ; ARO Groups

    ;-------------------------------------

    [warriors]

    allow = weapons, ale, salted_pork

    [wizards]

    allow = salted_pork, diplomacy, ale

    [hobbits]

    allow = ale

    [visitors]

    allow = salted_pork

    http://book.cakephp.org/view/471/checking-permissions-the-acl-chttp://book.cakephp.org/comments/index/466http://book.cakephp.org/complete/170/Core-Components#Getting-Started-468http://book.cakephp.org/history/468/Getting-Startedhttp://book.cakephp.org/complete/170/Core-Components#comments-468http://book.cakephp.org/view/468/Getting-Startedhttp://book.cakephp.org/edit/468/Getting-Startedhttp://book.cakephp.org/complete/170/Core-Components#Getting-Started-468http://book.cakephp.org/comments/index/467http://book.cakephp.org/history/467/Defining-Permissions-Cake-s-Database-ACLhttp://book.cakephp.org/complete/170/Core-Components#comments-467http://book.cakephp.org/view/467/Defining-Permissions-Cake-s-Database-ACLhttp://book.cakephp.org/edit/467/Defining-Permissions-Cake-s-Database-ACLhttp://book.cakephp.org/complete/170/Core-Components#Defining-Permissions-Cake-s-Database-ACL-467http://book.cakephp.org/comments/index/466http://book.cakephp.org/view/471/checking-permissions-the-acl-chttp://book.cakephp.org/view/471/checking-permissions-the-acl-c
  • 8/14/2019 Core Components

    7/40

    unning this command will drop and re-create the tables necessary to store

    CO and ARO information in tree format. The output of the console application

    hould look something like the following:

    This replaces an older deprecated command, "initdb".

    ou can also use the SQL file found in app/config/sql/db_acl.sql, but that's

    owhere near as fun.

    When finished, you should have three new database tables in your system:

    cos, aros, and aros_acos (the join table to create permissions information

    etween the two trees).

    If you're curious about how Cake stores tree information in these

    tables, read up on modified database tree traversal. The ACL

    component uses CakePHP's Tree Behavior to manage the trees'inheritances. The model class files for ACL are all compiled in a single file

    db_acl.php.

    ow that we're all set up, let's work on creating some ARO and ACO trees.

    ee comments for this section

    5.1.3.2 Creating Access Request Objects (AROs) andAccess Control Objects (ACOs)

    dit View just this section Comments (1) History

    $ cake schema run create DbAcl

    ---------------------------------------------------------------

    Cake Schema Shell

    ---------------------------------------------------------------

    The following tables will be dropped.

    acos

    aros

    aros_acos

    Are you sure you want to drop the tables? (y/n)

    [n] > y

    Dropping tables.

    acos updated.

    aros updated.

    aros_acos updated.

    The following tables will be created.

    acos

    aros

    aros_acos

    Are you sure you want to create the tables? (y/n)

    [y] > y

    Creating tables.

    acos updated.

    aros updated.

    aros_acos updated.

    End create.

    http://book.cakephp.org/comments/index/468http://book.cakephp.org/comments/index/468http://book.cakephp.org/history/469/Creating-Access-Request-Objects-AROs-and-Access-Cohttp://book.cakephp.org/complete/170/Core-Components#comments-469http://book.cakephp.org/view/469/Creating-Access-Request-Objects-AROs-and-Access-Cohttp://book.cakephp.org/edit/469/Creating-Access-Request-Objects-AROs-and-Access-Cohttp://book.cakephp.org/complete/170/Core-Components#Creating-Access-Request-Objects-AROs-and-Access-Co-469http://book.cakephp.org/comments/index/468http://api.cakephp.org/1.2/cake_2libs_2model_2db__acl_8php-source.htmlhttp://book.cakephp.org/view/91/tree-behavior
  • 8/14/2019 Core Components

    8/40

    n creating new ACL objects (ACOs and AROs), realize that there are two main

    ays to name and access nodes. The first method is to link an ACL object

    rectly to a record in your database by specifying a model name and foreign

    ey value. The second method can be used when an object has no direct

    elation to a record in your database - you can provide a textual alias for the

    bject.

    In general, when you're creating a group or higher level object, use an

    alias. If you're managing access to a specific item or record in the

    database, use the model/foreign key method.

    ou create new ACL objects using the core CakePHP ACL models. In doing so,

    here are a number of fields you'll want to use when saving data: model,

    oreign_key, alias, and parent_id.

    he model and foreign_key fields for an ACL object allows you to link up the

    bject to its corresponding model record (if there is one). For example, many

    ROs will have corresponding User records in the database. Setting an ARO's

    oreign_key to the User's ID will allow you to link up ARO and User information

    ith a single User model find() call if you've set up the correct model

    ssociations. Conversely, if you want to manage edit operation on a specific

    og post or recipe listing, you may choose to link an ACO to that specific modelecord.

    he alias for an ACL object is just a human-readable label you can use to

    entify an ACL object that has no direct model record correlation. Aliases are

    sually useful in naming user groups or ACO collections.

    he parent_id for an ACL object allows you to fill out the tree structure. Supply

    he ID of the parent node in the tree to create a new child.

    efore we can create new ACL objects, we'll need to load up their respective

    asses. The easiest way to do this is to include Cake's ACL Component in your

    ontroller's $components array:

    nce we've got that done, let's see what some examples of creating these

    bjects might look like. The following code could be placed in a controller action

    omewhere:

    While the examples here focus on ARO creation, the same techniques

    can be used to create an ACO tree.

    eeping with our Fellowship setup, let's first create our ARO groups. Because

    ur groups won't really have specific records tied to them, we'll use aliases to

    reate these ACL objects. What we're doing here is from the perspective of a

    ontroller action, but could be done elsewhere. What we'll cover here is a bit of

    n artificial approach, but you should feel comfortable using these techniques to

    uild AROs and ACOs on the fly.

    his shouldn't be anything drastically new - we're just using models to save

    ata like we always do:

    var $components = array('Acl');

    function anyAction()

    {

    $aro = new Aro();

    //Here's all of our group info in an array we can iterat

  • 8/14/2019 Core Components

    9/40

    nce we've got them in there, we can use the ACL console application to verify

    he tree structure.

    suppose it's not much of a tree at this point, but at least we've got some

    erification that we've got four top-level nodes. Let's add some children to

    hose ARO nodes by adding our specific user AROs under these groups. Every

    ood citizen of Middle Earth has an account in our new system, so we'll tie

    hese ARO records to specific model records in our database.

    When adding child nodes to a tree, make sure to use the ACL node ID,

    rather than a foreign_key value.

    $groups = array(

    0 => array(

    'alias' => 'warriors'

    ),

    1 => array(

    'alias' => 'wizards'

    ),

    2 => array(

    'alias' => 'hobbits'

    ),

    3 => array(

    'alias' => 'visitors'

    ),

    );

    //Iterate and create ARO groups

    foreach($groups as $data)

    {

    //Remember to call create() when saving in loops...

    $aro->create();

    //Save data

    $aro->save($data);

    }

    //Other action logic goes here...

    $ cake acl view aro

    Aro tree:

    ---------------------------------------------------------------

    [1]warriors

    [2]wizards

    [3]hobbits

    [4]visitors

    ---------------------------------------------------------------

    function anyAction()

    {

    $aro = new Aro();

    //Here are our user records, ready to be linked up to ne

    //This data could come from a model and modified, but we

    //arrays here for demonstration purposes.

    $users = array(

    0 => array(

  • 8/14/2019 Core Components

    10/40

    'alias' => 'Aragorn',

    'parent_id' => 1,

    'model' => 'User',

    'foreign_key' => 2356,

    ),

    1 => array(

    'alias' => 'Legolas',

    'parent_id' => 1,

    'model' => 'User',

    'foreign_key' => 6342,

    ),

    2 => array(

    'alias' => 'Gimli',

    'parent_id' => 1,

    'model' => 'User',

    'foreign_key' => 1564,

    ),

    3 => array(

    'alias' => 'Gandalf',

    'parent_id' => 2,

    'model' => 'User',

    'foreign_key' => 7419,

    ),

    4 => array(

    'alias' => 'Frodo', 'parent_id' => 3,

    'model' => 'User',

    'foreign_key' => 7451,

    ),

    5 => array(

    'alias' => 'Bilbo',

    'parent_id' => 3,

    'model' => 'User',

    'foreign_key' => 5126,

    ),

    6 => array(

    'alias' => 'Merry',

    'parent_id' => 3,

    'model' => 'User',

    'foreign_key' => 5144,

    ),

    7 => array(

    'alias' => 'Pippin',

    'parent_id' => 3,

    'model' => 'User',

    'foreign_key' => 1211,

    ),

    8 => array(

    'alias' => 'Gollum',

    'parent_id' => 4,

    'model' => 'User',

    'foreign_key' => 1337,

    ),

    );

    //Iterate and create AROs (as children)

    foreach($users as $data)

    {

    //Remember to call create() when saving in loops...

    $aro->create();

    //Save data

    $aro->save($data); }

  • 8/14/2019 Core Components

    11/40

    Typically you won't supply both an alias and a model/foreign_key, but

    we're using both here to make the structure of the tree easier to read

    for demonstration purposes.

    he output of that console application command should now be a little more

    nteresting. Let's give it a try:

    ow that we've got our ARO tree setup properly, let's discuss a possible

    pproach for structuring an ACO tree. While we can structure more of an

    bstract representation of our ACO's, it's often more practical to model an ACO

    ree after Cake's Controller/Action setup. We've got five main objects we're

    andling in this Fellowship scenario, and the natural setup for that in a Cake

    pplication is a group of models, and ultimately the controllers that manipulatehem. Past the controllers themselves, we'll want to control access to specific

    ctions in those controllers.

    ased on that idea, let's set up an ACO tree that will mimic a Cake app setup.

    ince we have five ACOs, we'll create an ACO tree that should end up looking

    omething like the following:

    Weapons

    Rings

    PorkChops

    DiplomaticEfforts

    Ales

    ne nice thing about a Cake ACL setup is that each ACO automatically contains

    //Other action logic goes here...

    $ cake acl view aro

    Aro tree:

    ---------------------------------------------------------------

    [1]warriors

    [5]Aragorn

    [6]Legolas

    [7]Gimli

    [2]wizards

    [8]Gandalf

    [3]hobbits

    [9]Frodo

    [10]Bilbo

    [11]Merry

    [12]Pippin

    [4]visitors

    [13]Gollum

    ---------------------------------------------------------------

  • 8/14/2019 Core Components

    12/40

    our properties related to CRUD (create, read, update, and delete) actions. You

    an create children nodes under each of these five main ACOs, but using Cake's

    uilt in action management covers basic CRUD operations on a given object.

    eeping this in mind will make your ACO trees smaller and easier to maintain.

    We'll see how these are used later on when we discuss how to assign

    ermissions.

    ince you're now a pro at adding AROs, use those same techniques to create

    his ACO tree. Create these upper level groups using the core Aco model.

    ee comments for this section

    5.1.3.3 Assigning Permissions

    dit View just this section Comments (1) History

    fter creating our ACOs and AROs, we can finally assign permissions between

    he two groups. This is done using Cake's core Acl component. Let's continue on

    ith our example.

    ere we'll work in the context of a controller action. We do that because

    ermissions are managed by the Acl Component.

    et's set up some basic permissions using the AclComponent in an action inside

    his controller.

    he first call we make to the AclComponent allows any user under the 'warriors'

    RO group full access to anything under the 'Weapons' ACO group. Here we're

    ust addressing ACOs and AROs by their aliases.

    otice the usage of the third parameter? That's where we use those handy

    ctions that are in-built for all Cake ACOs. The default options for that

    arameter are create, read, update, and delete but you can add a colum in the

    ros_acos database table (prefixed with _ - for example_admin) and use it

    ongside the defaults.

    he second set of calls is an attempt to make a more fine-grained permission

    ecision. We want Aragorn to keep his full-access privileges, but deny other

    arriors in the group the ability to delete Weapons records. We're using the

    ias syntax to address the AROs above, but you might want to use themodel/foriegn key syntax yourself. What we have above is equivalent to this:

    class SomethingsController extends AppController

    {

    // You might want to place this in the AppController

    // instead, but here works great too.

    var $components = array('Acl');

    }

    function index()

    {

    //Allow warriors complete access to weapons

    //Both these examples use the alias syntax

    $this->Acl->allow('warriors', 'Weapons');

    //Though the King may not want to let everyone

    //have unfettered access

    $this->Acl->deny('warriors/Legolas', 'Weapons', 'delete'

    $this->Acl->deny('warriors/Gimli', 'Weapons', 'delete'

    die(print_r('done', 1));

    http://book.cakephp.org/comments/index/469http://book.cakephp.org/comments/index/469http://book.cakephp.org/complete/170/Core-Components#Assigning-Permissions-470http://book.cakephp.org/complete/170/Core-Components#Assigning-Permissions-470http://book.cakephp.org/view/470/Assigning-Permissionshttp://book.cakephp.org/complete/170/Core-Components#comments-470http://book.cakephp.org/history/470/Assigning-Permissionshttp://book.cakephp.org/history/470/Assigning-Permissionshttp://book.cakephp.org/complete/170/Core-Components#comments-470http://book.cakephp.org/view/470/Assigning-Permissionshttp://book.cakephp.org/edit/470/Assigning-Permissionshttp://book.cakephp.org/complete/170/Core-Components#Assigning-Permissions-470http://book.cakephp.org/comments/index/469
  • 8/14/2019 Core Components

    13/40

    Addressing a node using the alias syntax uses a slash-delimited string

    ('/users/employees/developers'). Addressing a node using model/foreign

    key syntax uses an array with two parameters: array('model' =>

    'User', 'foreign_key' => 8282).

    he next section will help us validate our setup by using the AclComponent toheck the permissions we've just set up.

    ee comments for this section

    5.1.3.4 Checking Permissions: The ACL Component

    dit View just this section Comments (3) History

    et's use the AclComponent to make sure dwarves and elves can't remove

    hings from the armory. At this point, we should be able to use the

    clComponent to make a check between the ACOs and AROs we've created.

    he basic syntax for making a permissions check is:

    et's give it a try inside a controller action:

    he usage here is demonstrational, but hopefully you can see how checking like

    his can be used to decide whether or not to allow something to happen, show

    n error message, or redirect the user to a login.

    ee comments for this section

    5.2 Authenticationdit View just this section Comments (13) History

    ser authentication systems are a common part of many web applications. In

    // 6342 = Legolas

    // 1564 = Gimli

    $this->Acl->deny(array('model' => 'User', 'foreign_key' => 6

    $this->Acl->check( $aro, $aco, $action = '*');

    function index()

    {

    //These all return true:

    $this->Acl->check('warriors/Aragorn', 'Weapons');

    $this->Acl->check('warriors/Aragorn', 'Weapons', 'create

    $this->Acl->check('warriors/Aragorn', 'Weapons', 'read')

    $this->Acl->check('warriors/Aragorn', 'Weapons', 'update

    $this->Acl->check('warriors/Aragorn', 'Weapons', 'delete

    //Remember, we can use the model/foreign key syntax

    //for our user AROs

    $this->Acl->check(array('model' => 'User', 'foreign_key'

    //These also return true:

    $result = $this->Acl->check('warriors/Legolas', 'Weapons

    $result = $this->Acl->check('warriors/Gimli', 'Weapons',

    //But these return false:

    $result = $this->Acl->check('warriors/Legolas', 'Weapons

    $result = $this->Acl->check('warriors/Gimli', 'Weapons',

    http://book.cakephp.org/complete/170/Core-Components#Checking-Permissions-The-ACL-Component-471http://book.cakephp.org/comments/index/471http://book.cakephp.org/comments/index/471http://book.cakephp.org/complete/170/Core-Components#Authentication-172http://book.cakephp.org/edit/172/Authenticationhttp://book.cakephp.org/view/172/Authenticationhttp://book.cakephp.org/complete/170/Core-Components#comments-172http://book.cakephp.org/history/172/Authenticationhttp://book.cakephp.org/edit/471/Checking-Permissions-The-ACL-Componenthttp://book.cakephp.org/view/471/Checking-Permissions-The-ACL-Componenthttp://book.cakephp.org/view/471/Checking-Permissions-The-ACL-Componenthttp://book.cakephp.org/complete/170/Core-Components#comments-471http://book.cakephp.org/complete/170/Core-Components#comments-471http://book.cakephp.org/complete/170/Core-Components#comments-471http://book.cakephp.org/history/172/Authenticationhttp://book.cakephp.org/complete/170/Core-Components#comments-172http://book.cakephp.org/view/172/Authenticationhttp://book.cakephp.org/edit/172/Authenticationhttp://book.cakephp.org/complete/170/Core-Components#Authentication-172http://book.cakephp.org/comments/index/471http://book.cakephp.org/history/471/Checking-Permissions-The-ACL-Componenthttp://book.cakephp.org/complete/170/Core-Components#comments-471http://book.cakephp.org/view/471/Checking-Permissions-The-ACL-Componenthttp://book.cakephp.org/edit/471/Checking-Permissions-The-ACL-Componenthttp://book.cakephp.org/complete/170/Core-Components#Checking-Permissions-The-ACL-Component-471http://book.cakephp.org/comments/index/470
  • 8/14/2019 Core Components

    14/40

    akePHP there are several systems for authenticating users, each of which

    rovides different options. At its core the authentication component will check

    o see if a user has an account with a site. If they do, the component will give

    ccess to that user to the complete site.

    his component can be combined with the ACL (access control lists) component

    o create more complex levels of access within a site. The ACL Component, for

    xample, could allow you to grant one user access to public site areas, while

    ranting another user access to protected administrative portions of the site.

    akePHP's AuthComponent can be used to create such a system easily and

    uickly. Let's take a look at how you would build a very simple authenticationystem.

    ke all components, you use it by adding 'Auth' to the list of components in

    our controller:

    r add it to your AppController so all of your controllers will use it:

    ow, there are a few conventions to think about when using AuthComponent.

    y default, the AuthComponent expects you to have a table called 'users' with

    elds called 'username' and 'password' to be used. In some situations,

    atabases don't let you use 'password' as a column name, later, you will see how to

    hange the default field names to work with your own environment.

    et's set up our users table using the following SQL:

    omething to keep in mind when creating a table to store all your user

    uthentication data is that the AuthComponent expects the password value

    tored in the database to be hashed instead of being stored in plaintext. Make

    ure that the field you will be using to store passwords is long enough to store

    he hash (40 characters for SHA1, for example).

    or the most basic setup, you'll only need to create two actions in your

    ontroller:

    While you can leave the login() function blank, you do need to create the login

    class FooController extends AppController {

    var $components = array('Auth');

    class AppController extends Controller {

    var $components = array('Auth');

    CREATE TABLE users (

    id integer auto_increment,

    username char(50),

    password char(50),

    PRIMARY KEY (id)

    );

    class UsersController extends AppController {

    var $name = 'Users';

    var $components = array('Auth'); // Not necessary if dec

    /**

    * The AuthComponent provides the needed functionality

    * for login, so you can leave this function blank.

    */

    function login() {

    }

    function logout() {

    $this->redirect($this->Auth->logout());

    }

  • 8/14/2019 Core Components

    15/40

    ew template (saved in app/views/users/login.ctp). This is the only

    sersController view template you need to create, however. The example

    elow assumes you are already using the Form helper:

    his view creates a simple login form where you enter a username andassword. Once you submit this form, the AuthComponent takes care of the

    est for you. The session flash message will display any notices generated by

    he AuthComponent.

    elieve it or not, we're done! That's how to implement an incredibly simple,

    atabase-driven authentication system using the Auth component. However,

    here is a lot more we can do. Let's take a look at some more advanced usage

    f the component.

    ee comments for this section

    5.2.1 Setting Auth Component Variablesdit View just this section Comments (2) History

    Whenever you want to alter a default option for AuthComponent, you do that

    y creating a beforeFilter() method for your controller, and then calling various

    uilt-in methods or setting component variables.

    or example, to change the field name used for passwords from 'password' to

    ecretword', you would do the following:

    n this particular situation, you would also need to remember to change the

    eld name in the view template!

    ee comments for this section

    5.2.2 Displaying Auth Error Messagesdit View just this section Comments (0) History

    n order to display the error messages that Auth spits out you need to add the

    ollowing code to your view. In this case, the message will appear below the

    egular flash messages:

  • 8/14/2019 Core Components

    16/40

    ee comments for this section

    5.2.3 Troubleshooting Auth Problemsdit View just this section Comments (2) History

    can sometimes be quite difficult to diagnose problems when it's not behavings expected, so here are a few pointers to remember.

    assword hashing

    When posting information to an action via a form, the Auth component

    utomatically hashes the contents of your password input field if you also have

    ata in the username field. So, if you are trying to create some sort of

    egistration page, make sure to have the user fill out a 'confirm password' field

    o that you can compare the two. Here's some sample code:

    ee comments for this section

    5.2.4 Changing Encryption Typedit View just this section Comments (3) History

    he AuthComponent uses the Security class to encrypt a password. The

    ecurity class uses SHA1 scheme by default. To change the encryption method

    sed by the Auth component, use the setHash method passing it md5, sha1 or

    ha256 as its first and only parameter.

    The Security class uses a salt value (set in /app/config/core.php) to

    encrypt the password. If you have an existing database that previouslyused an encryption scheme without a salt, set authorize if not already

    set, and create the method hashPasswords in the class you nominate.

    ee comments for this section

    5.2.5 AuthComponent Methods

    dit View just this section Comments (3) History

    ee comments for this section

    if ($session->check('Message.auth')) {

    $session->flash('auth');

    }

    ?>

  • 8/14/2019 Core Components

    17/40

    5.2.5.1 action

    dit View just this section Comments (2) History

    action (string $action = ':controller/:action')

    f you are using ACO's as part of your ACL structure, you can get the path to

    he ACO node bound to a particular controller/action pair:

    you don't pass in any values, it uses the current controller / action pair

    ee comments for this section

    5.2.5.2 allow

    dit View just this section Comments (2) History

    f you have some actions in your controller that you don't have to authenticate

    gainst (such as a user registration action), you can add methods that the

    uthComponent should ignore. The following example shows how to allow an

    ction named 'register'.

    Do not specifically allow 'login' because that will break Auth.

    you wish to allow multiple actions to skip authentication, you supply them as

    arameters to the allow() method:

    hortcut: you may also allow all the actions in a controller by using '*'.

    If you are using requestAction in your layout or elements you should

    allow those actions in order to be able to open login page properly.

    The auth component assumes that your actions names follow

    conventions and are underscored.

    ee comments for this section

    5.2.5.3 deny

    dit View just this section Comments (0) History

    here may be times where you will want to remove actions from the list of

    lowed actions (set using $this->Auth->allow()). Here's an example:

    $acoNode = $this->Auth->action('user/delete');

    $this->Auth->allow('register');

    $this->Auth->allow('foo', 'bar', 'baz');

    $this->Auth->allow('*');

    function beforeFilter() {

    $this->Auth->authorize = 'controller';

    $this->Auth->allow('delete');

    }

    function isAuthorized() {

    if ($this->Auth->user('role') != 'admin') {

    $this->Auth->deny('delete');

    http://book.cakephp.org/complete/170/Core-Components#action-381http://book.cakephp.org/comments/index/381http://book.cakephp.org/view/559/URL-Considerations-for-Controller-Nameshttp://book.cakephp.org/view/559/URL-Considerations-for-Controller-Nameshttp://book.cakephp.org/comments/index/382http://book.cakephp.org/complete/170/Core-Components#deny-383http://book.cakephp.org/history/383/denyhttp://book.cakephp.org/complete/170/Core-Components#comments-383http://book.cakephp.org/view/383/denyhttp://book.cakephp.org/edit/383/denyhttp://book.cakephp.org/complete/170/Core-Components#deny-383http://book.cakephp.org/comments/index/382http://book.cakephp.org/view/559/URL-Considerations-for-Controller-Nameshttp://book.cakephp.org/view/559/URL-Considerations-for-Controller-Nameshttp://book.cakephp.org/history/382/allowhttp://book.cakephp.org/complete/170/Core-Components#comments-382http://book.cakephp.org/view/382/allowhttp://book.cakephp.org/edit/382/allowhttp://book.cakephp.org/complete/170/Core-Components#allow-382http://book.cakephp.org/comments/index/381http://book.cakephp.org/history/381/actionhttp://book.cakephp.org/complete/170/Core-Components#comments-381http://book.cakephp.org/view/381/actionhttp://book.cakephp.org/edit/381/actionhttp://book.cakephp.org/complete/170/Core-Components#action-381
  • 8/14/2019 Core Components

    18/40

    ee comments for this section

    5.2.5.4 hashPasswords

    dit View just this section Comments (0) History

    hashPasswords ($data)

    his method checks if the $data contains the username and password fields as

    pecified by the variable $fields indexed by the model name as specified by

    userModel. If the $data array contains both the usename and password, it

    ashes the password field in the array and returns the data array in the same

    ormat, otherwise it returns it unchanged. It might sound confusing but that's

    ow it works.

    he $hashedPasswords['User']['password'] field would now be hashed using theassword function of the component.

    f your controller uses the Auth component and posted data contains the fields

    s explained above, it will automatically hash the password field using this

    unction.

    ee comments for this section

    5.2.5.5 login

    dit View just this section Comments (0) History

    login($data = null)

    you are doing some sort of Ajax-based login, you can use this method to

    manually log someone into the system. If you don't pass any value for $data, it

    ill automatically use POST data passed into the controller.

    ee comments for this section

    5.2.5.6 logout

    dit View just this section Comments (0) History

    rovides a quick way to de-authenticate someone, and redirect them to where

    hey need to go. This method is also useful if you want to provide a 'Log me

    ut' link inside a members' area of your application.

    xample:

    ee comments for this section

    5.2.5.7 passworddit View just this section Comments (0) History

    }

    ...

    }

    $data['User']['username'] = 'foo';

    $data['User']['password'] = 'bar';

    $hashedPasswords = $this->Auth->hashPasswords($data);

    $this->redirect($this->Auth->logout());

    http://book.cakephp.org/comments/index/383http://book.cakephp.org/comments/index/384http://book.cakephp.org/complete/170/Core-Components#login-388http://book.cakephp.org/complete/170/Core-Components#logout-385http://book.cakephp.org/edit/385/logouthttp://book.cakephp.org/view/385/logouthttp://book.cakephp.org/complete/170/Core-Components#comments-385http://book.cakephp.org/history/385/logouthttp://book.cakephp.org/complete/170/Core-Components#password-386http://book.cakephp.org/history/386/passwordhttp://book.cakephp.org/complete/170/Core-Components#comments-386http://book.cakephp.org/view/386/passwordhttp://book.cakephp.org/edit/386/passwordhttp://book.cakephp.org/complete/170/Core-Components#password-386http://book.cakephp.org/comments/index/385http://book.cakephp.org/history/385/logouthttp://book.cakephp.org/complete/170/Core-Components#comments-385http://book.cakephp.org/view/385/logouthttp://book.cakephp.org/edit/385/logouthttp://book.cakephp.org/complete/170/Core-Components#logout-385http://book.cakephp.org/comments/index/388http://book.cakephp.org/history/388/loginhttp://book.cakephp.org/complete/170/Core-Components#comments-388http://book.cakephp.org/view/388/loginhttp://book.cakephp.org/edit/388/loginhttp://book.cakephp.org/complete/170/Core-Components#login-388http://book.cakephp.org/comments/index/384http://book.cakephp.org/history/384/hashPasswordshttp://book.cakephp.org/complete/170/Core-Components#comments-384http://book.cakephp.org/view/384/hashPasswordshttp://book.cakephp.org/edit/384/hashPasswordshttp://book.cakephp.org/complete/170/Core-Components#hashPasswords-384http://book.cakephp.org/comments/index/383
  • 8/14/2019 Core Components

    19/40

    password (string $password)

    ass in a string, and you can get what the hashed password would look like.

    his is an essential functionality if you are creating a user registration screen

    here you have users enter their password a second time to confirm it.

    The auth component will automatically hash the password field if the

    username field is also present in the submitted data

    ake appends your password string to a salt value and then hashes it. The

    ashing function used depends on the one set by the core utility class Security

    sha1 by default). You can use the Security::setHash function to change the

    ashing method. The salt value is used from your application's configuration

    efined in your core.php

    ee comments for this section

    5.2.5.8 user

    dit View just this section Comments (0) History

    user(string $key = null)

    his method provides information about the currently authenticated user. The

    nformation is taken from the session. For example:

    can also be used to return the whole user session data like so:

    this method returns null, the user is not logged in.

    ee comments for this section

    5.2.6 AuthComponent Variablesdit View just this section Comments (4) History

    ow, there are several Auth-related variables that you can use as well. Usually

    ou add these settings in your Controller's beforeFilter() method. Or, if you

    eed to apply such settings side-wide, you would add them to App Controller's

    eforeFilter()

    ee comments for this section

    5.2.6.1 userModel

    if ($this->data['User']['password'] ==

    $this->Auth->password($this->data['User']['password2']))

    // Passwords match, continue processing

    ...

    } else {

    $this->flash('Typed passwords did not match', 'users/reg

    if ($this->Auth->user('role') == 'admin') {

    $this->flash('You have admin access');

    }

    $data['User'] = $this->Auth->user();

    http://book.cakephp.org/comments/index/386http://book.cakephp.org/comments/index/387http://book.cakephp.org/complete/170/Core-Components#AuthComponent-Variables-248http://book.cakephp.org/complete/170/Core-Components#user-387http://book.cakephp.org/view/387/userhttp://book.cakephp.org/view/387/userhttp://book.cakephp.org/view/387/userhttp://book.cakephp.org/complete/170/Core-Components#comments-387http://book.cakephp.org/complete/170/Core-Components#comments-387http://book.cakephp.org/complete/170/Core-Components#comments-387http://book.cakephp.org/history/387/userhttp://book.cakephp.org/complete/170/Core-Components#userModel-389http://book.cakephp.org/comments/index/248http://book.cakephp.org/history/248/AuthComponent-Variableshttp://book.cakephp.org/complete/170/Core-Components#comments-248http://book.cakephp.org/view/248/AuthComponent-Variableshttp://book.cakephp.org/edit/248/AuthComponent-Variableshttp://book.cakephp.org/complete/170/Core-Components#AuthComponent-Variables-248http://book.cakephp.org/comments/index/387http://book.cakephp.org/history/387/userhttp://book.cakephp.org/complete/170/Core-Components#comments-387http://book.cakephp.org/view/387/userhttp://book.cakephp.org/edit/387/userhttp://book.cakephp.org/complete/170/Core-Components#user-387http://book.cakephp.org/comments/index/386
  • 8/14/2019 Core Components

    20/40

    dit View just this section Comments (1) History

    on't want to use a User model to authenticate against? No problem, just

    hange it by setting this value to the name of the model you want to use.

    ee comments for this section

    5.2.6.2 fieldsdit View just this section Comments (0) History

    verrides the default username and password fields used for authentication.

    ee comments for this section

    5.2.6.3 userScopedit View just this section Comments (0) History

    se this to provide additional requirements for authentication to succeed.

    ee comments for this section

    5.2.6.4 loginActiondit View just this section Comments (0) History

    ou can change the default login from/users/login to be any action of your

    hoice.

    ee comments for this section

    5.2.6.5 loginRedirect

    dit View just this section Comments (8) History

    ormally, the AuthComponent remembers what controller/action pair you were

    rying to get to before you were asked to authenticate yourself. Upon a

    uccessful authentication you will be redirected to your original destination.

    owever, you can force people to go to a specific controller/action pair if

    eeded.

  • 8/14/2019 Core Components

    21/40

    ee comments for this section

    5.2.6.6 logoutRedirect

    dit View just this section Comments (0) History

    ou can also specify where you want the user to go after they are logged out,

    ith the default being the login action.

    ee comments for this section

    5.2.6.7 loginError

    dit View just this section Comments (0) History

    hange the default error message displayed when someone does not

    uccessfully log in.

    ee comments for this section

    5.2.6.8 authError

    dit View just this section Comments (0) History

    hange the default error message displayed when someone attempts to

    ccess an object or action to which they do not have access.

    ee comments for this section

    5.2.6.9 autoRedirect

    dit View just this section Comments (0) History

    ormally, the AuthComponent will automatically redirect you as soon as it

    uthenticates. Sometimes you want to do some more checking before you

    edirect users:

  • 8/14/2019 Core Components

    22/40

    The code in the login function will not execute unless you set

    $autoRedirect to false in a beforeFilter. The code present in the login

    function will only execute after authentication was attempted. This is the

    best place to determine whether or not a successful login occurred by

    the AuthComponent (should you desire to log the last successful login

    timestamp, etc.).

    ee comments for this section

    5.2.6.10 authorize

    dit View just this section Comments (2) History

    ormally, the AuthComponent will attempt to verify that the login credentials

    ou've entered are accurate by comparing them to what's been stored in your

    ser model. However, there are times where you might want to do some

    dditional work in determining proper credentials. By setting this variable to

    ne of several different values, you can do different things. Here are some of

    he more common ones you might want to use.

    When authorize is set to 'controller', you'll need to add a method called

    Authorized() to your controller. This method allows you to do some more

    uthentication checks and then return either true or false.

    emember that this method will be checked after you have already passed the

    asic authentication check against the user model.

    $this->Cookie->write('Auth.User', $cookie, t

    unset($this->data['User']['remember_me']);

    }

    $this->redirect($this->Auth->redirect());

    }

    if (empty($this->data)) {

    $cookie = $this->Cookie->read('Auth.User');

    if (!is_null($cookie)) {

    if ($this->Auth->login($cookie)) {

    // Clear auth message, just in case we

    $this->Session->del('Message.auth');

    $this->redirect($this->Auth->redirect())

    }

    }

    }

    }

    http://book.cakephp.org/complete/170/Core-Components#authorize-396http://book.cakephp.org/history/396/authorizehttp://book.cakephp.org/complete/170/Core-Components#comments-396http://book.cakephp.org/view/396/authorizehttp://book.cakephp.org/edit/396/authorizehttp://book.cakephp.org/complete/170/Core-Components#authorize-396http://book.cakephp.org/comments/index/395
  • 8/14/2019 Core Components

    23/40

    on't want to add anything to your controller and might be using ACO's? You

    an get the AuthComponent to call a method in your user model called

    Authorized() to do the same sort of thing:

    ee comments for this section

    5.2.6.11 sessionKey

    dit View just this section Comments (0) History

    ame of the session array key where the record of the current authed user is

    tored.

    efaults to "Auth", so if unspecified, the record is stored in "Auth.{$userModel

    ame}".

    ee comments for this section

    5.2.6.12 ajaxLogin

    dit View just this section Comments (0) History

    f you are doing Ajax or Javascript based requests that require authenticatedessions, set this variable to the name of a view element you would like to be

    endered and returned when you have an invalid or expired session.

    s with any part of CakePHP, be sure to take a look at

    ttp://api.cakephp.org/1.2/class_auth_component.html for a more in-depth look

    t the AuthComponent.

    ee comments for this section

    5.2.6.13 authenticate

    dit View just this section Comments (0) History

    http://book.cakephp.org/comments/index/396http://book.cakephp.org/complete/170/Core-Components#ajaxLogin-397http://book.cakephp.org/comments/index/397http://book.cakephp.org/comments/index/397http://book.cakephp.org/complete/170/Core-Components#authenticate-739http://book.cakephp.org/history/739/authenticatehttp://book.cakephp.org/complete/170/Core-Components#comments-739http://book.cakephp.org/view/739/authenticatehttp://book.cakephp.org/edit/739/authenticatehttp://book.cakephp.org/complete/170/Core-Components#authenticate-739http://book.cakephp.org/comments/index/397http://api.cakephp.org/1.2/class_auth_component.htmlhttp://book.cakephp.org/history/397/ajaxLoginhttp://book.cakephp.org/complete/170/Core-Components#comments-397http://book.cakephp.org/view/397/ajaxLoginhttp://book.cakephp.org/edit/397/ajaxLoginhttp://book.cakephp.org/complete/170/Core-Components#ajaxLogin-397http://book.cakephp.org/comments/index/737http://book.cakephp.org/history/737/sessionKeyhttp://book.cakephp.org/complete/170/Core-Components#comments-737http://book.cakephp.org/view/737/sessionKeyhttp://book.cakephp.org/edit/737/sessionKeyhttp://book.cakephp.org/complete/170/Core-Components#sessionKey-737http://book.cakephp.org/comments/index/396
  • 8/14/2019 Core Components

    24/40

    y default AuthComponent uses the hash function of the core utility class

    ecurity to hash passwords. But you can also configure it to use your own

    ashing logic if needed by setting authenticate to an object of a class which

    ontains a function named hashPasswords. This function would basically replicate

    he functionality of the component's hashPasswords function using your custom

    ashing logic. Check the api and maybe the code for the function itself for more

    nfo on how it works.

    ee comments for this section

    5.3 Cookiesdit View just this section Comments (0) History

    he CookieComponent is a wrapper around the native PHP setcookie method. It

    so includes a host of delicious icing to make coding cookies in your controllers

    ery convenient. Before attempting to use the CookieComponent, you must

    make sure that 'Cookie' is listed in your controllers' $components array.

    ee comments for this section

    5.3.1 Controller Setupdit View just this section Comments (2) History

    here are a number of controller variables that allow you configure the way

    ookies are created and managed. Defining these special variables in the

    eforeFilter() method of your controller allows you to define how the

    ookieComponent works.

    he following snippet of controller code shows how to include the

    Cookievariable

    defau lt description

    string

    $name

    'CakeCookie' The name of the cookie.

    string$key

    null This string is used to encrypt the value written tothe cookie. This string should be random anddifficult to guess.

    string$domain

    '' The domain name allowed to access the cookie. e.g.Use '.yourdomain.com' to allow access from all yoursubdomains.

    nt orstring$time

    '5 Days' The time when your cookie will expire. Integers areinterpreted as seconds and a value of 0 isequivalent to a 'session cookie': i.e. the cookieexpires when the browser is closed. If a string isset, this will be interpreted with PHP function

    strtotime(). You can set this directly within the write() method.

    string$path

    '/' The server path on which the cookie will be applied.If$cookiePath is set to '/foo/', the cookie will onlybe available within the /foo/ directory and all sub-directories such as /foo/bar/ of your domain. Thedefault value is the entire domain. You can set thisdirectly within the write() method.

    boolean$secure

    false Indicates that the cookie should only be transmittedover a secure HTTPS connection. When set to true,the cookie will only be set if a secure connectionexists. You can set this directly within the write()

    method.

    http://book.cakephp.org/complete/170/Core-Components#Cookies-177http://book.cakephp.org/edit/177/Cookieshttp://book.cakephp.org/view/177/Cookieshttp://book.cakephp.org/complete/170/Core-Components#comments-177http://book.cakephp.org/history/177/Cookieshttp://book.cakephp.org/complete/170/Core-Components#Controller-Setup-179http://book.cakephp.org/complete/170/Core-Components#Controller-Setup-179http://book.cakephp.org/history/179/Controller-Setuphttp://book.cakephp.org/complete/170/Core-Components#comments-179http://book.cakephp.org/view/179/Controller-Setuphttp://book.cakephp.org/edit/179/Controller-Setuphttp://book.cakephp.org/complete/170/Core-Components#Controller-Setup-179http://book.cakephp.org/comments/index/177http://book.cakephp.org/history/177/Cookieshttp://book.cakephp.org/complete/170/Core-Components#comments-177http://book.cakephp.org/view/177/Cookieshttp://book.cakephp.org/edit/177/Cookieshttp://book.cakephp.org/complete/170/Core-Components#Cookies-177http://book.cakephp.org/comments/index/739
  • 8/14/2019 Core Components

    25/40

    ookieComponent and set up the controller variables needed to write a cookie

    amed 'baker_id' for the domain 'example.com' which needs a secure

    onnection, is available on the path /bakers/preferences/, and expires in one

    our.

    ext, lets look at how to use the different methods of the Cookie Component.

    ee comments for this section

    5.3.2 Using the Componentdit View just this section Comments (1) History

    his section outlines the methods of the CookieComponent.

    rite(mixed $key, mixed $value, boolean $encrypt, mixed $expires)

    he write() method is the heart of cookie component, $key is the cookie

    ariable name you want, and the $value is the information to be stored.

    ou can also group your variables by supplying dot notation in the key

    arameter.

    f you want to write more than one value to the cookie at a time, you can pass

    n array:

    All values in the cookie are encrypted by default. If you want to store

    the values as plain-text, set the third parameter of the write() method

    to false.

    he last parameter to write is $expires the number of seconds before your

    ookie will expire. For convenience, this parameter can also be passed as a

    tring that the php strtotime() function understands:

    ead(mixed $key)

    his method is used to read the value of a cookie variable with the name

    pecified by $key.

    var $components = array('Cookie');

    function beforeFilter() {

    $this->Cookie->name = 'baker_id';

    $this->Cookie->time = 3600; // or '1 hour'

    $this->Cookie->path = '/bakers/preferences/';

    $this->Cookie->domain = 'example.com';

    $this->Cookie->secure = true; //i.e. only sent if using s

    $this->Cookie->key = 'qSI232qs*&sXOw!';

    $this->Cookie->write('name','Larry');

    $this->Cookie->write('User.name', 'Larry');

    $this->Cookie->write('User.role','Lead');

    $this->Cookie->write(

    array('name'=>'Larry','role'=>'Lead')

    );

    $this->Cookie->write('name','Larry',false);

    //Both cookies expire in one hour.$this->Cookie->write('firs

    // Outputs Larry

    echo $this->Cookie->read('name');

    http://book.cakephp.org/complete/170/Core-Components#Using-the-Component-180http://book.cakephp.org/edit/180/Using-the-Componenthttp://book.cakephp.org/view/180/Using-the-Componenthttp://book.cakephp.org/history/180/Using-the-Componenthttp://book.cakephp.org/complete/170/Core-Components#comments-180http://book.cakephp.org/view/180/Using-the-Componenthttp://book.cakephp.org/edit/180/Using-the-Componenthttp://book.cakephp.org/complete/170/Core-Components#Using-the-Component-180http://book.cakephp.org/comments/index/179
  • 8/14/2019 Core Components

    26/40

    el(mixed $key)

    eletes a cookie variable of the name in $key. Works with dot notation.

    estroy()

    estroys the current cookie.

    ee comments for this section

    5.4 Emaildit View just this section Comments (3) History

    he emailComponent is a way for you to add simple email sending functionality

    o your CakePHP application. Using the same concepts of layouts and view ctp

    les to send formated messages as text, html or both. It supports sending via

    he built in mail functions of PHP, via smtp server or a debug mode where it

    rites the message out to a session flash message. It supports file

    ttachments and does some basic header injection checking/ filtering for you.

    here is a lot that it doesn't do for you but it will get you started.

    ee comments for this section

    5.4.1 Class Attributes and Variables

    dit View just this section Comments (0) History

    hese are the values that you can set before you call EmailComponent::send()

    //You can also use the dot notation for read

    echo $this->Cookie->read('User.name');

    //To get the variables which you had grouped

    //using the dot notation as an array use something like

    $this->Cookie->read('User');

    //Delete a variable $this->Cookie->del('bar')

    //Delete the cookie variable bar, but not all under foo

    $this->Cookie->del('foo.bar')

    to address the message is going to (string)

    cc array of addresses to cc the message to

    bcc array of addresses to bcc (blind carbon copy) the message to

    replyTo reply to address (string)

    from from address (string)

    subject subject for the message (string)

    template

    The email element to use for the message (located inapp/views/elements/email/html/ and

    app/views/elements/email/text/)

    ayout

    The layout used for the email (located inapp/views/layouts/email/html/ and

    app/views/layouts/email/text/)

    ineLength Length at which lines should be wrapped. Defaults to 70.(integer)

    http://book.cakephp.org/complete/170/Core-Components#Email-176http://book.cakephp.org/complete/170/Core-Components#Class-Attributes-and-Variables-270http://book.cakephp.org/history/270/Class-Attributes-and-Variableshttp://book.cakephp.org/complete/170/Core-Components#comments-270http://book.cakephp.org/view/270/Class-Attributes-and-Variableshttp://book.cakephp.org/edit/270/Class-Attributes-and-Variableshttp://book.cakephp.org/complete/170/Core-Components#Class-Attributes-and-Variables-270http://book.cakephp.org/comments/index/176http://book.cakephp.org/history/176/Emailhttp://book.cakephp.org/complete/170/Core-Components#comments-176http://book.cakephp.org/view/176/Emailhttp://book.cakephp.org/edit/176/Emailhttp://book.cakephp.org/complete/170/Core-Components#Email-176http://book.cakephp.org/comments/index/180
  • 8/14/2019 Core Components

    27/40

    here are some other things that can be set but you should refer to the api

    ocumentation for more information

    ee comments for this section

    5.4.1.1 Sending Multiple Emails in a loop

    dit View just this section Comments (0) History

    f you wish to send multiple emails using a loop, you'll need to reset the email

    elds using the reset method of the Email component. You'll need to reset

    efore setting the email properties again.

    ee comments for this section

    5.4.2 Sending a basic messagedit View just this section Comments (0) History

    o send a message without using a template, simply pass the body of the

    message as a string (or an array of lines) to the send() method. For example:

    ee comments for this section

    5.4.2.1 Setting up the Layouts

    dit View just this section Comments (0) History

    o use both text and html mailing message you need to create layout files for

    hem, just like in setting up your default layouts for the display of your views in

    browser, you need to set up default layouts for your email messages. In thepp/views/layouts/ directory you need to set up (at a minimum) the following

    tructure

    hese are the files that hold the layout templates for your default messages.

    ome example content is below

    mail/text/default.ctp

    sendAshow do you want message sent string values oftext, html or

    both

    attachments array of files to send (absolute and relative paths)

    deliveryhow to send the message (mail, smtp [would require

    smtpOptions set below] and debug)

    smtpOptionsassociative array of options for smtp mailer (port, host,

    timeout,username, password)

    $this->Email->reset()

    $this->Email->from = 'Somebody ';

    $this->Email->to = 'Somebody Else Email->subject = 'Test';

    email/

    html/

    default.ctp

    text/

    default.ctp

    http://book.cakephp.org/comments/index/270http://book.cakephp.org/edit/528/Sending-Multiple-Emails-in-a-loophttp://book.cakephp.org/view/528/Sending-Multiple-Emails-in-a-loophttp://book.cakephp.org/view/528/Sending-Multiple-Emails-in-a-loophttp://book.cakephp.org/complete/170/Core-Components#comments-528http://book.cakephp.org/history/528/Sending-Multiple-Emails-in-a-loophttp://book.cakephp.org/comments/index/269http://book.cakephp.org/complete/170/Core-Components#Setting-up-the-Layouts-271http://book.cakephp.org/edit/271/Setting-up-the-Layoutshttp://book.cakephp.org/view/271/Setting-up-the-Layoutshttp://book.cakephp.org/complete/170/Core-Components#comments-271http://book.cakephp.org/complete/170/Core-Components#comments-271http://book.cakephp.org/history/271/Setting-up-the-Layoutshttp://book.cakephp.org/comments/index/528http://book.cakephp.org/comments/index/528http://book.cakephp.org/comments/index/528http://book.cakephp.org/comments/index/528http://book.cakephp.org/comments/index/528http://book.cakephp.org/complete/170/Core-Components#Sending-a-basic-message-269http://book.cakephp.org/history/271/Setting-up-the-Layoutshttp://book.cakephp.org/complete/170/Core-Components#comments-271http://book.cakephp.org/view/271/Setting-up-the-Layoutshttp://book.cakephp.org/edit/271/Setting-up-the-Layoutshttp://book.cakephp.org/complete/170/Core-Components#Setting-up-the-Layouts-271http://book.cakephp.org/comments/index/269http://book.cakephp.org/history/269/Sending-a-basic-messagehttp://book.cakephp.org/complete/170/Core-Components#comments-269http://book.cakephp.org/view/269/Sending-a-basic-messagehttp://book.cakephp.org/edit/269/Sending-a-basic-messagehttp://book.cakephp.org/complete/170/Core-Components#Sending-a-basic-message-269http://book.cakephp.org/comments/index/528http://book.cakephp.org/history/528/Sending-Multiple-Emails-in-a-loophttp://book.cakephp.org/complete/170/Core-Components#comments-528http://book.cakephp.org/view/528/Sending-Multiple-Emails-in-a-loophttp://book.cakephp.org/edit/528/Sending-Multiple-Emails-in-a-loophttp://book.cakephp.org/complete/170/Core-Components#Sending-Multiple-Emails-in-a-loop-528http://book.cakephp.org/comments/index/270
  • 8/14/2019 Core Components

    28/40

    mail/html/default.ctp

    ee comments for this section

    5.4.2.2 Setup an email element for the message

    body

    dit View just this section Comments (0) History

    n the app/views/elements/email/ directory you need to set up folders for text

    nd html unless you plan to just send one or the other. In each of these folders

    ou need to create templates for both types of messages refering to the

    ontent that you send to the view either by using $this->set() or using the

    contents parameter of the send() method. Some simple examples are shown

    elow. For this example we will call the templates simple_message.ctp

    ext

    tml

    ee comments for this section

    5.4.2.3 Controller

    dit View just this section Comments (0) History

    n your controller you need to add the component to your $components array or

    dd a $components array to your controller like:

    n this example we will set up a private method to handle sending the email

    messages to a user identified by an $id. In our controller (let's use the User

    ontroller in this example)

  • 8/14/2019 Core Components

    29/40

    ou have sent a message, you could call this from another method like

    ee comments for this section

    5.4.3 Sending A Message Using SMTPdit View just this section Comments (0) History

    o send an email using an SMTP server, the steps are similar to sending a basic

    message. Set the delivery method to smtp and assign any options to the Email

    bject's smtpOptions property. You may also retrieve SMTP errors generated

    uring the session by reading the smtpError property of the component.

    your SMTP server requires authentication, be sure to specify the username

    nd password parameters for smtpOptions as shown in the example.

    ee comments for this section

    5.5 Request Handlingdit View just this section Comments (0) History

    he Request Handler component is used in CakePHP to obtain additional

    nformation about the HTTP requests that are made to your applications. You

    an use it to inform your controllers about Ajax as well as gain additional insight

    nto content types that the client accepts and automatically changes to the

    ppropriate layout when file extensions are enabled.

    y default RequestHandler will automatically detect Ajax requests based on the

    TTP-X-Requested-With header that many javascript libraries use. When used

    n conjunction with Router::parseExtension() RequestHandler will automatically

    witch the layout and view files to those that match the requested type.

    urthermore, if a helper with the same name as the requested extension exists,

    will be added to the Controllers Helper array. Lastly, if XML data is POST'ed to

    our Controllers, it will be parsed into an XML object which is assigned to

    ontroller::data, and can then be saved as model data. In order to make use of

    equest Handler it must be included in your $components array.

    }

    $this->_sendNewUserMail ( $this->User->id );

    /* SMTP Options */

    $this->Email->smtpOptions = array(

    'port'=>'25',

    'timeout'=>'30',

    'host' => 'your.smtp.server',

    'username'=>'your_smtp_username',

    'password'=>'your_smtp_password');

    /* Set delivery method */

    $this->Email->delivery = 'smtp';

    /* Do not pass any args to send() */

    $this->Email->send();

    /* Check for SMTP errors. */

    $this->set('smtp-errors', $this->Email->smtpError);

  • 8/14/2019 Core Components

    30/40

    ee comments for this section

    5.5.1 Obtaining Request Informationdit View just this section Comments (1) History

    equest Handler has several methods that provide information about the clientnd its request.

    accepts ( $type = null)

    type can be a string, or an array, or null. If a string, accepts will return true if

    he client accepts the content type. If an array is specified, accepts return true if

    ny one of the content types is accepted by the client. If null returns an array of

    he content-types that the client accepts. For example:

    ther request 'type' detection methods include:

    isAjax()

    eturns true if the request contains the X-Requested-Header equal to

    MLHttpRequest.

    isSSL()

    eturns true if the current request was made over an SSL connection.

    isXml()

    eturns true if the current request accepts XML as a response.

    isRss()

    eturns true if the current request accepts RSS as a response.

    isAtom()

    eturns true if the current call accepts an Atom response, false otherwise.

    isMobile()

    eturns true if user agent string matches a mobile web browser, or if the clientccepts WAP content. The supported Mobile User Agent strings are:

    //rest of controller

    }

    ?>

    class PostsController extends AppController {

    var $components = array('RequestHandler');

    function beforeFilter () {

    if ($this->RequestHandler->accepts('html')) {

    // Execute code only if client accepts an HTML (

    } elseif ($this->RequestHandler->accepts('xml')) {

    // Execute XML-only code

    }

    if ($this->RequestHandler->accepts(array('xml', 'rss

    // Executes if the client accepts any of the abo

    }

    }

    http://book.cakephp.org/comments/index/174http://book.cakephp.org/history/350/Obtaining-Request-Informationhttp://book.cakephp.org/complete/170/Core-Components#comments-350http://book.cakephp.org/view/350/Obtaining-Request-Informationhttp://book.cakephp.org/edit/350/Obtaining-Request-Informationhttp://book.cakephp.org/complete/170/Core-Components#Obtaining-Request-Information-350http://book.cakephp.org/comments/index/174
  • 8/14/2019 Core Components

    31/40

    iPhone

    MIDP

    AvantGo

    BlackBerry

    J2ME

    Opera Mini

    DoCoMo

    NetFront

    Nokia

    PalmOSPalmSource

    portalmmm

    Plucker

    ReqwirelessWeb

    SonyEricsson

    Symbian

    UP.Browser

    Windows CE

    Xiino

    isWap()

    eturns true if the client accepts WAP content.

    ll of the above request detection methods can be used in a similar fashion to

    lter functionality intended for specific content types. For example when

    esponding to Ajax requests, you often will want to disable browser caching,

    nd change the debug level. However, you want to allow caching for non-ajax

    equests. The following would accomplish that:

    ou could also disable caching with the functionally analogous

    ontroller::disableCache

    ee comments for this section

    5.5.2 Request Type Detectiondit View just this section Comments (0) History

    equestHandler also provides information about what type of HTTP request has

    een made and allowing you to respond to each Request Type.

    isPost()

    eturns true if the request is a POST request.

    if ($this->RequestHandler->isAjax()) {

    Configure::write('debug', 0);

    $this->header('Pragma: no-cache');

    $this->header('Cache-control: no-cache');

    $this->header("Expires: Mon, 26 Jul 1997 05:00:00 GM

    }

    if ($this->RequestHandler->isAjax()) {

    $this->disableCache();

    }

    //Continue Controller action

    http://book.cakephp.org/complete/170/Core-Components#Request-Type-Detection-352http://book.cakephp.org/edit/352/Request-Type-Detectionhttp://book.cakephp.org/view/352/Request-Type-Detectionhttp://book.cakephp.org/complete/170/Core-Components#comments-352http://book.cakephp.org/history/352/Request-Type-Detectionhttp://book.cakephp.org/history/352/Request-Type-Detectionhttp://book.cakephp.org/complete/170/Core-Components#comments-352http://book.cakephp.org/view/352/Request-Type-Detectionhttp://book.cakephp.org/edit/352/Request-Type-Detectionhttp://book.cakephp.org/complete/170/Core-Components#Request-Type-Detection-352http://book.cakephp.org/comments/index/350
  • 8/14/2019 Core Components

    32/40

    isPut()

    eturns true if the request is a PUT request.

    isGet()

    eturns true if the request is a GET request.

    isDelete()

    eturns true if the request is a DELETE request.

    ee comments for this section

    5.5.3 Obtaining Additional Clientnformation

    dit View just this section Comments (0) History

    getClientIP()

    et the remote client IP address

    getReferrer()

    eturns the domain name from which the request originated

    getAjaxVersion()

    ets Prototype version if call is Ajax, otherwise empty string. The Prototype

    brary sets a special "Prototype version" HTTP header.

    ee comments for this section

    5.5.4 Responding To Requestsdit View just this section Comments (0) History

    n addition to request detection RequestHandler also provides easy access to

    tering the output and content type mappings for your application.

    setContent($name, $type = null)

    name string The name of the Content-type ie. html, css, json, xml. $type mixed

    he mime-type(s) that the Content-type maps to.

    etContent adds/sets the Content-types for the given name. Allows content-

    ypes to be mapped to friendly aliases and or extensions. This allows

    equestHandler to automatically respond to requests of each type in its startup

    method. Furthermore, these content types are used by prefers() and accepts().

    etContent is best used in the beforeFilter() of your controllers, as this will best

    everage the automagicness of content-type aliases.

    he default mappings are:

    javascript text/javascript

    js text/javascript

    json application/json

    css text/css

    html text/html, */*

    http://book.cakephp.org/comments/index/352http://book.cakephp.org/complete/170/Core-Components#Obtaining-Additional-Client-Information-351http://book.cakephp.org/comments/index/351http://book.cakephp.org/complete/170/Core-Components#Responding-To-Requests-353http://book.cakephp.org/history/353/Responding-To-Requestshttp://book.cakephp.org/complete/170/Core-Components#comments-353http://book.cakephp.org/view/353/Responding-To-Requestshttp://book.cakephp.org/edit/353/Responding-To-Requestshttp://book.cakephp.org/complete/170/Core-Components#Responding-To-Requests-353http://book.cakephp.org/comments/index/351http://book.cakephp.org/history/351/Obtaining-Additional-Client-Informationhttp://book.cakephp.org/complete/170/Core-Components#comments-351http://book.cakephp.org/view/351/Obtaining-Additional-Client-Informationhttp://book.cakephp.org/edit/351/Obtaining-Additional-Client-Informationhttp://book.cakephp.org/complete/170/Core-Components#Obtaining-Additional-Client-Information-351http://book.cakephp.org/comments/index/352
  • 8/14/2019 Core Components

    33/40

    text text/plain

    tx t text/plain

    csv application/vnd.ms-excel, text/plain

    form application/x-www-form-urlencoded

    file multipart/form-data

    xhtml application/xhtml+xml, application/xhtml, text/xhtml

    xhtml-mobile application/vnd.wap.xhtml+xml

    xml application/xml, text/xml

    rss application/rss+xml

    atom application/atom+xmlamfapplication/x-amf

    wap text/vnd.wap.wml, text/vnd.wap.wmlscript, image/vnd.wap.wbmp

    wml text/vnd.wap.wml

    wmlscript text/vnd.wap.wmlscript

    wbmp image/vnd.wap.wbmp

    pdfapplication/pdf

    zip application/x-zip

    tar application/x-tar

    prefers($type = null)

    etermines which content-types the client prefers. If no parameter is given the

    most likely content type is returned. If $type is an array the first type the client

    ccepts will be returned. Preference os determined primarily by the file

    xtension parsed by Router if one has been provided. and secondly by the list

    f content-types in HTTP_ACCEPT.

    renderAs($controller, $type)

    $controller - Controller Reference

    $type - friendly content type name to render content for ex. xml, rss.

    hange the render mode of a controller to the specified type. Will also appendhe appropriate helper to the controller's helper array if available and not

    ready in the array.

    respondAs($type, $options)

    $type - Friendly content type name ex. xml, rss or a full content type likeapplication/x-shockwave

    $options - If $type is a friendly type name that has more than one contentassociation, $index is used to select the content type.

    ets the response header based on content-type map names. If DEBUG is

    reater than 2, the header is not set.

    responseType()

    eturns the current response type Content-type header or null if one has yet to

    e set.

    mapType($ctype)

    aps a content-type back to an alias

    ee comments for this section

    5.6 Security Component

    http://book.cakephp.org/complete/170/Core-Components#Security-Component-175http://book.cakephp.org/comments/index/353
  • 8/14/2019 Core Components

    34/40

    dit View just this section Comments (1) History

    he Security Component creates an easy way to integrate tighter security in

    our application. An interface for managing HTTP-authenticated requests can be

    reated with Secur