SitePoint Sponsor

User Tag List

Results 1 to 7 of 7
  1. #1
    SitePoint Enthusiast jitao's Avatar
    Join Date
    Feb 2003
    Location
    Shanghai
    Posts
    42
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    OOP and access control

    Hello,
    Now, I'm using fusebox for php as the structure of our web app and use the access control functions in phplib7.4. They work fine at this moment.

    After reading many posts in this forum I try to structure my web app as voostind mentioned in http://www.sitepointforum.com/showth...threadid=74109 ? Using the Application class.

    But I find it is very hard to implement the Authentication or Permission class to control the access.

    I don't know
    1.Where I should initialize the Authentication class?.

    2.What are the basic vars and functions an Authentication class should have?

    3.Who is responsible for prompting a login page, Application class or the Authentication class?

    Ji Tao

  2. #2
    midnight coder
    Join Date
    Dec 2000
    Location
    The flat edge of the world
    Posts
    838
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    An Authentication class sounds...C'ish, it's just a bunch of related functions wrapped in a class, and doesn't really have an OO feel. For a more object-orientated approach, isn't it more natural to have a User class, that has methods like login() and logoff(), as well as other stuff a User can do, such as postArticle() and buyItem()?

    As the Application class starts, an User object is created, and uses login(), if it returns false, Application points the person to another page, such as a login page
    Work smarter, not harder. -Scrooge McDuck

  3. #3
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm working on this assumption myself (w/out fusebox of course) so once I get something to work as it should I post the script ?

    Maybe that'll help and if my OOP designs are incorrect then of course folks at this forum will help

  4. #4
    SitePoint Enthusiast Powerlord's Avatar
    Join Date
    May 2003
    Location
    Mason, MI, USA
    Posts
    37
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I would think that including single module things like postArticle() and buyItem() to a User class would be a Bad Idea (tm)*.

    Actually, having a base user class with login and logout functions wouldn't be a bad idea... maybe just use the extends keyword when creating a class with the aforementioned functions...

    * With HTML disabled, I can't use HTML entities.
    Ross Bemrose,
    Independant MySQL/Perl/PHP Developer

  5. #5
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yer, was thinking of doing that with my Form Validations/Xml Transformation classes; although based on some MVC by trickie (thanks again btw) I keep the VIEWs and MODELs as seperate classes.

    Just makes things more maintainable I suppose and is the approach taken by MVC no ?

  6. #6
    SitePoint Enthusiast jitao's Avatar
    Join Date
    Feb 2003
    Location
    Shanghai
    Posts
    42
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank your replies, Here is my try to implement a User class:
    PHP Code:
    /*
     Every logged in user have a session variable $_SESSION['user']
    It is an array.
    $_SESSION['user']['uid'] User's unique id in database,
    $_SESSION['user']['name'] User's real name,
    $_SESSION['user']['level'] User's permission level,
    $_SESSION['user']['errors']  The user login error message.
    */
    class User 
    {
     function 
    User() 
     {
      if(!isset(
    $_SESSION['user'])) 
      {
       
    $_SESSION['user']['uid']=0;
       
    $_SESSION['user']['realname']='';
       
    $_SESSION['user']['level']='guest';
       
    $_SESSION['user']['errors']='';
      }
     }
     
     function 
    login() 
     {
      
    // check the database against the username and password
      // if good (username and password)
      // 1. set the $_SESSION['user'] variable.
      // 2. return true
      // else
      // 1. set the $_SESSION['user']['errors']
      // 2. return false.
     
    }
     
    function 
    logout() 
     {
       unset(
    $_SESSION['user']['uid']);
       unset(
    $_SESSION['user']['realname']);
       
    $_SESSION['user']['level']='guest';
       
    $_SESSION['user']['errors']='';
     }
     
    function 
    getUid() 
     {
      Return 
    $_SESSION['user']['uid'];
     }
     
    function 
    getErrors() 
     {
      Return 
    $_SESSION['user']['errors'];
     }
     
    function 
    checkLevel($required
     {
      
    //Compare the current user level $_SESSION['user']['level'] with the $required
      //if good
      // return true
      // else
      // 1. return false
      // 2. and set the $_SESSION['user']['errors'];
     
    }

    And Now I have an Application class like following:

    PHP Code:
    class Application 
    {
     var 
    $user;
     
     function 
    Application() 
     {
     }
     function 
    run() 
     {
      
    $this->user = new User ();
      if(
    $this->user->getUid()) 
      {
       
    // if the session variable $_SESSION['user']['uid'] is set we assum he is a logged in user. 
       // And check his permission level
        
    if($this->user->checkLevel($this->getRequiredLevel)) 
        {
          
    $page =& $this->loadPage($this->getCurrent());
        }
        else
        {
          
    $page = & $this->loadPage($this->getNoLevelPage());
        }
      }
      
    // if session variable $_SESSION['user']['uid'] is not set, we try to test the password and username
      
    elseif(isset($_POST['username'])&&isset($_POST['password'])) 
      {
        if(
    $this->user->login()) 
        {
          
    // now check if the user has required access level
          
    if($this->user->checkLevel($this->getRequiredLevel)) 
          {
            
    // This user has the access level show the page he want
            
    $page =& $this->loadPage($this->getCurrent());
          }
          else
          {
            
    //This user don't have enough access level, load the no level page to give him some warning.
            
    $page = & $this->loadPage($this->getNoLevelPage());
          }
        }
        else
        {
           
    // if the login failed , load the login page again.
           
    $page = & $this->loadPage($this->getLoginPage());
        } 
      }
      else
      {
        
    //No $_SESSION['user']['uid'], no username and password, load the login page.
        
    $page = & $this->loadPage($this->getLoginPage());
      }
      
    $page->show();
     }
     
     function & 
    getUser() 
     {
      Return 
    $this->user;
     }
     function 
    loadPage(&$item
     {
      
    //Initialize the corresponding page class
     
    }
     function 
    getCurrent() 
     {
      
    // Parse the $_GET or $_POST to find the proper class 
     
    }
     function 
    getNoLevelPage() 
     {
      
    // return the proper page configuration for the page of no-accessing-level ;
     
    }
     function 
    getLoginPage() 
     {
      
    // return the proper page configuration for the page of login;
     
    }
     function 
    getRequiredLevel() 
     {
      
    // return the required level
     
    }

    And I need a LoginPage class like following:

    PHP Code:
    include_once('Page.php');
    class 
    loginPage extends Page
    {
     var 
    $form;
     function 
    loginPage (&$application)
     {
      
    $user = & $application->getUser();
      
    $this->form['errors']= $user->getErrors(); 
      
    $this->form['action']='index.php?'.$_SERVER["QUERY_STRING"];
     }
     
     function 
    show() 
     {
      
    $this->showLoginForm();
     }
     
     function 
    showLoginForm() 
     {
      
    //Display the login form ; 
     
    }
      

    What do you think about the class and the workflow?

  7. #7
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ummm.....

    Kind of new to MVC and still learning although your OOP design looks clean ?

    Though I wouldn't rely wholly upon those SESSION variables holding the correct user ? I compare the SESSION against the database on every page load just to be sure...

    ...looking at my script below for example ?

    PHP Code:
    # first somethings from index.php
    #
    # check for logged user
     
    @ include_once('library/users.class.php');
     if(!
    class_exists('userAccess')) {
      
    trigger_error('unable to import required file: library/users.class.php'E_USER_WARNING);
      return 
    false;
     }
     
     
    $user = & new validateUser(& $db);
     if(!
    $user -> isLogged($_SESSION['OffManager']['UserName'], $_SESSION['OffManager']['PassWord'])) {
      
    # invalid so user has to log on again
      
    $user -> logUser();
     }
     
     
    $command = (!empty($_REQUEST['comm']))? $_REQUEST['comm']:'defaults';
     
     @ include_once(
    'library/'strtolower($command) .'.class.php');
     if(!
    class_exists($command)) {
      
    trigger_error('unable to import required file: library/'strtolower($command) .'.class.php'E_USER_WARNING);
      return 
    false;
     }
     
     
    $command = & new $command(& $db);
     
    $command -> process();
    .
    .
    # and now some classes themselves
    #
    class userAccess {
      var 
    $da;
      
      function 
    userAccess(& $da) {
       
    $this -> da =  & $da;
      }
      
      function 
    getId() {
       return 
    $this -> da['userId'];
      }
      
      function 
    getUsername() {
       return 
    $this -> da['userName'];
      }
      
      function 
    getPassword() {
       return 
    $this -> da['userPass'];
      }
     }
     
     
    # views...
     
     
    class logUserView {
      var 
    $view;
      
      
    /** constructor
      */
      
    function logUserView() {
       
    $this -> view = & new transformXml;
      }
      
      function 
    showView() {
       
    $this -> view -> setXmlDir(TEMPLATE_DIR);
       
    $this -> view -> setXslFile('transform.xsl');
       
    $this -> view -> setXmlFile('login.xml');
       
    # display log in FORM
       
    $this -> view -> transformDocument();
      }
     }
     
     class 
    logUserErrorView {
      var 
    $view;
      var 
    $form_handler;
      
      function 
    logUserErrorView() {
       
    $this -> view = & new transformXml;
      }
      
      function 
    showView($form) {
       
    $this -> form_handler $form;
       
    $this -> view -> setXmlDir(TEMPLATE_DIR);
       
    $this -> view -> setXslFile('transform.xsl');
       
    # display log in FORM with valid INPUTs only
       
    $this -> view -> setXmlFile('login-errors.xml');
       
    # void using class method: appendtext2xmlfile(.., ..)
       
    $this -> view -> appendText2XmlFile('<dummy />''');
       
    #
       
    if($this -> form_handler -> getOneFormError(0) == (int) 1) {
        
    # username is valid so put it back to FORM INPUT
        
    $this -> view -> appendText2XmlString('<data-1 />'$this -> form_handler -> getFormUserInput(0));
       }
       if(
    $this -> form_handler -> getOneFormError(1) == (int) 1) {
        
    # password is valid so put it back to FORM INPUT
        
    $this -> view -> appendText2XmlString('<data-2 />'$this -> form_handler -> getFormUserInput(1));
       } 
       
    $this -> view -> transformString();
      }
     }
     
     
    # commands...
     
     
    class validateUser {
      var 
    $db;
      var 
    $dao;
      var 
    $is_valid;
      var 
    $form_handler;
      
      
    /** constructor
      */
      
    function validateUser(& $db) {
       
    # object reference to database access
       
    $this -> db = & $db;
       
    $this -> form_handler = new formValidation;
       
    # by default, user is invalid unless stated otherwise
       
    unset($this -> is_valid);
      }
      
      function 
    isValid() {
       
    # if not empty return true
       
    return !empty($this -> is_valid)? 1:0;
      }
      
      function 
    logUser() { 
       
    # FORM sent yet ?
       
    if(!$this -> form_handler -> checkFormStatus()) {
        
    # so display it
        
    $view = new logUserView;
        
    $view -> showView();
       }
       else {
        
    # prepare to validate INPUTs from user
        
    $this -> form_handler -> initFormVars();
        
    $this -> form_handler -> getFormPostData();
        

        
    $this -> form_handler -> formInputIsAlphaNumeric('');  // username
        
    $this -> form_handler -> formInputIsAlphaNumeric('');  // password
        
        
    if(!$this -> form_handler -> formValidated()) {
         
    # one or more bad INPUTs found
         
    $view = new logUserErrorView;
         
    $view -> showView($this -> form_handler);
        }
        else {
         
    # check against database records
         
    $this -> dao = & new userDao($this -> db);
         
    $result $this -> dao -> searchByUserPassword($this -> form_handler -> getFormUserInput(0), $this -> form_handler -> getFormUserInput(1));
         
    #
         
    if($result -> rowCount()) {
          
    # found required records
          
    $row = & new userAccess($result -> getRow());
          
    # place user details to session variables
          
    $_SESSION['OffManager']['UserId'] = $row -> getId();
          
          
    # perform script to lookup user roles and permissions at this point
          
          
    $_SESSION['OffManager']['UserName'] = $row -> getUsername();
          
    $_SESSION['OffManager']['PassWord'] = $row -> getPassword();
          
          
    # redirect
          
    header('location:index.php');
         }
         else {
          
    # found no match from database records
          
    $view = new logUserErrorView;
          
    $view -> showView($this -> form_handler);
         }
        }
       }
      }
      
      function 
    isLogged($user$pass) {
       
    # create instance of user dao
       
    $this -> dao = & new userDao($this -> db);
       
       
    # check against users from database; decrypt password mode
       
    $result $this -> dao -> searchByAltUserPassword($user$pass);
       
         
    # read in the resultset queried - returns one row exact in this case -
          # following below is not required at this point
         
    $row = & new userAccess($result -> getRow());
       
       if(
    $result -> rowCount()) {
        
    # equates to 1 ?
        
    $this -> is_valid 1;
       }
       
    #
       
    return $this -> isValid();
      }
     }
     
    class 
    userDao extends dao {
      var 
    $db;
      var 
    $dao;
      
      
    /** constructor
      */
      
    function userDao(& $db) {
       
    dao::dao(& $db);   
      }
      
      function & 
    searchAll() {
       
    $sql "SELECT * FROM users ORDER BY userid";
       
       return 
    $this -> retrieve($sql);
      }
      
      function & 
    searchById($id) {
       
    $sql "SELECT * FROM users WHERE userid = '"$id ."'";
       
       return 
    $this -> retrieve($sql);
      }
      
      function & 
    searchByUserPassword($user$pass) {
       
    $sql "SELECT * FROM users WHERE username = '"$user ."' AND userpass = PASSWORD('"$pass ."')";
       
       return 
    $this -> retrieve($sql);
      }
      
      function & 
    searchByAltUserPassword($user$pass) {
       
    $sql "SELECT * FROM users WHERE username = '"$user ."' AND userpass = '"$pass ."'";
       
       return 
    $this -> retrieve($sql);
      }
      
      function & 
    totalRows() {
       
    $sql "SELECT COUNT(*) FROM users";
       
       return 
    $this -> retrieve($sql);
      }
     } 
    This is how I do things at the moment; you create a new user which I don't as the 'new user' doesn't exist;

    In which case they get redirected to log in

    See what you think and get back to me ?


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •