代码之家  ›  专栏  ›  技术社区  ›  kebie

Django:如果url是由用户手动写入的,则重定向

  •  0
  • kebie  · 技术社区  · 6 年前

    是否可以限制用户手动放置页面的url?

    假设我有两页-somepage。通信/家和某处。com/other和主页中的某个地方是一个按钮,用于将用户重定向到/other站点。我想确保用户无法通过手动写入其url来访问/其他。相反,它应该重定向回主页。

    是否需要一些类似于decorator的login\u,我可以使用?或者我应该使用一些js函数?

    提前谢谢你的提示,干杯。

    2 回复  |  直到 6 年前
        1
  •  0
  •   Umair Mohammad    6 年前

    尝试使用html的referer属性,如果用户通过单击主页中的链接转到其他页面,则referer指向您的主页。但是,如果用户手动键入了其他页面链接,那么推荐人将不会指向您的主页。

    返回值:一个字符串,表示加载当前文档的文档的URL。返回整个URL,包括协议(如http://)。如果当前文档不是通过链接(例如,通过书签)打开的,则返回空字符串。

    参考号: https://www.w3schools.com/jsref/prop_doc_referrer.asp

    其他效率不高的解决方案:

    1. 您不需要登录功能?如果需要,只需继续实现一个视图,并将另一个视图标记为login\u required。 如果不需要,请阅读第2点。

      1. 您可以从主页按钮发布一些随机的唯一值,以转到其他页面。在其他视图中检查该值。如果找不到该值,则重定向到主页。如果找到,则显示其他视图。 如果用户通过输入url访问页面,则该值将丢失要发生的重定向到主页的内容。需要注意的一点是,此解决方案不安全。如果您没有实现足够的安全性,用户可以欺骗服务器。
        2
  •  0
  •   rmaleki Chris Mustola    6 年前

    您可以构建一个中间件并使用它。 首先,您需要为每个用户提供一个组或访问该用户的权限。我使用user\u type完成了此操作。 现在,您创建文件acl并创建一组URL名称。

    acl。py公司

        acl_view_segment_divided = {
            "pack_1": [
                "url_name_1",
                "url_name_2",
                .
                .
                .
            ],
            "pack_2": [
                "url_name_3",
                "url_name_4",
                .
                .
                .
            ],
        }
    
        acl_view_segment = dict(
            user_type_1=list(
                acl_view_segment_divided["pack_1"] +
                acl_view_segment_divided["pack_2"]
            ),
            user_type_2=list(
                acl_view_segment_divided["pack_1"] 
            ),
        )
    

    现在需要创建中间件文件:

    中间件。py公司

    from django.conf import settings
    from django.utils.deprecation import MiddlewareMixin
    from django.core.urlresolvers import resolve
    from acl import acl_view_segment
    from django.shortcuts import render
    from django.contrib import auth
    
    from apps.main.views import page_permission_denied_view
    
    
    class ACLMiddleware(MiddlewareMixin):
        @staticmethod
        def process_view(request, view_func, view_args, view_kwargs):
            if not request.user.is_authenticated():
                return
    
            current_url = resolve(request.path_info).url_name
    
            if current_url in getattr(settings, 'ACL_EXEMPT_VIEWS', set()):
                return
    
            user_type = request.user.user_type
    
            acl = acl_view_segment[user_type]
    
            if current_url not in acl:
                return page_permission_denied_view(request)
                or
                return redirect(home_page)
    

    向设置中添加了中间件。py公司

    设置。py公司

    MIDDLEWARE = [
        ...
        'yourproject.middleware.ACLMiddleware',
    ]
    

    如果您有问题,请在评论中提出问题。我希望你的问题得到解决。