Presentation is loading. Please wait.

Presentation is loading. Please wait.

Martin Kruliš 21. 3. 2016 by Martin Kruliš (v1.0)1.

Similar presentations


Presentation on theme: "Martin Kruliš 21. 3. 2016 by Martin Kruliš (v1.0)1."— Presentation transcript:

1 Martin Kruliš 21. 3. 2016 by Martin Kruliš (v1.0)1

2  Traditional Web Applications 21. 3. 2016 by Martin Kruliš (v1.0)2 Web Server Client ` Internet /var/www/myweb/ mod_php index.php HTTP request HTTP response with contents generated by a PHP script Database

3  Single Page Applications (SPA) 21. 3. 2016 by Martin Kruliš (v1.0)3 Web Server Client Internet HTML document and scripts Browser downloads static content (HTML, JS, …) ajax.php AJAX, WebSockets, …

4  Other Shades of Grey ◦ Traditional Applications with AJAX  Isolated operations are handled directly in the browser  Form validation and autocomplete  Long tables shown in multipage views  Simple single-click operations (e.g., deleting a record) ◦ Multiple Connected SPAs  Integrating multiple SPA into one larger application which share the user session  Typically used when a larger project is created as a composition of independent smaller projects 21. 3. 2016 by Martin Kruliš (v1.0)4

5  Expressing UI in the Browser ◦ Browser was originally designed as a viewer for static contents (HTML pages) ◦ Hyperlinks as controls  Leading to the same page with different query params  Changing application state of requires HTTP request  Only the view state can be changed (HTTP GET request) ◦ Forms  Smarter forms of hyperlinks (e.g., filter form)  Can use POST request to insert/update/delete data at server side  Single-button forms (like hyperlinks for POST actions) 21. 3. 2016 by Martin Kruliš (v1.0)5

6 Cookies  HTTP Is Stateless ◦ Applications require state (logged in user, contents of a shopping cart, currently selected page, …) 21. 3. 2016 by Martin Kruliš (v1.0)6 Passing on parameters in URL Sessions Database, Files, … Server SideClient Side Temporary Persistent JS, web storage

7  Passing on URL Parameters ◦ URL query parameters are not automatically kept ◦ Must be manually added to all generated URLs  Hyperlinks, form action fields, redirects, …  Such a task is quite tedious and error prone ◦ Use a framework/function for generating URLs  Automatically adds (sanitized) parameters from $_GET  Or more likely from an object which manages the params.  Other smart features can be added  Removing defaults, merging values, … 21. 3. 2016 by Martin Kruliš (v1.0)7 Example 1

8  Session ◦ Identification of a client over multiple HTTP req. ◦ Essential when user authentication is required ◦ Session ID must be kept at both client and server  Client – in URL query parameters or in cookies  Server – special storage with additional associated data  Session Hijacking ◦ One of the greatest security concerns of web apps. ◦ HTTPS must be used when session is maintained ◦ ID must be sufficiently long (hundreds of bits) and regenerated periodically 21. 3. 2016 by Martin Kruliš (v1.0)8

9  Opening Session ◦ Simple call to session_start() method ◦ Checks $_COOKIE and $_GET arrays for PHPSESSID variable which should have the ID ◦ If the variable is missing, new session is started  And a cookie with the new ID is set (if php.ini says so)  Accessing Session Data ◦ In the $_SESSION global array ◦ It can be read and written (incl. unset() on items) 21. 3. 2016 by Martin Kruliš (v1.0)9

10  Removing the Session ◦ session_unset() – clears the session (keeps the ID) ◦ session_destroy() – invalidates the session ID  Others ◦ session_name() – gets/sets name of the variable for the session ID ( PHPSESSID by default) ◦ session_id() – get/sets current session ID ◦ session_regenerate_id() – generate a new ID ◦ session_cache_expire(time) – sets time (in minutes) after which the session expires if not used 21. 3. 2016 by Martin Kruliš (v1.0)10 Example 2

11  Where to put which parameters? ◦ URL query ( $_GET )  Short term parameters (“changed” by hyperlinks)  Parameters affecting visualization (paging, filters, …)  Parameters that can be (effectively) bookmarked ◦ Session ( $_SESSION )  Parameters changed only on POST requests  User-related parameters (identity, shopping cart, …)  Parameters that should not be “visible” in URL ◦ Cookies ( $_COOKIE )  Long term parameters that should survive between sessions (long term sessions, tracking, …) 21. 3. 2016 by Martin Kruliš (v1.0)11

12  Study Case – Editing Form ◦ Edit personal data of existing user 21. 3. 2016 by Martin Kruliš (v1.0)12 Full Name: <input name="fullname" type="text" value="Martin Kruliš"> Date of Birth: <input name="born" type="date" value="14.4.1984"> Married: <input name="married" type="checkbox" checked> Children: <input name="children" type="number" value="0"> Various data types (string, date, bool, and integer respectively)

13  Study Case – Editing Form ◦ Major concerns  Appropriate mapping between HTML form and PHP script processing its POST request  Item names, types, …  Data are transferred as strings (no matter orig. type)  Two level sanitization (client side, server side)  What to do when the server side validation fails  Data has to be loaded from the database (existing user)  Mapping DB object data to form elements  Some data may not be editable by the form  Which data to show when the server side validation failed and the form is being re-shown with errors 21. 3. 2016 by Martin Kruliš (v1.0)13

14  Redirect (303 See Other) after POST 21. 3. 2016 by Martin Kruliš (v1.0)14 Client (Browser) Web Server POST Request Redirect (new URL) add/change something Refresh GET (new URL) HTML Page read-only Redirects to a new URL (without updating history)

15  Study Case – Editing Form ◦ Form Component  Each form is represented by one object  Responsible for rendering and HTTP data processing  And handling the serialization or data conversions ◦ Sticky Forms  Form remembers user inputs even if they are incorrect  I.e., even if a result was not saved to the database and the form needs to allow the user fix the input mistakes  Data are stored in a session  Additional identifier is required that is passed to the URL query parameters (in case multiple windows are opened) 21. 3. 2016 by Martin Kruliš (v1.0)15 Example 3

16  Study Case – Flash Messages ◦ Notifications that should appear exactly once  E.g., “the data were saved”, “the e-mail was sent”, …  Non-persistent error messages ◦ Where to put the text (or ID) of such message, if…  The message should not get lost nor it should be displayed long after the operation is finished  The user may click refresh button  The user may use back/forward buttons  The user may copy/bookmark the URL  The HTTP request may be interrupted and refreshed 21. 3. 2016 by Martin Kruliš (v1.0)16

17  Front Controller ◦ Software design pattern that provides centralized entry point for all request (commands) ◦ All URLs point to the same script  Actual action is determined from URL query parameters 21. 3. 2016 by Martin Kruliš (v1.0)17 Controller/Presenter … Action … Front Controller ( index.php ) Front Controller ( index.php ) HTTP Initializing the libraries, setting up the container Routing and dispatching

18  Model-View-Controller ◦ Design pattern that clearly divides responsibilities 21. 3. 2016 by Martin Kruliš (v1.0)18 View Controller Model Manipulates Prepares Loads data from Handles business logic. Action of the controller is invoked by front controller Handles business logic. Action of the controller is invoked by front controller Encapsulates data loading and data manipulation (e.g., in a database) Responsible for formatting (presenting) data in HTML (JSON, XML, …)

19  Model-View-Presenter ◦ A derivation of MVC pattern  Presenter have similar role as controller ◦ Presenter strictly separates model and view  View should no longer access model directly  Data from model are passed to view by presenter 21. 3. 2016 by Martin Kruliš (v1.0)19 Updates View Presenter Model Send data Send events Prepares

20  Templates ◦ Libraries that help with formatting the data (HTML)  Simplifying syntax (abstracting from low level PHP)  Providing additional functions for formatting  Date, time, currency, …  Handling data sanitization (preventing script injection)  Handling language translations ◦ The controller/presenter prepares the data for the view and the view fills them into the template ◦ Many approaches to templating exist  Simple frameworks rely on PHP-HTML interleaving, complex ones use their own syntax and preprocessing 21. 3. 2016 by Martin Kruliš (v1.0)20

21  Latte Templates Example Latte Example {$item|capitalize} {if ($user)} User {$user->login} Name: {$user->name} Home page: homepage">{$user->homepage} {/if} 21. 3. 2016 by Martin Kruliš (v1.0)21 The same text will appear in the title of the page If and foreach are translated in PHP structures Value filtering Alternative syntax for if statement Context-aware escaping

22  Controller/Presenter ◦ One class that represents one (logical) page ◦ Multiple actions  Each action is a method  Rendering actions  Initialize a template, produce HTML (JSON, XML, …)  Other actions (POST actions)  Update model and respond with redirect  Careful when using POST actions for AJAX calls ◦ Naming convention for classes and methods 21. 3. 2016 by Martin Kruliš (v1.0)22

23  Component-based Development ◦ Modern applications use components to promote encapsulation and separation of concerns  Component – a software module that provides some well defined functionality through a set of interfaces  In PHP, typically a class that implements interfaces ◦ Component construction and management  A centralized manager (application server, container, …) has to be present to create components  Especially to handle component dependencies 21. 3. 2016 by Martin Kruliš (v1.0)23

24  Dependency Injection ◦ Design pattern that implements inversion of control  Component is not responsible for seeking its own dependencies  Dependencies are injected externally (by container) ◦ Declaring dependencies  In configuration, by annotations, using reflection, …  Problem of cyclic dependencies  DB component requires log to log errors  Log may require DB component to save messages 21. 3. 2016 by Martin Kruliš (v1.0)24

25  Example /** * @component WelcomePage */ class WelcomePageController implements IController { /** @inject IDatabase */ public $db; /** @inject name="NewsService" */ public $news; function __construct(ILog $log) {... } } 21. 3. 2016 by Martin Kruliš (v1.0)25 Component naming convention Annotations (inject by interface) Annotations (inject by name) Constructor injection (by type hinting)

26  Authentication ◦ Verifies identity of a user  E.g., by user credentials, by a certificate, … ◦ User identity must be kept within the session  The session must be secured to prevent identity stealing ◦ Password security  Password should not be stored in plain text nor in decryptable form in the database, but rather hashed ,hashfnc(, )  The hashfnc could be SHA-256, SHA-512, bcrypt, scrypt, …  PHP has built-in functions for password hashing  crypt(), password_hash(), password_verify() 21. 3. 2016 by Martin Kruliš (v1.0)26 PHP 5.5

27  Authentication Embedded in HTTP ◦ If the auth. information are provided, they are in  $_SERVER['PHP_AUTH_USER']  $_SERVER['PHP_AUTH_PW'] ◦ The script can request authentication data header('WWW-Authenticate: Basic realm="Auth test"'); header('HTTP/1.0 401 Unauthorized'); exit; ◦ Potential problems  Password is sent with every request  Logout operation is not very well defined 21. 3. 2016 by Martin Kruliš (v1.0)27

28  Authorization ◦ Process of verification access rights of the user ◦ Security Model  Defines protected objects, authorities, operations  Simple (state-less) models  Function (object, authority, operation) -> yes/no  More complex models exist  Typically implemented in one class (component) ◦ Roles  Authorities are typically not individual users, but roles  Each user have one (or multiple) roles 21. 3. 2016 by Martin Kruliš (v1.0)28

29  Security Models Examples ◦ Directory (Capability List)  Authorities have lists of accessible objects ◦ Access List  Protected objects have lists of users (+permissions) ◦ Access Control Matrix  Rows ~ authorities, cols ~ objects, items ~ access rights ◦ Bell-La Padula  Each authority has maximal level of access, each object has minimal required level of access 21. 3. 2016 by Martin Kruliš (v1.0)29

30  Access Control List (ACL) Example authorizator: setup: - addRole('user') - addRole('editor', 'user') - addRole('admin', 'editor') - addResource('Homepage') - addResource('Archive') - addResource('Users') - allow('user', 'Homepage', 'default') - allow('user', 'Archive', 'default') - allow('user', 'Users', 'default') - allow('user', 'Users', 'show') - allow('editor', 'Users', 'show-private') - allow('editor', 'Archive', 'create') - allow('editor', 'Archive', 'edit') - allow('editor', 'Archive', 'delete') - allow('admin') 21. 3. 2016 by Martin Kruliš (v1.0)30 Authorities (roles) Protected objects (resources) corresponds to controllers here List of all access privileges (what is not explicitly allowed, is denied) Admin is allowed everything

31  Application Errors ◦ User errors (e.g., filling a wrong value to form)  Ideally, they should be part of normal operations (application explains problem/offers remedy) ◦ Temporary errors/soft errors (e.g., DBMS is offline)  “Try it later” message + notify administrator by e-mail ◦ Hard errors (bugs)  Generic message for the user “error occurred …”  Log the error and notify administrator  Position in the code, stack trace, variable dumps, …  URL, POST body, logged user, session data, …  In some cases it might help to allow user add comments 21. 3. 2016 by Martin Kruliš (v1.0)31 Who is General Failure and why is he reading my disk?

32  Error Levels ◦ Define the severity of the error  E_ERROR – fatal errors, terminate the script  E_WARNING – severe errors, but recoverable  E_NOTICE – unusual situations (possible error)  E_USER_xxx – user level error, warning, or notice  E_STRICT – suggestion for improvement ◦ The log can filter selected error levels  Controlled in php.ini or by error_reporting() ◦ User errors can be triggered manually  trigger_error() 21. 3. 2016 by Martin Kruliš (v1.0)32

33  Error Control Operator ◦ Symbol @ prepended to an expression ◦ All error messages from the expression are ignored ◦ For specific local solutions only (use with caution) $data = @file('data_file.txt') or die('Error…');  Information about Errors ◦ The handling callback gets error level and position ◦ debug_backtrace() – retrieves current call stack ◦ debug_print_backtrace() – prints call stack 21. 3. 2016 by Martin Kruliš (v1.0)33

34  Concept of Exceptions ◦ Similar to other object languages  Exceptions are thrown and caught ( throw, catch )  Exception is an object of class Exception or derived class ◦ Used for reporting errors  Especially from deeply nested code ◦ Note that …  Uncaught exception causes Fatal Error  Destructors should not throw exceptions  Throwing-catching process is somewhat slow 21. 3. 2016 by Martin Kruliš (v1.0)34

35  Try-catch Blocks ◦ Exception-safe code is wrapped in try block ◦ First matching catch block handles the exception  Exception is matched by its class try {... throw new Exception('Error …');... } catch (MyException $e) {... My exception handler... } catch (Exception $e) {... Generic exception handler... } 21. 3. 2016 by Martin Kruliš (v1.0)35

36  Creating Custom Exceptions ◦ Exception class is derived from Exception ◦ Derived classes need not to override any methods  If the constructor is overridden, parent constructor must be invoked  It is recommended to redefine __toString() ◦ When to customize…  To distinguish a new error type  To add additional data to the exception object 21. 3. 2016 by Martin Kruliš (v1.0)36

37 21. 3. 2016 by Martin Kruliš (v1.0)37


Download ppt "Martin Kruliš 21. 3. 2016 by Martin Kruliš (v1.0)1."

Similar presentations


Ads by Google