django xss过滤

django对于xss的过滤有其本身自带的safe等

但是如果通过jsonResponse返回再在前端加载,无法对XSS进行有效的过滤。

因此需自己写一个XSS过滤器,作为装饰器对request的GET POST函数的返回值进行过滤。

该过滤函数通过对 json list 字符串等进行过滤、可用于 render 、 HttpResponse、JsonResponse 

import json

def jsonXssFilter(data):
    payloads = {
        '\'':''',
        '"':'"',
        '<':'<',
        '>':'>'
    }
    if type(data) == dict:
        new = {}
        for key,values in data.items():
            new[key] = jsonXssFilter(values)
    elif type(data) == list:
        new = []
        for i in data:
            new.append(jsonXssFilter(i))
    elif type(data) == int or type(data) == float:
        new = data
    elif type(data) == str:
        new = data
        for key,value in payloads.items():
            new = new.replace(key,value)
    elif type(data) ==bytes:
        new = data
    else:
        print('>>> unknown type:')
        print(type(data))
        new = data
    return new

def xssfilter(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        result.content = result.content
        try:
            jsondata = json.loads(result.content)
            result.content = json.dumps(jsonXssFilter(jsondata))
        except:
            result.content = jsonXssFilter(result.content)
        return result
    return wrapper

 

demo  作为GET POST函数的装饰器:

class PermissionListView(LoginRequiredMixin, generic.TemplateView):
    """权限管理"""
    def dispatch(self, request, *args, **kwargs):
        return super(PermissionListView, self).dispatch(request, *args, **kwargs)
    @xssfilter
    def get(self, request, *args, **kwargs):
        if not user_has_permission(str(request.user),'permission_list'):
            return render(request, "blank.html")
        return render(request, 'user_manage/permission.html', locals())

    @xssfilter
    def post(self, request, *args, **kwargs):
        if request.is_ajax():
            self.post_data = request.POST
            dics = {
                "listPermission":{'op_fun':self.list_permission,'perm':'permission_list'},
                "addPermission":{'op_fun':self.add_permission,'perm':'permission_operate'},
                "delPermission":{'op_fun':self.del_permission,'perm':'permission_operate'}
            }
            operation=self.post_data.get("operation","")
            if not user_has_permission(str(request.user),dics[operation]['perm']):
                response = {'state':'false','message':'权限不够,需%s权限'%(dics[operation]['perm'])}
                return JsonResponse(response)
            data = dics[operation]['op_fun']()
            if not data:
                data = {}
            data['state'] = 'success'
            return JsonResponse(data=data)
    def list_permission(self):
        return {'permissions':search_all_permission()}
    def add_permission(self):
        permission_name = self.post_data['permissionName']
        permission_codename = self.post_data['permissionCodename']
        add_permission(name=permission_name,codename=permission_codename)
    def del_permission(self):
        del_permission(permissionid=self.post_data['permissionid'])

 

转载于:https://www.cnblogs.com/huim/p/9830760.html

你可能感兴趣的:(django xss过滤)