2 Replies - 240 Views - Last Post: 26 March 2019 - 09:04 AM Rate Topic: -----

#1 pfar54   User is offline

  • D.I.C Addict

Reputation: 0
  • View blog
  • Posts: 519
  • Joined: 30-April 15

Attempt in trying to retrieve information using a framework

Posted 25 March 2019 - 12:03 PM

Hi everyone.

I am attempting to modify a framework that I have been using for sometime. The framework is essentially for registration/login, but there are permission settings and other things.

I am trying to add a public function to find the user's permission roles (groups) and then check to see what they are in order to display the correct navigation menu.

Currently, I have a public function in my user class called "hasPermission" which checks if a specified group id matches the specific group name. Instead of messing with this, I created a new public function called "getGroup".

I cannot figure out how to retrieve the user's group name and return it to the file I am trying to check this in.

Here is the getGroup function I created. I also added the DB class and entire User Class (this function is in the user class) so you understand this framework better.

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


Does anyone see what I am doing wrong?


DB class
application/x-httpd-php DB.php ( C++ source, ASCII text )
<?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;
	}
}
?>


User Class
<?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));
			$date = new DateTime();
            file_put_contents('debug_log', "\n[{$date->format('Y-m-d H:i:s')}] " . print_r($data, 1));
			if($data->count()) {
				$this->_data = $data->first();
				return true;
			}
		}
		return false;
	}
	
	public function login($username = null, $password = null, $remember = false) {
        $date = new DateTime();
	    file_put_contents('debug_log_U', "\n[{$date->format('Y-m-d H:i:s')}] Sent pass: " . $password);
		if(!$username && !$password && $this->exists()) {
			Session::put($this->_sessionName, $this->data()->id);
		} else {
			$user = $this->find($username);

            file_put_contents('debug_log_U', "\n[{$date->format('Y-m-d H:i:s')}] Stored pass:" . print_r($this->_data->password, 1) . "\nSent pass: " . $password);
			if($user) {
				if(password_verify($password, $this->_data->password)) {
				//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 getGroup() {
		$group_name = $this->_db->get('groups', array('name'));
		return $group_name;
	}

	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;
	}
}


How I am trying to call for the function in the other file:

$permission = $user->getGroup();

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


Is This A Good Question/Topic? 0
  • +

Replies To: Attempt in trying to retrieve information using a framework

#2 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2290
  • View blog
  • Posts: 6,981
  • Joined: 15-January 14

Re: Attempt in trying to retrieve information using a framework

Posted 25 March 2019 - 02:36 PM

In your action method, the if statement on line 62 is false.
Was This Post Helpful? 0
  • +
  • -

#3 pfar54   User is offline

  • D.I.C Addict

Reputation: 0
  • View blog
  • Posts: 519
  • Joined: 30-April 15

Re: Attempt in trying to retrieve information using a framework

Posted 26 March 2019 - 09:04 AM

Thanks. I modified the function to the following and it now works.

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

		if($db->count() > 0) {
			$role = $db->first()->name;
		}
		return $role;
	}

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1