gpt4 book ai didi

php - 保护/限制用户组功能的良好做法

转载 作者:搜寻专家 更新时间:2023-10-31 21:33:04 25 4
gpt4 key购买 nike

我有一个扩展到多个类文件的大项目。这个项目是在赶时间前匆忙完成的。这对项目安全造成了影响。所以简单来说,理论上任何人都可以在我的项目中调用一个 AJAX 脚本并让它运行,因为脚本中的函数不是用户权限感知的。当然,我会检查我所有的 AJAX PHP 脚本以查看用户是否已登录。

举个例子:

// Update user information. This script is called with jQuery AJAX:
<?php
include('../../../config/config.php');
require_once('classes/Autoloader.php');

$iris = new IRIS();

if( !$iris->UUID() ){
die( "Unauthorized access! ");
}

$result = array('success'=>true);

$users = new users();

try {
$res = $users->createUser();
$result = array( 'success' => true, 'result' => $_POST );
}
catch(Exception $e){
$result = array( 'error' => true, 'errmsg' => $e->getMessage() );
}

echo json_encode( $result );

我有 3 个用户类:“Admin”、“client”、“employee”。现在理论上,所有这些都可以调用此 php 脚本,并修改用户,即使只有管理员有权执行此操作。用户在数据库中指定了权限参数,我在项目中通过常量定义:

define('USER_AUTH_LEVEL', $_SESSION['auth_level']);

我知道我可以更新每个 AJAX PHP 文件并设置:

if( USER_AUTH_LEVEL !== 1 ) { die( 'You do not have access' ); }

但我想做的是保护所有或部分类的功能。比方说:

class IRIS {
public function doSomething(){
// $function_access not defined, accessable by all
}
public function doSomethingAdmin(){
$function_access = 1;
// Should be limited to admins
}
public function doSomethingClient(){
$function_access = 2;
// Should be limited to clients
}
}

我想要实现的是一个脚本,无论它在哪个类中运行,每次函数都会运行。此脚本应检查是否设置了参数 $function_access。如果是,它应该与当前登录用户的权限级别进行比较。如果不匹配,函数应该中断。如果根本没有定义,任何人都可以运行该函数。

有没有人有办法解决这个问题?我在这里完全空白。

最佳答案

您需要在任何函数调用之前调用一些函数。为此,请使用 __call方法:

class IRIS extends Access {
/* other methods here */

// list all methods to allow some access levels.
public function accessControll() {
return [
parent::ADMIN => ['doSomethingAdmin', 'doSomethingElseAdmin'],
parent::USER => ['doSomething', 'doSomethingElse'],
];
}
}

abstract class Access {
// access levels defines
const ADMIN = 1, USER = 2;

public function __call($method, $arguments) {
$accessLevel = -1;

// get access level of current method
foreach ($this->accessControll() as $key => $group) {
if (in_array($method, $group)) {
$accessLevel = $key;
break;
}
}

if (USER_AUTH_LEVEL !== $accessLevel) {
throw new Exception('You do not have access');
// OR header('HTTP/1.0 401 not authorized');
}
}

// abstract, so every class, that extends it must have this method.
abstract public function accessControll();
}

关于php - 保护/限制用户组功能的良好做法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26293500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com