我正在使用基于Laravel的OctoberCMS,以及官方用户插件。
我正在制作一个画廊,前端用户可以在其中上传文件。
用户是其上传文件的所有者,并且是唯一有权编辑的用户。
我的问题是,这是设计和处理用户记录所有权的正确方法吗?所有用户上传记录将混合在一个数据库表中mysite_gallery_
,并将使用过滤器以 html 形式排序和显示,例如按特定用户名查看所有上传。
这会很慢吗?每个用户都应该有自己的表吗?它是否足够安全,以防止其他用户、机器人或黑客脚本编辑他们不拥有的文件记录?
MySQL 表
所有上载记录都保存到表中mysite_gallery_
。
| id | username | filename | slug | title | tags |
| ---- | ---------- | ---------- | -------- | --------- | -------------------- |
| 1 | matt | xyz123 | xyz123 | My File | space, galaxy, stars |
记录所有权
在上传时,我的自定义上传组件使用 Laravel 在文件的title
、slug
、tags
等数据库中创建记录。
为了定义所有权,我让上传组件将用户的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();
}
最好使用用户 ID 而不是用户名。它将在数据库中占用更少的空间,而且速度也更快。
我也会把标签放在另一个表中。尽管这取决于您如何使用标签。例如,如果您将它们放在另一个表中,那么获取标签的所有上传会更容易。