User Levels in SQL - php

Okay, so I have created a user table inside of my database to hold all the users data
CREATE TABLE `user` (
`id` INT NOT NULL auto_increment,
`username` VARCHAR(50) NOT NULL default '',
`nicename` VARCHAR(255) NOT NULL default '',
`email` VARCHAR(255) NOT NULL default '',
`password` VARCHAR(255) NOT NULL default '',
`permissions` INT NOT NULL default '1',
UNIQUE KEY `user_n` (`username`),
UNIQUE KEY `user_e` (`email`),
PRIMARY KEY (`id`)
);
I want the permissions field to dictate what users can and cannot see. IE. The permissions for the ACP would require a permissions level of 3 whereas 1 is a registered user and 0 is a guest visiting the site. How could I get a page to block itself depending upon a users permission level? Thanks in advance.
Using MySQL/PHP

have the user login , fetch his permissions from table and depending upon the permission redirect him/her to appropriate page e.g.
 
$dbh = new PDO("mysql:dbname=dbname;host=hostname", "username", "password" );
$result = $dbh->prepare("select check_user_exists(?) as retval");
$result->bindParam(1, $value, PDO::PARAM_STR, 2);
$result->setFetchMode(PDO::FETCH_CLASS, 'stdClass');
$result->execute();
switch($result) {
case 1 : $header('Location:x.php');
case 2 : $header('Location:y.php');
case 3 : $header('Location:z.php');
default 'no suitable page found');
break;
}

If you don't want to use MySQL user-account-management You can use switch case
$permissions = $_GET["permissions"];//Or Post from html page
switch ($permissions)
{
case 1:
//Level 1 code
break;
case 2:
//level 2 code
break;
case 3:
//level 3 code
break;
default:
//default code
}

Related

MYSQL delete statement deletes too many rows

I have a table for users in my MYSQL db like so:
CREATE TABLE `myDatabase`.`user` (
`id` INT NOT NULL AUTO_INCREMENT ,
`login` VARCHAR(250) NOT NULL ,
`uid` VARCHAR(250) NOT NULL ,
`email` VARCHAR(250) NOT NULL ,
`user_type` VARCHAR(250) NOT NULL ,
PRIMARY KEY (`id`)) ENGINE = InnoDB;
uid is provided by firebase when a user logs in (strings such as 3LmgcBeCUNW1lfMKCQcoI8Xkxai1
or DrFblVatVdacokhcQCuwb8DK13q1.
My project has a delete user option that calls the query:
public function deleteProfile($uid) {
$memberDelete = $this->_db->prepare("DELETE FROM user WHERE uid = :uid");
$memberDelete->bindParam(':uid',$uid,PDO::PARAM_INT);
$resp = $memberDelete->execute();
if(!$resp) {
throw new PDOException('member couldn't be removed');
}
$memberDelete->closeCursor();
return "member successfully removed";
}
When I do this, it deletes way too many users. I tried deleting based on email instead of UID and it deleted all of the users.
Here:
$memberDelete->bindParam(':uid', $uid, PDO::PARAM_INT);
You are binding your param as an integer, while obviously it's a string. This generates a chain of implicit conversions that ends up deleting more rows that you intend.
Instead, you want:
$memberDelete->bindParam(':uid', $uid, PDO::PARAM_STR);

PHP User Group Levels

I am working on a small cms project my database fields are as follows
Levels Table
CREATE TABLE IF NOT EXISTS `security_level` (
`user_level` int(10) NOT NULL,
`level_title` varchar(30) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
VALUES
1, User
2, Moderator
3, Administrator
User table
CREATE TABLE IF NOT EXISTS `users` (
`uid` int(11) unsigned NOT NULL,
`username` varchar(25) NOT NULL,
`user_email` varchar(255) NOT NULL,
`password` text,
`security_level` int(11) NOT NULL DEFAULT '1',
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
What I am trying to do is create a function that I can include on my member area pages, so if there level_id is 1 but the page requires level_id 2 it will simply redirect them, by default the level is set to 1...
I am using this to make sure they are logged in or redirect
<?php
if (logged_in()) {} else {
redirect("login.php");
}
?>
but I would like to restrict access to certain pages based on level_id
A simple way to do it would be something like this. The function below returns true or false and takes 2 arguments: $page_level and $user_level:
function user_has_permissions($user_level, $page_level)
{
// a user can access page less than or equal to their level
if ((int)$user_level >= (int)$page_level)
{
return true;
}
else
{
return false;
}
}
I am calling this function user_has_permissions() and not logged_in() because the user might be logged in but they may not have permissions to a page that belongs to a different level.
Then on the page, in order to user this function.
$page_level = "2"; // define page level on each page
// get the user level from sessions
if (!user_has_permissions($_SESSION['user_level'], $page_level))
{
header ("Location: login.php");
exit;
}
// code after successful permissions checking goes here
This is a simple implementation but you are probably looking for something like Access Control Lists (ACL).

Simple PHP/MySQL ACL System

I have a simple ACL system in PHP and MYSQL started. I need help finishing it though...
I have 2 Database tables shown below...
user_link_permissions : Holds a record for every user, on every entity/link that permissions apply to...
--
-- Table structure for table `user_link_permissions`
--
CREATE TABLE IF NOT EXISTS `user_link_permissions` (
`id` int(100) NOT NULL AUTO_INCREMENT,
`user_id` int(30) NOT NULL,
`link_id` int(30) NOT NULL,
`permission` int(2) NOT NULL DEFAULT '0',
KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2055 ;
intranet_links : Is basically the entity that the permission gives or revokes user access to
--
-- Table structure for table `intranet_links`
--
CREATE TABLE IF NOT EXISTS `intranet_links` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) DEFAULT NULL,
`description` text NOT NULL,
`url` varchar(255) DEFAULT NULL,
`notes` text,
`user_login` varchar(255) DEFAULT NULL,
`user_pw` varchar(255) DEFAULT NULL,
`active` int(2) NOT NULL DEFAULT '1',
`sort_order` int(11) DEFAULT NULL,
`parent` int(10) NOT NULL DEFAULT '1',
`local_route` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`),
UNIQUE KEY `local_route` (`local_route`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=34 ;
To save these permissions settings I have a matrix style grid like this below where each checkbox is a record in the user_link_permissions table...
I need help creating a simple ACL function in PHP which can check if a user has permission or not to view a link/entity based on the database results.
On page load I am thinking I can query the user_link_permissions DB table for all records with a matching user ID of the logged in user and store them to a session array variable.
A function could then use that array to check for a link/entity permission using that array value on the entity key.
I just can't visualize how it might look at the moment in PHP.
Any help please?
function aclCanAccess($user_id, $entity_id){
}
$entity_id = 123;
if(aclCanAccess(1, $entity_id){
// yes user can see this item
}else{
// NO user permission denied
}
I will leave writing the code to you for fun.
Assume you are storing all the previously queried permissions in a variable called $_SESSION['acl']
Your ACL function should:
check the session if you already queried that entity
if it is not set, read it from the db
in short
function..... {
if(!isset($_SESSION['acl'][$entity_id])) {
$_SESSION['acl'][$entity_id] = query here to return to you if he has access or not
}
return $_SESSION['acl'][$entity_id];
}
You can also read the entire array when you log in the user. That might also be appropriate. In that case you should be able to just
return $_SESSION['acl'][$entity_id];
But I would then try and catch an exception in case it is not set.

Specifying which data to display based on ID using Yii

I have a web application that contains a link towards the "album" section of my application. My problem right now is that it's showing the albums created for ALL users (and this goes the same for all members within the application). I want that whenever a user who is logged in selects the "phots" link, he/she is directed into the album page where they can only see the pictures that THEY uploaded.
To begin, this is the schema wherein the photos are being uploaded into.:
CREATE TABLE IF NOT EXISTS `content` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`node_type_id` int(11) DEFAULT NULL,
`party_id` int(11) DEFAULT NULL,
`category` text,
`title` text,
`content` text CHARACTER SET utf8 COLLATE utf8_unicode_ci,
`date_created` datetime DEFAULT NULL,
`date_modified` datetime DEFAULT NULL,
`start_date` datetime DEFAULT NULL,
`end_date` datetime DEFAULT NULL,
`status` int(11) DEFAULT NULL,
`content_id` int(11) NOT NULL,
`country` text NOT NULL,
`view_count` int(11) NOT NULL,
`attribute1` varchar(200) DEFAULT NULL,
`attribute2` varchar(50) DEFAULT NULL,
`liked` text,
`approved` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;
Then this is where the album is being viewed:
<div class="photodiv">
<?php
foreach ($albumArr as $album)
{
Yii::app()->user->id;
$image = Image::model()->findByAttributes(array('content_id'=>$album->id, 'attribute1'=>'1'));
$photos = Image::model()->findAllByAttributes(array('content_id'=>$album->id));
echo '<div class="albumdiv">';
echo '<div class="picdiv">';
if (!empty($image))
{
echo '<img src="'.Yii::app()->baseUrl.'/images/albums/'.$album->content.'/'.$image->id.$image->content.'" height="100px" width="100px" />';
}
echo '</div>';
echo '<br/>';
echo '<center><h4>'.$album->content.'</h4></center>';
echo count($photos) == 1 ? '<center><h5>'.count($photos).' photo</h5></center>' : '<center><h5>'.count($photos).' photos</h5></center>';
echo '</div>';
}
?>
</div>
If you are wondering how this was generated, the controller contained the following:
public function actionIndex()
{
$usertag = isset($_GET['usertag']) ? addslashes($_GET['usertag']) : FALSE;
$users = new CActiveDataProvider('SystemUser', array(
'id' => '',
'criteria' => array(
'alias'=>'u',
'join'=>'JOIN persons p ON u.party_id = p.party_id JOIN lookup_codes lc ON p.country = lc.id',
'condition' => $usertag ? 'status != "Approved" AND company_name LIKE "%'.$usertag.'%" OR status = "'.$usertag.'"' : 'status != "Approved"',
//'order'=> 'date_created DESC'
'order'=> 'status'
),
'pagination' => array(
'pageSize' => 100
)
));
$data = array(
'dataProvider' => $users
);
$this->render('index', $data);
}
And index rendered the _view which I showed 2 scripts ago.
My problem is I'm not quite sure how to display only the specific creator of the album. In this case, 'party_id' is the ID that identifies who the creator is.
Ok If i understood you correctly then I am making some assumptions prior to answer your question.
1. Normally user table is used to login a user and store credentials like username,password, rememberme, and other attributes, but in your case i assume you are using person table for logging in a user.
2. In userIdentity.php you are using person model for verification purpose.
Then you need to do like this.
First create a function in your UserIdentity.php file
public function getId()
{
return $this->_id;
}
it will return the id of the person.
Now in your view file you can use this code to get id of logged in user
$id=Yii::app()->user->getId()
Now you can use it in your criteria like
$image = Image::model()->findByAttributes(array('content_id'=>$album->id,'party_id'=>$id, 'attribute1'=>'1'));
$photos = Image::model()->findAllByAttributes(array('content_id'=>$album->id,'party_id'=>$id,));
This will give you the results on for the logged in user.
Edit:
For your next question
If you are able to display a link and pass some user id in that link then you can do like this.
1. Where you are showing the link for a user pass this link id of that user like
CHtml::link('ViewAlbum',array('controller/userAlbum',array('id'=>userId)))
2. Create action for specific user
public function actionUserAlbum($id)
{
album=Album::model()->findAllByAttributes(array(
'id_of_creator_of_album'=>$id;
));
$this->render('someView',array('id'=>$id))
}
then use us this id in your view to get photos related to that album

How to delete user in oo php api (using postman testing tool)

I am working on an basic crud API. So far i have a working get function, but want to delete the current users. MY tables are as follows.
CREATE TABLE IF NOT EXISTS `users`
(
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_fullname` varchar(25) NOT NULL,
`user_email` varchar(50) NOT NULL,
`user_password` varchar(50) NOT NULL,
`user_status` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
This is the delete code, how can i delete a user by specific id?
} elseif ($this->get_request_method() == "DELETE"){
$result = $this->db->query("DELETE * From users");
$result->close();
// Send the response to the response() function (lives in the parent class) the 200 is the HTTP status code that's returned
$this->response(json_encode("Deleted", JSON_PRETTY_PRINT), 200);
} else {
/*
* THE METHOD IS NOT ALLOWED
*/
$this->response(json_encode("Method Not Allowed"), 405);
}
You could send the user_id in the URL string then delete that specific record
http://url.com.script.php?user_id=123
// get the user ID and cast to an integer
$user_id = (int) $_GET['user_id'];
// run the query
$result = $this->db->query("DELETE FROM users WHERE user_id = $user_id");
of course, you'd want to sanitize the $user_id against SQL injection in your query, just in case...

Categories