【问题标题】:User Record Ownership with OctoberCMS & MySQL使用 OctoberCMS 和 MySQL 的用户记录所有权
【发布时间】:2017-03-20 03:49:42
【问题描述】:

我正在使用基于LaravelOctoberCMS,带有官方的User 插件。

我正在制作一个前端用户可以上传文件的画廊。

用户是其上传文件的所有者,并且是唯一有权编辑的人。


我的问题,这是设计和处理用户记录所有权的正确方法吗?所有用户上传记录将混合在一个数据库表mysite_gallery_ 中,并使用过滤器进行排序和显示在 html 中,例如通过特定用户名查看所有上传。

这会很慢吗?每个用户都应该有自己的表吗?是否足够安全以防止其他用户、机器人或黑客脚本编辑他们不拥有的文件记录?


MySQL 表

所有上传记录都保存到表mysite_gallery_

| id   | username   | filename   | slug     | title     | tags                 |
| ---- | ---------- | ---------- | -------- | --------- | -------------------- |
| 1    | matt       | xyz123     | xyz123   | My File   | space, galaxy, stars | 

记录所有权

在上传时,我的自定义 Upload 组件使用 Laravel 在数据库中创建文件的titleslugtags 等记录。

为了定义所有权,我让上传组件将用户的username 保存到记录中。

# Get Current User
$user = '';
if (Auth::check()) {
    $user = Auth::getUser();
    $user = $user->username;
}

# Create Record
$gallery = new Gallery();
$gallery->username = $user;
$gallery->filename = $name;
$gallery->title = $title;
$gallery->slug = $slug;
$gallery->tags = $tags;
$gallery->save();

编辑记录

如果用户想要编辑文件属性,例如标题,Laravel 会检查 current user 是否与记录中的 username 匹配。如果用户是所有者,则允许编辑。

# Get File Record Owner
$owner = '';
if (Gallery::where('filename', '=', $filename)->exists()) {

    $record = Gallery::where('filename', '=', $filename)->first();
    $owner = $record->username;

}

# Authenticate Current User is Owner
$is_owner = false;
if (Auth::check()) {

    # Get Current User
    $user = Auth::getUser();

    # Check if User is Owner
    if ($user->username == $owner) {
        $is_owner = true;
    }
}

# Edit Record
if ($is_owner == true) {

    # Update Record
    Gallery::where('filename', '=', $filename)->update(['title' => $title]);

    return Redirect::back();
}

【问题讨论】:

    标签: php mysql laravel laravel-5 octobercms


    【解决方案1】:

    最好使用用户 ID 而不是用户名。它在数据库中占用的空间更少,速度也更快。

    我还会将标签放在另一个表中。尽管这取决于您如何使用标签。例如,如果您将它们放在另一个表中,那么获取标签的所有上传内容会更容易。

    【讨论】:

    • 如果我添加一列'user_id'并保存id,然后过滤记录,它会比搜索用户名更快地搜索数字?
    • 是的。您还可以为 id 添加索引以进一步提高性能
    猜你喜欢
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    • 2020-11-22
    • 1970-01-01
    • 2017-07-21
    相关资源
    最近更新 更多