PHP - Permissions Done Properly!
So here is a concept of a permission system that I haven't really seen any where else. Now usually conventional permissions are usually stored in columns whilst the record specifies a bit which is then used to determine if the record has access to that permission.
Below is my concept of how permissions should be done, I'm looking for someone who can help me create the system in a way which would be easily implementable by other applications such as MyBB. In my case I have multiple game servers, and most of my players have accounts created on my forums which are powered by MyBB, I'm currently in the process of integrating their MyBB accounts across all my related game servers, but one thing I've noticed is that I have multiple permission systems created for all of my servers so right now I'm also trying to integrate all of them into one system so please try and understand that I designed this system in a way that could be used by multiple applications.
Any constructive criticism is accepted.
So the idea is that you have 1 table, I'll just list it here to make it easier to follow: - uniperms_nodes Now the uniperms_nodes table will contain the following columns: - key (Int, Not Null, Primary Key, Auto Increment) - type (Enum('USER', 'GROUP'), Not Null) - id (Int, Not Null) - permission (Varchar(255), Not Null) - description (Text)Now here is how it works, a record is inserted into the uniperms_nodes table containing the necessary information. Here is an example: INSERT INTO `uniperms_nodes` (`type`, `id`, `permission`, `description`) VALUES ('GROUP', '1', 'my.test.node', 'A simple permission'); With this information inserted, I can simply use the following query in order to get all of the permissions related to the GROUP with the ID of 1. SELECT `permission` FROM `uniperms_nodes` WHERE type='GROUP' AND id=1;With this array of permission nodes I can simply just check if the array has 'my.test.node', if the array contains 'my.test.node' then that means that the group I queried has access to that permission. Now the reason I have the types USER and GROUP is because maybe you would like to give permissions to individual users, but maybe you wouldn't necessarily want to create a new group. I'm currently looking for someone to help me create a lovely interface for this system, so that it's easier for the user to modify a group/user's permissions. If you're interested feel free to message me here on the forums or via email. kieron.wiltshire@outlook.com Edited by KieronWiltshire, 19 November 2014 - 11:15 AM. Similar TutorialsWasn't sure exactly where to post this at but here is my issue. I have a directory setup where multiple developers work on a project and they all have "group" access to the folder and files(read, write, execute) so the permissions on the php files need to be 775 so they can upload and overwrite the files via FTP. The problem is that PHP files will not work with permissions of 775 and throw a internal server error unless I change it to something lower. Is there a way to overcome this for these files? Hey guys i have a script that i made with multiple permissions.. i need to add in the pages restitutions for diffrent levels.. so i got the level $query = "SELECT * FROM users WHERE `username`='$username_from_cookie'"; $numresults=mysql_query($query); $numrows=mysql_num_rows($numresults); // get results $result = mysql_query($query) or die("Couldn't execute query"); // now you can display the results returned while ($row10= mysql_fetch_array($result)) { $permissions= $row10["permissions"]; echo '$permissions'; } Now to restick im ok with like to but more then that i get confused.. this shows navigation on levels of permissions.. if ($row10['permissions'] == 2) { print "<a href=\"U.php\"><img src=\"./Icons/Users.png\" title=\"Prof\" /></a>"; } else { print "<img src=\"./Icons/Users_o.png\"/>"; } 2 levels if ($row10['permissions'] == 5) { print "<a href=\"Prof_1.php\"><img src=\"./Icons/sec.png\" title=\"Enseignant(e)\"/></a>"; } elseif ($row10['permissions'] == 2) { print "<a href=\"Prof_1.php\"><img src=\"./Icons/sec.png\" title=\"Enseignant(e)\"/></a>"; } else { print "<img src=\"./Icons/sec_o.png\" title=\"Enseignant(e)\"/>"; } ok so instead of have 10 lines of codes can i $row10['permissions'] == 5&2&3 ??? and can i do if not permissions ==5 redirect to loggin.. thanks Hello needed for permissions well dont know even how to ask . im building simple betting and im want to add message if user has submitted bet but problem im got is once user submit all other bets comes with message how to make it work separate for every single row Here is my code Code: [Select] $statom = $TSUE['TSUE_Database']->query("SELECT count(*), b.betid, a.betid, a.memberid, a.chosen_team FROM rasta_betters a, rasta_betting b WHERE memberid = ".$TSUE['TSUE_Member']->info["memberid"]." AND b.betid = a.betid "); $arr = mysqli_fetch_array($statom); if ($arr[0] > 0) { $forma = '<div class="success">You have placed bet here</div>'; } else{ $team1 = $row['team1']; $team2 = $row['team2']; $pisk = '<input type="checkbox" name="komanda" value="'.$team1.'" />'; $pisk2 = '<input type="checkbox" name="komanda" value="'.$team2.'" />'; $komanda = ''; $komanda = $team1.$pisk; $komanda2 = ''; $komanda2 = $team2.$pisk2; $forma = 'This bet end on:'. date('Y-m-d H:i:s',$row['finish']).''; eval("\$betting_form = \"".$TSUE['TSUE_Template']->LoadTemplate('betting_form')."\";"); $forma .= $betting_form; } $TSUE['TSUE_Member']->info["memberid"] that is actual user id gets id auto Hi I've got a file upload script i've written and I have set the folder to 777 to allow uploads With the permission set to 777 does this open me up to potential uploads from 3rd parties? (ie: viruses etc)? So I thought what I would do is 1: Set folder to 777 to allow uploads 2: Upload file 3: Set folder to 755 to disable uploads Would this be the best method to do it? Or is that a waste of time and am I safe just leaving it as 777 Thanks I'm doing a flash app where i save webcam images to a folder on the server. I'm able to make this work when running of xampp on my machine, I create the required folder structure and I'm able to read from that folder and display the images, however once i move the stuff onto a live server, it fails to create the folders and it seems to be a permission problem. Is it server specific? i've tried chmod etc but I don't think i'm doing it right. any help, pointers for a non php developer would be most helpful. here's my code snippet <?php //This project is done by vamapaull: http://blog.vamapaull.com/ //The php code is done with some help from Mihai Bojin: http://www.mihaibojin.com/ $uid = $_GET[uid]; $structure = './images/' . date("Ymd") .'/' . $uid. '/'; // To create the nested structure, the $recursive parameter // to mkdir() must be specified. if(is_dir($structure)) { echo "Exists!"; } else { echo "Doesn't exist" ; if (!mkdir($structure,'0777', true) ) { die('Failed to create folders...'); } } if(isset($GLOBALS["HTTP_RAW_POST_DATA"])){ $jpg = $GLOBALS["HTTP_RAW_POST_DATA"]; $img = $_GET["img"]; $filename = 'images/' . date("Ymd"). "/" .$uid. "/img_". mktime(). ".jpg"; file_put_contents($filename, $jpg); } else{ echo "Encoded JPEG information not received."; } ?> Dear Coder Bro, I made a simple php script which copy some files to the server directory through a php loop. It means it will copy some 1000+ files via loop & store into a directory. The script worked fine before some 2 - 3days, Suddenly i saw that script is executing but no files copied to the server's directory. I checked the directory permission & it was 755. I changed the permission to 777 and run the script once again and it worked success... But the problem is the directory permission automatically changes to the old 755. I don't know how it happen. I need to change the directory permission to 777 when i begin to run the script. My Question is. 1.) Why did the directory permission automatically changes to 755. ? 2.) How to solve this problem to avoid the every time directory permission changing behavior ? I Hope expert coder guys will respond soon...! Hi, I've written the function below to check the permissions of a user based on the table structure of....
staff
staff_roles_id (foreign)
staff_roles
id
roleName
staff_roles_permissions
staff_roles_id (foreign)
staff_permissions_id (foreign)
staff_permissions
id
permissionName
function checkPerm($permission){ global $db; $user = $_SESSION['userid']; if(!$stmt = $db->prepare("SELECT * FROM staff LEFT JOIN staff_roles ON staff.staff_roles_id = staff_roles.id LEFT JOIN staff_role_permissions ON staff_roles.id = staff_role_permissions.staff_roles_id LEFT JOIN staff_permissions ON staff_role_permissions.staff_permissions_id = staff_permissions.id WHERE staff.id = ? AND staff_permissions.permissionsName = ?")){ echo $db->error; exit; } $stmt->bind_param('is',$user,$permission); if(!$stmt->execute()){ echo $db->error(); exit; }; $stmt->store_result(); $authenticate = $stmt->num_rows; $stmt->close(); return $authenticate; }So for example if I then had the permission of 'adminAccess', I would use the code below to check access, referring to the 'staff_permissions' table if(checkPerm('adminAccess')){ echo 'you are authorised'; exit; } else { echo 'you are not authorised'; exit; }This works, but Is this the correct way to be going about access for group based permissions or am I missing a glaring security vulnerability here? If this is suitable then I intend to turn it into a class, and add checkRole() which would just check the user against the 'staff_roles' table. This would then be called by $security->checkRole('example'); $security->checkPermission('example'). Would that be a good idea? Any advice would be great - I'm not great with functions (and just starting to learn classes!) Cheers. I am developing a system that with have 4 different levels of permissions. My question is this. From a structure standpoint, some systems will have the administrators area in one file and the users admin area in another file. Others will have a level of permission with all the different levels of administrative tasks, menus, etc, coming from the database. Is one of these better than the other or does it matter. From a coding standpoint it would be much easier to just have permissions and allow access to user menus and admin pages accordingly. Thanks in advance. Hey, practicing my PHP for the first time, starting with a simple upload script with Xampp. Script: Code: [Select] $target = '/Uploads'; $uploadedfile = $target . basename($_FILES['file']['name']); if(move_uploaded_file($_FILES['file']['tmp_name'], $target)){ echo "The file ". basename($_FILES['file']['name'])." has been uploaded."; } else { echo 'Failed'; } error_reporting(E_ALL); It echos out a successful, but the file is nowhere? Uploads is inside htdocs. Checked my php.ini file: file_uploads = On upload_tmp_dir = "C:\xampp\tmp" upload_max_filesize = 128M Just wondering if there are any permission i may have missed? Hi there, I am working on a little CMS site and I have run into a bit of a problem. When the user comes to publish the changes they have made I need to push the new files onto their server. I don't know whether they are on a shared host or not though, and if they are they won't be the root user and so functions like chmod() and rmdir() will be disallowed. Even if they weren't on a shared host I doubt whether they would be running scripts as root anyway. I cannot ask the user to set the file permissions to 0777 to use the CMS as I know that most people would not do that, I know I wouldn't. So my plan of action was to have the permissions set to 0644 and temporarily change them to 0777 whiles I push the changes then change it back again afterwards. I have a tiny website on a shared host so I am able to test this in the worst of scenarios and these are the errors I get: Quote from: The errors Warning: chmod() [function.chmod]: Operation not permitted in ******** on line 20 Warning: fopen(********) [function.fopen]: failed to open stream: Permission denied in ******** on line 35 Warning: fwrite() expects parameter 1 to be resource, boolean given in ******** on line 39 Warning: fclose() expects parameter 1 to be resource, boolean given in ******** on line 40 Because I am not the root user chmod is not permitted and because the file permissions are set to 0644 I cannot execute the file system functions which alter the files. It all relies on the permissions being set right. I tried using umask() but as someone says in a note on php.net, umask can only remove/delete permissions, it can't grant them. So that seems like a dead end. I can't change ownership either with chown() as that requires you to be the root to use too. Wondering what was going on I used fileperms() to find out what the permissions were according to the php and got the number 33188. Turns out after a bit of research that this is an octal number, so I converted it and got the number 100644. That looks about right, but I don't know what the 10 is doing before the permissions? Does anyone know how can I get around this problem? I would like to avoid using FTP functions if I can. Thanks for any help, Joe Can someone please give me some guidance on how to deal with the following warning Quote
Warning: move_uploaded_file(../usernet/img/60ff59c9f0a830.45733158.jpg): Failed to open stream: Permission denied in /opt/lampp/htdocs/site/admin/add_post.php on line 23 All directories and files in the path have full owner permissions and I've made myself the owner of them all (I'm on a linux system). I've also done the same with the /tmp folder. I can't even think of anything else to change and haven't found anything online that solves the issue. in case it's needed, the php is as follows: <?php require("assets/initializations.php"); if(isset($_POST['add_post']) && !empty($_FILES['post_image'])) { $filename = $_FILES['post_image']['name']; $file_tmp_name = $_FILES['post_image']['tmp_name']; $filesize = $_FILES['post_image']['size']; $file_ext = explode('.', $filename); $file_act_ext = strtolower(end($file_ext)); $allowed = array('jpeg', 'jpg', 'png', 'gif'); if(!in_array($file_act_ext, $allowed)) { header("Location: add_post.php?message=file_type_not_allowed"); } else { if($filesize > 10000000) { header("Location: add_post.php?message=file_too_large"); } else { $file_new_name = uniqid('', true) . "." . $file_act_ext; $dir = "../usernet/img/"; $target_file = $dir . basename($file_new_name); move_uploaded_file($file_tmp_name, $target_file); echo "<script>alert('Image uploaded successfully');</script>"; } } } I do get the javascript alert that's it's been successfully uploaded, but the image doesn't make it into the specified directory and I get the warnings at the top. I'm also, probably obviously from the path, using XAMPP server for development. TIA This topic has been moved to Other Libraries and Frameworks. http://www.phpfreaks.com/forums/index.php?topic=357211.0 HI All, Currently when my users log into my site i store their user level in a session. This allows admins to see more than normal users. I am worried that it would be very easy for someone to amend the session and give themselves admin rights. I am asking for advice on best practice for setting the user level of the logged in user. Where would you suggest i store this information so that only admins see the admin stuff. My navbar has a PHP if test running against $_SESSION['user_level'] and only admins see the admin panal. Hi Have searched this and other forums for an answer to this and found lots of similar questions but nothing dealing with exactly what I'm after. I want to copy a file located in parent/dir1/file.pdf (for example) to another directory parent/dir2/id/file.pdf. This is straightforward enough using copy(). But... I don't want users to be able to access the original file directly (eg by just putting /parent/dir1/file.pdf into their browser. The only way I seem to be able to do this is by removing the 'read' permission, but then the copy() command gives an error. If this is possible, I assume the solution is somehow linked to the various file and directory permissions but I can't figure out the correct settings. Can someone help out? Thanks in advance hello guys. i ve been trying to write to a file using fwrite() inside my server directory. i am using this code: Code: [Select] ini_set('error_reporting', 'on'); error_reporting(E_ALL); echo substr(sprintf('%o', fileperms('skata')), -4); $fp = fopen("skata", "w"); fwrite($fp, "skata"); fclose($fp); the only thing that comes up to the browser is: Code: [Select] 0777 i have even pre-created the file "skata" in the diractory running as root and gave it permissions 777. i m not quite familiar with linux or apache permissions and i can tfigure out what's going wrong. i am running apache under fedora, and i would appreciate some guidelines here. This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=355485.0 I have a simply script like this: $fh = fopen("test/test.js", 'w+') or die("can't open file"); fwrite($fh, $output); fclose($fh); It ONLY works if the "test" directory has a 777 permissions. Works like a charm then, but the moment it goes to even 775, I get this: Warning: fopen(test/test.js) [function.fopen]: failed to open stream: Permission denied in /var/www/vhosts/mydomain.com/httpdocs/f.php on line 42 Any thoughts? I don't want this folder to remain 777 Thanks Hi everyone, am developing an application that has two views 1 for administrator and 1 for staff. Administrator can perform all application tasks and Staff can ONLY perform certain task. I have implemented sessions quite alright and are working. Now the problem is that when I login as Staff and then I change the URL to point to an administrator's page the application is allowing that, How can I prevent that from happening. Staff MUST NOT see administrators pages. Here is my login code, logout code and code am using to protect webpages below. Here is my login code <?php //start the session session_start(); $username=$_POST['username']; $password=$_POST['password']; $encrypted=md5($password); // set connection to database $hostname="localhost"; // Host name $mysql_server_username="root"; // Mysql username $server_password=""; // Mysql password $db_name="db_inventory"; // Database name $table = "tbl_users"; // Table name // Connect to server and select database. mysql_connect("$hostname", "$mysql_server_username", "$server_password")or die("cannot connect to database server"); mysql_select_db("$db_name") or die ("Couldn't select the database."); $admin=("select * from $table where username='$username' AND password='$encrypted' AND type = 'admin'"); $staff=("select * from $table where username='$username' AND password='$encrypted' AND type = 'staff'"); //check that at least one row was returned $adminresult=mysql_query($admin); $admincount = mysql_num_rows($adminresult); $staffresult=mysql_query($staff); $staffcount = mysql_num_rows($staffresult); if($admincount> 0){ $_SESSION['valid_user'] = $username ; header( "Location: main_menu.php" ); } else if($staffcount> 0){ $_SESSION['valid_user'] = $username ; header( "Location: staff/main_menu.php" ); } else { ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>title> | Login</title> </head> <body bgcolor="#FFFFFF" background-repeat:no-repeat; background="images/images1.jpg"> <div align="center"> <table width="800" height="501" border="0" cellpadding="1" cellspacing="1"> <tr> <td height="100"> </td> </tr> <tr> <td height="350"> <div align="center"> <form method="post" action="login_process.php"> <h4 align="center"><font color="red">Incorrect Username / Password ! Please Try Again</font></h4> <img name="" src=images/padlock_closed.gif width="34" height="32" alt="" /><br /><br /> <table width="314" border="0" cellspacing="1" cellpadding="1"> <tr> <td>Username:</td> <td><label> <input type="text" name="username" /> </label></td> </tr> <tr> <td>Password:</td> <td><label> <input type="password" name="password" /> </label></td> </tr> <tr> <td colspan="2"> <p> <input type="submit" name ="submit" value="Login" /> <input type="reset" value="Reset" /> </p> </td> </tr> </table> </form> </div> </td> </tr> <tr> <td height="100"> </td> </tr> </table> </div> </body> </html> <?php } ?> Here is my logout code <?php //start the session session_start(); //check to make sure the session variable is registered if(isset($_SESSION['valid_user'])){ //session variable is registered, the user is ready to logout session_unset(); session_destroy(); //the session variable isn't registered, the user shouldn't even be on this page header( "Location: index.php" ); } else { //check to see if the session variable is not registered if(!isset($_SESSION['valid_user'])){ //redirect to login page header( "Location: index.php" ); } } ?> Here is code I am using to protect pages <?php //start the session session_start(); //check to make sure the session variable is registered if(!isset($_SESSION['valid_user'])){ //redirect to login page header( "Location: index.php" ); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title> | Main Menu</title> <link rel="stylesheet" type="text/css" href="css.css" /> </head> <body> <div id="tabsF"> <ul> <!-- CSS Tabs --> <li id="current"><a href="main_menu.php"><span>MAIN MENU</span></a></li> <li><a href="stockmaster.php"><span>STOCK MASTER</span></a></li> <li><a href="controlpanel.php"><span>CONTROL PANEL</span></a></li> <li><a href="logout.php"><span>LOGOUT</span></a></li> </ul> </div> </body> </html> Thank you. I have a question for developing (or in this case rewriting) an application. The current application creates directories and files (thumbnails, etc..) in a directory of the application files. In order to do this I have to set the directories chmod to 777 via ftp. I know this isn't secure. What exactly do you put in the application's code to allow it to write to a file or directory with CHMOD of 755. good evening dear php-friends well i am in big trouble - i have a terrible server error! Code: [Select] on openSuse Linux server My Setup: OpenSuse 11.4 on the local machine! Linux- Server FileZilla Client ---------------- Version: 3.3.4.1 Build information: Compiled for: i686-pc-linux-gnu Compiled on: i686-pc-linux-gnu Build date: 2011-02-23 Compiled with: gcc (SUSE Linux) 4.5.1 20101208 [gcc-4_5-branch revision 167585] Compiler flags: -fomit-frame-pointer -fmessage-length=0 -O2 -Wall -D_FORTIFY_SOURCE=2 -fstack-protector - funwind-tables -fasynchronous-unwind-tables -g -fstack-protector -Wall -g -fexceptions Linked against: wxWidgets: 2.8.11 GnuTLS: 2.8.6 Operating system: Name: Linux 2.6.37.6-0.7-default i686 Version: 2.6 Well folks i go crazy - sure thing: I run a linux-root-server that is administered by a friend of mine. i controll the SFTP session - with filezilla (see all i mentione above) in order to do installations and maintenance of some drupal-installations (and besides them some joomla-sites) Note: in the future i want to install Drush - in order to get rid all that annoying bugs. I am using directories with setgid bit set. I want to change the permissions of newly created directories to give write permission to the group (by default they have not). For this I right-click on the directory and change the permissions from the Properties dialog. When I change the permissions of a directory that way, the setgid bit gets removed. In fact, there is no way to set the setgid bit, it just always gets turned off, whatever operation one does on permissions.I heard that a buddy found a workaround by creating a custom command that executes chmod -R g+w "!" and applies on directories. This works fine. he said. Well what should i do!? BTW - why does this custom comand work for him !? Can somebody explain this abit! Well i go almost crazy and throw the computer out of the window (well notabene - of the 14 th floor) this is sure thing no good idea but i need to have a solution. waht should i do here. Note: with FileZilla you cannot (!!!!!) set the SETGID-Bit again - no way here - no chance. But with winscp (see below the link ). And you can imagine with Drush you can do it too! What sould i do - can you advice something for me! btw: see winscp with its ability to control the SETGID bit more than the FileZilla can do!! Well what can cause the issue - where is it rooted. Why do i loose the SETGID-Bit every time! It is possible that our SFTP server does not support the setgit bit and silently ignores the request to set it. What is the issue - can it be the SFTP.-SERVER!? Do you need more information more input should i do more investigations on the troubles and the environment. just let me know - i do everything to get the troubles rid! look forward to hear from you Greetings |