My first zf presentation part two


Published on

1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

My first zf presentation part two

  1. 1. My Very First…Model View Controller Web Applicationwith the ZendFramework – Part Deux<br />New York CityZF Meetup<br />
  2. 2. Previously…<br />MVC Basics<br />Zend_Controller_Action, Zend_View, view scripts<br />ZF application structure<br />Where do I find file xyz?<br />Database<br />Zend_DB<br />Forms<br />Zend_Form, Zend_Form_Element, Zend_Validate<br />Zend Tool<br />Project set-up tasks simplified<br />
  3. 3. Part One  Part Two<br />Finished With<br />User table set-up<br />Registration form completed<br />Added between Part One and Part Two: <br />User home page (home action in UserController)<br />A few more users<br />Extension of Zend_Controller_Action<br />Explanation forthcoming<br />
  4. 4. Part Two<br />Security<br />Authentication<br />Authorization<br />ZF Dispatch Process<br />Action helpers<br />Layouts<br />View Helpers (briefly)<br />
  5. 5. Step 8: Security<br />Need to make sure non-logged in users can’t see user home page.<br />Should still be able to see user register page and about page.<br />Members should be able to do everything except admin tasks<br />
  6. 6. User Access Security<br />General Pattern (not ZF specific) - two components<br />Authentication<br />Verify that a user is who they say they are<br />Authorization <br />Verify that an authenticated user is allowed to do something<br />
  7. 7. User Access Security<br />Analogous to getting into a bar:<br />The bouncer authenticates you when he looks at your ID and decides whether it’s real or not<br />The bouncer authorizes you to enter when he sees that your ID says you’re 21, and that you’re not beyond redemption for the night<br />
  8. 8. ZF – User Access Security<br />Authentication – Zend_Auth<br />Adapter based authentication, including:<br />Zend_Db (users stored in DB)<br />OpenID<br />LDAP<br />Others<br />Authorization – Zend_Acl<br />Access Control List<br />Your app’s bouncer<br />
  9. 9. Zend_Auth<br />Zend_Auth is a class, implements singleton<br />Access singleton auth instance with:<br />Zend_Auth::getInstance()<br />Instance methods for:<br />Is user logged in? - Zend_Auth::hasIdentity()<br />What is user’s identity? – Zend_Auth::getIdentity()<br />Clear identity – Zend_Auth::clearIdentity()<br />Adapter authenticate– Zend_Auth::authenticate($adapter)<br />
  10. 10. Zend_Auth<br />Can handle storage of identity<br />Defaults to storage as session variable<br />Coordinates authentication, doesn’t do it<br />Adapters handle actual authentication<br />I.e., user password lookup is handled by MyApp_Auth_Adapter<br />
  11. 11. Auth: Deny Guest Access to Home<br />Grab auth instance, test for identity:<br />If identity, user is logged in<br />If not, user is guest, redirect to login<br />Note, no need for adapter here as we’re not performing authentication<br />
  12. 12. Auth: Use of Adapters for Login<br />Redirect logged in user home.<br />Process login attempt.<br />
  13. 13. Db Adapter: Setup<br />Constructor needs<br />Db adapter<br />Name of table<br />Name of ID column (i.e. user name, email)<br />Name of credential column (i.e. password)<br />
  14. 14. Db Adapter: Setup<br />Pass in posted email and password<br />setIdentity – Tell the adapter the identity the user is trying to log in with.<br />setCredential – Tell the adapter the credential the user is trying to log in with. <br />
  15. 15. Db Adapter: Authenticate…<br />Well, kind of<br />Don’t use adapter’s authentication method directly, use Zend_Auth::authenticate and pass the adapter<br />Let’s Zend_Auth store identity in session<br />
  16. 16. Auth: Authentication Successful?<br />Zend_Auth::authenticate returns instance of Zend_Auth_Result<br />Use Zend_Auth_Result::isValid to determine success or failure<br />Zend_Auth_Result:: getCodeto get details (useful on auth failure)<br />
  17. 17. Auth Accomplished!<br />We can now control access based on log in status!<br />Good enough for simple access control needs:<br />Any user has access to home action<br />No guest has access to home action<br />
  18. 18. Auth Accomplished?<br />What about something like delete user action?<br />Being logged in isn’t good enough<br />Would like to base decision on information about the user<br />Is this user an admin?<br />Is this user a plain vanilla user?<br />
  19. 19. Auth Accomplished…But Not Authorization<br />What we’re asking is: does this authenticated user have permission to do this thing?<br />This isn’t the responsibility of auth<br /> Authorization is the process of determining if a user has access to do an action.<br />Generally, two steps:<br />Determine type of user<br />Ask if that type of user is allowed to perform the requested action (delete a user, edit a task, etc)<br />
  20. 20. Authorization: Zend_Acl<br />ZF has Access Control List component<br />Effectively, table of rules for access<br />Rules can be specified flexibly and hierarchically<br />One of ZF’s best components<br />
  21. 21. Access Control Concepts<br />Role – user access level (your role in a system)<br />Resource – a thing a user requests access to<br />Privilege – describes an action a user may perform on a resource<br />Roles and resources can be hierarchical<br />Member inherits privileges from guest<br />Admin inherits privileges from member<br />
  22. 22. Zend_Acl<br />Access control list is an object.<br />Four steps to configure<br />Create object<br />Add roles<br />Add resources<br />Set rules<br />Query acl using Zend_Acl::isAllowed()<br />
  23. 23. TaskMaster Access Control Roles<br />Start with 4 roles, must be declared in advance:<br />Guest<br />Member, inherits from guest<br />Staff, inherits from member<br />Admin, inherits from Staff<br />
  24. 24. TaskMaster Access Control Resources<br />Strategy:<br />One controller = one resource<br />One action = one privilege<br />Doesn’t have to be done this way, but is often sensible and convenient later on.<br />3 Resources, do need to be declared in advance<br />User<br />Task<br />Index<br />Privileges don’t need to be declared in advance<br />
  25. 25. ACL Creation: Roles and Resources<br />Add roles and resources first<br />Exception thrown if an unregistered role or resource is referred to:<br />
  26. 26. ACL Configuration: Create Rules<br />“Rules” tell the ACL when to allow/deny a user access to a resource<br />“Allow members to edit their info”<br />“Don’t let members delete other members”<br />“Allow an admin to do anything”<br />Syntax: <br />$acl->allow/deny($user, $resource, $privilege)<br />Parameters are flexible, see ZF reference<br />
  27. 27. ACL Configuration: Rules<br />Allow the admin all privileges on all resources<br />Deny guest all privileges on all resources<br />Note that this denies all privileges for anyone who inherits from guest as well (member, staff)<br />Note that deny all happens by default, this is to be explicit<br />
  28. 28. ACL Configuration: Guest Rules<br />Allow guest access to:<br />Index controller pages (about page, etc)<br />Register and login insider UserController<br />Error controller (technicality, but good to do for later)<br />
  29. 29. ACL Configuration: Member Rules<br />Allow member access to:<br />Do anything inside UserController, except delete a user<br />Do anything with tasks<br />Note that further security is needed to make sure members can’t mess with other people’s tasks, but this won’t happen here.<br />
  30. 30. ACL Configuration: Staff<br />Let staff delete users:<br />
  31. 31. Access Control Accomplished…<br />Well, Access Control created…<br />
  32. 32. Point of Auth and Access Control?<br />Fantastic, I have things that will control access to my app<br />Where do I use them?<br />
  33. 33. Point of Control?<br />Could test inside each action method…<br />
  34. 34. Point of Access Control?<br />Works, but not ideal:<br />Very redundant<br />What if you want to add logic later<br />Logging<br />Blacklist IP of repeat offender<br />Etc<br />Separation of concerns: action method should only have to worry about what it does.<br />
  35. 35. Point of Access Control?<br />What we’d like is to:<br />Put the Access Control logic in one place, have it run before all action methods<br />If the user is allowed, proceed as usual<br />If not, redirect to login (for guest) or home (for member)<br />Almost like a “onPreAnyActionMethod” hook…<br />
  36. 36. Detour: ZF Dispatch Process<br />Stuff happens before and after action method<br />Hooks exist in ZF controller architecture, various ways to plug in.<br />Observe an event, idea similar to<br />Javascript events<br />Doctrine model/connection events<br />Firefox plugins<br />Let’s take a look at the app flow…<br />
  37. 37. ZF Request Dispatch Process<br />Simplified ZF Request Process<br />Request to Response<br />
  38. 38. Point of Access Control in ZF Request Dispatch Process<br />preDispatch lets us make a decision before the action runs<br />
  39. 39. preDispatch<br />preDispatch happens before the action method is dispatched<br />Always runs, hard-coded into controller architecture<br />Can redirect or otherwise alter request in preDispatch<br />3 ways to hook into preDispatch<br />
  40. 40. ZF – preDispatch Phase<br />Three parts of preDispatch<br />
  41. 41. ZF – preDispatch Options<br />Three ways to hook into preDispatch phase:<br />Use preDispatch method of the controller<br />Use action helpers <br />Use front controller plugins<br />
  42. 42. preDispatch Option #1: Method of Controller<br />Zend_Controller_Action has preDispatch method.<br />Override in extending class.<br />
  43. 43. preDispatch Option #1: Method of Controller<br />Pros:<br />Simple<br />Always runs before action method<br />Cons<br />Can be overridden in extending class<br />Extending class must call parent method, doesn’t happen implicitly<br />All controllers must extend same base class<br />
  44. 44. preDispatch Options #2 and #3:Plugins and Action Helpers<br />Plugins and Action helpers are:<br />Objects<br />With preDispatch methods<br />preDispatch methods are run prior to action method<br />Will run no matter what controller is being invoked<br />
  45. 45. preDispatch Options #2 and #3:Plugins and Action Helpers<br />Similar to:<br />Javascript event listeners<br />Doctrine event listeners<br />Can plugin as many or as few as you like<br />
  46. 46. preDispatch Options #2 and #3:Plugins and Action Helpers<br />Pros:<br />Harder to accidentally over-ride: aren’t over-riden by sub-classes of controller base class.<br />Run before action method of any controller<br />Highly modular<br />Hook into multiple events with one class<br />Cons:<br />Small increase in complexity:<br />Need to know what they are<br />Another place to look for logic<br />
  47. 47. Plugins and Action Helpers<br />Plugins register with Front Controller<br />Plugins have more opportunities to hook into dispatch flow (7 hooks available)<br />Action helpers register with a special broker<br />Can access controller object easily in pre and post dispatch<br />Can also provide extra functionality (help) to the controller<br />We’ll deal with action helpers<br />
  48. 48. Action Helpers<br />This is an action helper…that’s it<br />preDispatch method is called inside ZF<br />
  49. 49. Auth Action Helper:<br />Get the user object, if available, inject into controller<br />
  50. 50. ACL Action Helper<br />Grab user from controller (assume Auth helper goes first)<br />Redirect to login if access denied (simply reset action and controller name)<br />
  51. 51. Security Accomplished!<br />Use Zend_Auth to verify a user is who he says he is<br />Use Zend_Acl to verify that person can do what he’s requesting<br />Use action helpers (or front controller plugins) to reliably hook into application flow without repeating yourself<br />
  52. 52. While We’re on Action Helpers<br />Register helpers with the helper broker:<br />Zend_Controller_Action_HelperBroker::addHelper(new Zx_Controller_Action_Helper_Acl());<br />Need not implement pre/postDispatch<br />Access in action methods for help with complex logic<br />From with controller:<br />$this->_helper->helperName (overloading)<br />$this->getHelper($helperName)<br />Can help keep controller classes clean<br />Many built in, including…<br />
  53. 53. Action Helpers: Redirector<br />Lets you redirect user without dealing with headers<br />
  54. 54. Action Helpers: JSON<br />Easily send JSON response, appropriate headers sent, data encoded.<br />
  55. 55. Action Helpers: Action Stack<br />Stack actions to run after the current action.<br />Can help widgetize pages:<br />User edit page might be combination of 4 forms, rather than 1 giant form<br />
  56. 56. Not Bad…<br />We have:<br />DB access up and running<br />User system running<br />Basic security<br />And we can make and user action helpers<br />But…<br />
  57. 57. Doesn’t Look Great<br />
  58. 58. Back to the View<br />Would like to create a site wide look and feel<br />Each view script should only be responsible for it’s content<br />Almost want a template to inject view script output into<br />
  59. 59. Site Wide Layout: Zend_Layout<br />ZF has layout component<br />Single view script that runs after main content is generated<br />Can inject content into the desired location<br />Can change layout script in different parts of site<br />Disable if necessary (JSON/XML response, etc)<br />Integrates with JSON action helper, other components<br />
  60. 60. Zend_Layout: Setup<br />Enable in application.ini<br />Enables layout resource, sets default layout script<br />/views/layouts/default.phtml will be layout<br />Default specified in first line, phtml ext assumed<br />
  61. 61. Zend_Layout: Layout File<br />View script output injected into markup<br />
  62. 62. Zend_Layout: Voila!<br />Modified from<br />
  63. 63. Layout: Explained<br />View script output is buffered and stored in response object<br />Output stored in content “segment” by default.<br />Output can be organized into different segments.<br />Layout view script has access to the response segments, and injects them into the template<br />
  64. 64. Layout: Explained<br />Q: How does the layout script get the response segments:<br />A: The layout view helper.<br />
  65. 65. View Helpers<br />View Helpers are to View Scripts what Action Helpers are to Action Methods<br />Objects plugged into the view to separate complex logic from display logic<br />From inside a view script, access with:<br />$helper = $this->helperName<br />$layoutHelper = $this->layout<br />$urlHelper = $this->url<br />
  66. 66. Layout View Helper<br />Here, the layout view helper is accessed…<br />…and it’s content property contains the content segment of the response<br />
  67. 67. URL View Helper<br />Forms URL based on a route<br />Useful when doing non-standard routing<br />
  68. 68. Action View Helper<br />Run an action, grab the output, and place it where you want it:<br />
  69. 69. Further Resources<br />ZF Reference Guide<br /><br />Zend Casts<br /><br />The Internet<br /><br />
  70. 70. Questions?<br />
  71. 71. New York City area Zend Framework Meetup<br /><br />Affiliated with<br />Thanks for attending “Your First Zend Framework Project, Part Two” <br />presented on March 22, 2011 by<br />Isaac Foster<br /><br />Alan Seiden<br />http://www.alanseiden.comalan@alanseiden.comTwitter: @alanseiden<br />Sign up to hear about all our ZF meetups at<br />