OOP permission checking best practice question

Discussion in 'PHP' started by stats, Jun 2, 2011.

  1. #1
    suppose i have a "user" class which has "add_user" method.
    suppose i have 3 kind of users: Admin, Manager, User

    only Admin and Manager can create new users with "add_user" method.

    question: which implementation would be a best practice ?

    class user {
    	
    	function add_user(array $userdetails, user $current_user) {
    		if ($current_user != "Admin" && $current_user != "Manager") {
    			die("You don't have permission");
    		} else {
    			// add the user
    			return $new_userid;
    		}
    	}	
    }
    
    
    
    // calling code
    $new_user = $user->add_user($newuser_details, $current_user);
    
    PHP:
    OR

    class user {
    	
    	function add_user(array $userdetails) {
    	// add the user
    	return $new_userid;
    	}
    }
    
    // calling code
    if ($current_user != "Admin" && $current_user != "Manager") {
    	die("You don't have permission");
    } else {
    	$new_user = $user->add_user($newuser_details);
    }
    PHP:
    the downside of the first one is that "what if tomorrow i will need to add a user from within the system, i.e. the process won't get initiated by any actual user" (and it is really possible in my case). I could, in that case, create an imaginary user object and complete my task, but that's gonna be another headache.

    the downside of the second one is that my method is not secure by itself, and what if after a month i use it somewhere and forget to do the permission-check within the calling code.. i'll end up with security hole.

    Please share your thoughts or point me to another implementation which i didn't think about
     
    stats, Jun 2, 2011 IP