【问题标题】:A user can manually edit another user view from URL用户可以从 URL 手动编辑另一个用户视图
【发布时间】:2020-06-29 18:03:30
【问题描述】:

我刚刚注意到,用户可以通过更改 URL 中的其他用户 pk 或用户名(作为 slug)手动访问其他用户更新配置文件视图。 比如

http://127.0.0.1:8000/account/dashboard/18/updateprofile

假设这是用户更新个人资料的网址,如果该用户将 pk 更改为 19 并进行编辑,则会编辑具有 pk 19 个人资料的用户,这是一个错误还是我这边的错误?谢谢。

我的观点

class ProfilepdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
    login_url = 'userlogin'
    fields = ('age', 'location')
    model = UserProfile
    template_name = 'account/updateprofile.html'
    success_message = "Your profile was successfully updated"

网址

path('account/dashboard/<int:pk>/updateprofile', views.ProfilepdateView.as_view(), name="updateprofile"),

【问题讨论】:

  • 这似乎真的是关于网页设计和安全的问题,而不是关于编程的问题。
  • moonpig exposed customers data 就是这样,是功能还是错误取决于您的应用程序。
  • Django 不知道谁可以访问视图,这取决于你在视图中处理。如果您 edit 您的问题包括您的视图和 URL 模式,那么我们可以建议如何限制访问。
  • 哦我明白了,我不知道,现在我明白了 django 不知道谁可以访问视图。

标签: python django


【解决方案1】:

由你决定谁可以做什么和在哪里做 - Django 无法猜到这一点。您有两种解决方案:

1/ 保持您的网址不变,但检查是否允许当前用户 (request.user) 编辑此配置文件:

def update_profile(request, profile_id):
    # assume that profile as a onetone to User
    profile = get_object_or_404(pk=profile_id)
    if request.user != profile.user:
        return HttpResponseForbidden()
    # your code here

2/从url中去掉profile_id,使用request.user获取当前用户的profile

def update_profile(request, profile_id):
    # assume that profile as a onetone to User
    profile = request.user.get_profile()
    # your code here

【讨论】:

  • 感谢您的回复,但这是一个通用视图而不是基于函数的视图,您有什么建议?我更新了问题以显示视图。谢谢
  • 我实际上尽可能避免使用 CBV——大多数时候它们只会让事情变得无用的复杂化,而且它们真的对新手没有帮助......现在不是一个非常简单的更改而是一个非常简单函数,你必须找到你必须覆盖的十几个父类中的哪个方法。
  • 或者更好:使用UserPassesTest mixin,参见stackoverflow.com/questions/29682704/…
【解决方案2】:

感谢我所有能干的BOSSES和MASTERS,这是我为解决问题而添加到我的观点中的。

def get_queryset(self):
    profile= super().get_queryset()
    return profile.filter(user=self.request.user)

最终的视图是这样的

class ProfilepdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
    login_url = 'userlogin'
    fields = ('age', 'location')
    model = UserProfile
    template_name = 'account/updateprofile.html'
    success_message = "Your profile was successfully updated"

    def get_queryset(self):
        profile= super().get_queryset()
        return profile.filter(user=self.request.user)

【讨论】:

    【解决方案3】:

    这样,其他用户仍然可以访问其他用户页面,但无法更新它。如果您最初只希望个人资料的所有者能够访问更新页面,那么您可以限制在模板中查看。

        {% if object.user == user %} Show Page Content {% endif %}
    

    或在视图中。

    【讨论】:

    • 谢谢兄弟,我知道这一点,我只是想在视图中而不是在模板中处理它。根本不希望将信息呈现到页面上。只有运动鞋用户会手动更改 url 中的 pk,因此如果运动鞋用户尝试这样做,则使用此 GET_QUERYSET 函数,他将被发送到 404 页面。我个人认为这比让狡猾的用户即使看不到信息也能访问页面要好。
    • 是的.. 有时,我故意在模板中限制偷偷摸摸的用户权限,只是为了嘲讽用户。比如,通知用户偷偷摸摸。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 1970-01-01
    • 2023-03-04
    • 2011-06-16
    相关资源
    最近更新 更多