从类获取变量以检查权限设置的问题

时间:2019-03-25 17:12:48

标签: php pdo permissions

我正在尝试执行if语句,以为不同级别的权限用户填充正确的导航菜单。

我有一个名为“用户”的类,该类具有以下名为“ hasPermission”的功能:

public function hasPermission($key) {
    $group = $this->_db->get('groups', array('id', '=', $this->data()->group));

    if($group->count()) {
        $permissions = json_decode($group->first()->permissions, true);

        if($permissions[$key] == true) {
            return true;
        }
    }
    return false;
}

哪个可以处理数据库中的以下组:

enter image description here

然后在另一个文件中,我尝试使用$permission获取当前用户的登录权限(我认为错误在这里),然后使用if语句填充正确的文件。

$permission = $user->hasPermission($group);

if($permission == 'User') {
    include 'nav/userNav.php';
} else if ($permission == 'Admin') {
    include 'nav/adminNav.php';
}

有人看到我在做什么错吗?

编辑:

用户类的完整代码:

<?php
class User {
    private $_db,
            $_data,
            $_sessionName,
            $_cookieName,
            $_isLoggedIn;

    public function __construct($user = null) {
        $this->_db = DB::getInstance();

        $this->_sessionName = Config::get('session/session_name');
        $this->_cookieName = Config::get('remember/cookie_name');

        if(!$user) {
            if(Session::exists($this->_sessionName)) {
                $user = Session::get($this->_sessionName);

                if($this->find($user)) {
                    $this->_isLoggedIn = true;
                } else {
                    // process Logout
                }
            }
        } else {
            $this->find($user);
        }
    }

    public function update($fields = array(), $id = null) {

        if(!$id && $this->isLoggedIn()) {
            $id = $this->data()->id;
        }

        if(!$this->_db->update('users', $id, $fields)) {
            throw new Exception('There was a problem updating!');
        }
    }

    public function create($fields = array()) {


        if(!$this->_db->insert('users', $fields)) {
            throw new Exception('There was a problem creating an account:' .  $this->_db->errorMessage());

        }
    $this->lastId = $this->_db->lastInsertId();
    }

    public function find($user = null) {
        if($user) {
            $field = (is_numeric($user)) ? 'id' : 'username';
            $data = $this->_db->get('users', array($field, '=', $user));

            if($data->count()) {
                $this->_data = $data->first();
                return true;
            }
        }
        return false;
    }

    public function login($username = null, $password = null, $remember = false) {

        if(!$username && !$password && $this->exists()) {
            Session::put($this->_sessionName, $this->data()->id);
        } else {
            $user = $this->find($username);

            if($user) {
                if($this->data()->password === Hash::make($password, $this->data()->salt)) {
                //if(Auth::check($this->data()->password, $password)){
                    Session::put($this->_sessionName, $this->data()->id);

                    if($remember) {
                        $hash = Hash::unique();
                        $hashCheck = $this->_db->get('users_session', array('user_id', '=', $this->data()->id));

                        if(!$hashCheck->count()) {
                            $this->_db->insert('users_session', array(
                                'user_id' => $this->data()->id,
                                'hash' => $hash
                            ));
                        } else {
                            $hash = $hashCheck->first()->hash;
                        }

                        Cookie::put($this->_cookieName, $hash, Config::get('remember/cookie_expiry'));
                    }
                    return true;
                }
            }

        }
        return false;
    }

    public function hasPermission($key) {
        $group = $this->_db->get('groups', array('id', '=', $this->data()->group));

        if($group->count()) {
            $permissions = json_decode($group->first()->permissions, true);

            if($permissions[$key] == true) {
                return true;
            }
        }
        return false;
    }

    public function exists() {
        return (!empty($this->_data)) ? true : false;
    }

    public function logout() {

        $this->_db->delete('users_session', array('user_id', '=', $this->data()->id));

        Session::delete($this->_sessionName);
        Cookie::delete($this->_cookieName);
    }

    public function data() {
        return $this->_data;
    }
    public function isLoggedIn() {
        return $this->_isLoggedIn;
    }
}
?>

编辑#2-尝试为此创建一个新功能:

public function getGroup($groupkey) {
    $group_name = $this->_db->get('groups', array('name'));
}

然后在另一个我要称呼它的文件中:

$permission = $user->getGroup($group_name);

if($permission == 'User') {
    include 'nav/userNav.php';
} else if ($permission == 'Admin') {
    include 'nav/adminNav.php';
}

编辑#3

使用以下代码:

 public function getGroup($groupkey) {
    $group_name = $this->_db->get('groups', array('name'));
    return $group_name;
}

我得到这个错误:

Fatal error: Uncaught ArgumentCountError: Too few arguments to function User::getGroup(), 0 passed in /home/house/public_html/admin/index.php on line 322 and exactly 1 expected in /home/house/public_html/classes/User.php:116 Stack trace: #0 /home/house/public_html/admin/index.php(322): User->getGroup() #1 {main} thrown in

DB类中的动作函数。

public function action($action, $table, $where = array()){
    if(count($where) === 3){
        $operators = array('=', '>', '<', '>=', '<=');

        $field      = $where[0];
        $operator   = $where[1];
        $value      = $where[2];

        if(in_array($operator, $operators)) {
            $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
            $date = new DateTime();
            file_put_contents('debug_log', "\n[{$date->format('Y-m-d H:i:s')}] $sql", FILE_APPEND);

            $results = $this->query($sql, array($value));
                file_put_contents('debug_log1', "\n[{$date->format('Y-m-d H:i:s')}] $sql" . print_r($results, 1), FILE_APPEND);
            return $this;

        }
    }
    return false;
}

编辑-完整数据库类

<?php
class DB {
    private static $_instance = null;
    private $_pdo,
            $_query, 
            $_error = false,
            $_results,
            $_count = 0,
            $_errmsg = "";

    private function __construct(){
        try {
            $this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'), Config::get('mysql/username'), Config::get('mysql/password'));
            /*$host = config::get('mysql/host');
            $database = config::get('mysql/db');
            $username = config::get('mysql/user');
            $password = config::get('mysql/password');

            $dbh = new PDO('mysql:host='.$host.';dbname='.$database.', $username, $password);*/
            } catch(PDOException $e) {
        die($e->getMEssage());
        }   
    }
    //**********LastID

    public function lastInsertId () { 
        return $this->_pdo->lastInsertId(); 
    } 
    public static function getInstance() {
        if(!isset(self::$_instance)) {
            self::$_instance = new DB();
        }
        return self::$_instance;
    }
    public function query($sql, $params = array()){
"DEBUG DB::query called<br>SQL: $sql<br><br>PARAMS: " . implode("<br>", $params) . "<hr>\n";        
        $this->_error = false;
        if($this->_query = $this->_pdo->prepare($sql)) {
"DEBUG: prepared statement created ok<hr>\n";           
            $x = 1;
            if(count($params)){
                foreach($params as $param){
                    $this->_query->bindValue($x, $param);
                    $x++;
                }
            }
            if($this->_query->execute()){
                $this->_results = $this->_query->fetchALL(PDO::FETCH_OBJ);
                $this->_count = $this->_query->rowCount();
"DEBUG: query succeeded, rowcount was: " . $this->_count . "<hr>\n";                
            } else {
    "DEBUG: query failed to execute, reason:<br>" . implode( "<br>", $this->_query->errorInfo() ) . "<hr>\n";   
                $this->_error = true;
            }
        } else {
"DEBUG: Failed to create prepared statement<hr>\n";
        }   
        return $this;
    }
    public function action($action, $table, $where = array()){
        if(count($where) === 3){
            $operators = array('=', '>', '<', '>=', '<=');

            $field      = $where[0];
            $operator   = $where[1];
            $value      = $where[2];

            if(in_array($operator, $operators)) {
                $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
                $date = new DateTime();
                file_put_contents('debug_log', "\n[{$date->format('Y-m-d H:i:s')}] $sql", FILE_APPEND);

                $results = $this->query($sql, array($value));
                    file_put_contents('debug_log1', "\n[{$date->format('Y-m-d H:i:s')}] $sql" . print_r($results, 1), FILE_APPEND);
                return $this;

            }
        }
        return false;
    }
    public function get($table, $where){
        return $this->action('SELECT *', $table, $where);
    }
    public function delete($table, $where){
        return $this->action('DELETE', $table, $where);
    }
    public function insert($table, $fields = array()) {
        $keys = array_keys($fields);
        $values = '';
        $x = 1;

        foreach($fields as $field) {
            $values .= '?';
            if($x < count($fields)) {
                $values .= ', ';
            }
            $x++;
        }

        $sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) Values ({$values})";

        return ! $this-> query($sql, $fields)->error(); 
    }
    public function update($table, $id, $fields) {
        $set = '';
        $x = 1;

        foreach($fields as $name => $value) {
            $set .= "{$name} = ?";
            if($x < count($fields)) {
                $set .= ', ';
            }
            $x++;
        }

        $sql = "UPDATE {$table} SET {$set} WHERE id = {$id}";

        return ! $this-> query($sql, $fields)->error();
    }
    public function results() {
        return $this->_results;
    }
    public function first() {
        return $this->results()[0];
    }
    public function error() {
        return $this->_error;
    }
    public function errorMessage() { 
        return $this->_errmsg; 
    }
    public function count(){
        return $this->_count;
    }
}
?>

2 个答案:

答案 0 :(得分:1)

根据更新的信息,我可以看到您正在使用PDO并执行fetchALL并以stdClass对象数组(FETCH_OBJ)的形式返回结果。不确定为什么要存储permission,更不用说作为JSON对象了,但是幸运的是,在这种情况下,我们不需要该列。我们可以简单地基于name查找id

重要的是要意识到$this->_db->get(...返回数据库类(或false)的实例,因此您应该适当地命名变量$db。如果您遇到任何问题,请告诉我,我会尽力帮助您。

<?php 
/**
 * Returns the role name of the currently logged in user. If no role can be
 * determined, an empty string will be returned.
 * @return string
 */
public function getGroup() 
{
    $role = '';
    // I really can't tell what `$this->data()->group` is but 
    // I'm making the assumption that it is the logged in user's role ID. 
    $db = $this->_db->get('groups', array('id', '=', $this->data()->group));

    if($db->count() > 0) { 
        // `first()` returns the first element of the results as a stdClass object.
        // https://www.geeksforgeeks.org/what-is-stdclass-in-php/
        $role = $db->first()->name;
    }   

    return $role;  
}

答案 1 :(得分:0)

...
public function hasPermission($key) {
    $group = $this->_db->get('groups', array('id', '=', $this->data()->group));

    if($group->count()) {
        $permissions = json_decode($group->first()->permissions, true);

        if($permissions[$key] == true) {
            return $key;//change true here to the role
        }
    }
    return false;
}
...