【问题标题】:How should I be writing the HTML etc for security roles in the application I've inherited?我应该如何为我继承的应用程序中的安全角色编写 HTML 等?
【发布时间】:2010-08-13 08:53:59
【问题描述】:

正如标题所示,我继承了一个 php/MySQL 应用程序,该应用程序的程序代码编写得相当好,但只有一个管理员用户登录。客户自然希望将功能拆分为不同的用户/角色,并最终使用最佳实践技术更新应用程序代码。

对于在管理部分更新某人的用户名的示例,原始版本仅显示一个预先填充了用户名的文本字段(为简洁起见简化了代码):

<input type="text" name="username" value="<?= $username; ?>">

然后根据正则表达式检查 POST 并将其保存到数据库中。

我被要求查看如何更改现有代码,以便它可以处理不同的用户“角色”,并且非常高兴地模拟了一个示例应用程序,其中包含 userrolepermission 等表、user-rolerole-permission 来解释这在实践中是如何工作的。我只是想知道你们中是否有人对如何将权限写入代码库有任何提示?将模板或函数中的现有代码简单地包装成如下内容是否明智:

// $access_type can be the result of a function call, an array value, etc.
switch($access_type){
    case 'edit':
        echo '<input type="text" name="username" value="' . $username . '">';
        break;
    case 'readonly':
        echo $username;
        break;
    case NULL:
    default:
        // Don't display anything.
}

我的问题是,对于更大的代码块,这种扩展效果如何?有几个“交互功能”使用大量的 HTML 和 JavaScript 来一次回传多个值。我们会为每个角色有效地拥有这个自定义控件的单独版本。将每个版本粘贴到 switch 中有点味道(无论是内联代码还是作为单独的文件包含在内)......同样,在后端,处理 POST 的脚本将根据角色有多个版本。

我知道一定有一百种方法可以做到这一点,但其他人过去做过什么?如果你有一些见识,你能不能用程序风格来演示它,因为在这个项目中没有 OO 可以看到!谢谢!

【问题讨论】:

    标签: php security permissions coding-style


    【解决方案1】:

    你可以使用类似的东西:

    interface User {
        /* stores several roles */
        /**
         * Combines the permissions of the several roles
         * of the user and returns the result.
         * @return Permission */
        function getPermission($key);
    }
    interface Role {
        /* stores several permissions */
        /* if there's no record of this kind of this
         * particular permission, return an empty one */
        /** @return Permission */
        function getPermission($key);
    }
    interface Permission {
        /** @return Permission */
        function combine(array $permissions);
        /** @return bool */
        function canEdit();
        function canRead();
    }
    

    然后就这样做:

    /* user factory takes care of creating the instances and
     * wiring them together */
    $u = UserFactory::loadCurrentUser();
    if ($u->getPermission('admin_page')->canWrite()) {
        //...
    }
    

    【讨论】:

    • 您好 Artefacto,感谢您的回答。但是,我正在寻找有关如何最好地将 HTML/JavaScript 块包含到 if/else 或 switch 代码中以及如何处理访问类型“canWrite()”不够精细的情况的建议 - canWrite()返回一个布尔值,而我正在研究一个可能返回多种访问类型之一的场景(例如,'edit'、'readonly' 和可能的 'constrain_to_8_characters'、'lowercase_only'),它们都将使用不同的 HTML 表单和后端验证。谢谢!
    • @Bendos 您可以通过添加额外权限来实现额外的粒度。例如,if ($u-&gt;getPermission('admin_page_uppercase_stuff')-&gt;canWrite()) { ... }
    • @Atrefacto - 我想根据权限返回editreadonlylowercase_only 显示不同的HTML/JavaScript。如果它更像switch($u-&gt;getPermission('username')-&gt;getEditability()) { ... },你的例子会起作用吗?
    猜你喜欢
    • 2010-12-22
    • 2019-10-12
    • 2022-12-14
    • 2014-10-20
    • 2011-04-12
    • 2023-03-19
    • 1970-01-01
    • 2013-04-05
    • 2013-08-11
    相关资源
    最近更新 更多