问:如何在身份验证发生之前存储会话数据

时间:2019-03-30 02:44:33

标签: django django-authentication django-allauth

我正在使用django-all身份验证和GMail登录。

我的观点之一是将从其他服务器中的热点登录页面接收HTTP-POST(实际上是mikrotik热点重定向)。 社交登录后,我需要阅读他们发布的数据。

我读了https://stackoverflow.com/a/32250781/5901318

最安全的方法似乎是将POST数据存储在会话中,稍后我的视图将从request.session中获取

但是我不知道如何“在身份验证发生之前将数据安全地存储在request.session中”。

def my_login_required(function):
    #https://stackoverflow.com/a/39256685/5901318
    def wrapper(request, *args, **kwargs):
        decorated_view_func = login_required(request)
        if not decorated_view_func.user.is_authenticated:
            if request.method == "POST" :
                print('my_login_required POST:',request.POST.__dict__)
                print('my_login_required ARGS:',args)
                print('my_login_required KWARGS:',kwargs)
                print('my_login_required SESSION:',request.session.__dict__)
    wrapper.__doc__ = function.__doc__
    wrapper.__name__ = function.__name__
    return wrapper


#@receiver(user_logged_in)
@csrf_exempt 
@my_login_required
def hotspotlogin(request,*args,**kwargs):
    print('HOTSPOTLOGIN')

我尝试使用请求访问它:

r = requests.post('http://mysite:8000/radius/hotspotlogin/', json={"NAMA": "BINO"}, headers = {'Content-type': 'application/json', 'Accept': 'text/plain'})

但是在django shell中我只有:

my_login_required POST: {'_encoding': 'utf-8', '_mutable': False}
my_login_required ARGS: ()
my_login_required KWARGS: {}
my_login_required SESSION: {'storage_path': '/opt/djangos/radius03/mysessions/', 'file_prefix': 'sessionid', '_SessionBase__session_key': None, 'accessed': True, 'modified': False, 'serializer': <class 'django.core.signing.JSONSerializer'>, '_session_cache': {}}

请给我任何线索。

真诚的

-bino-

1 个答案:

答案 0 :(得分:0)

得到了朋友的无价帮助,这是解决方案。

def my_login_required(function):
    def wrapper(request, *args, **kwargs):
        old_data=dict()
        try :
            old_data['POST'] = dict(request.POST)
        except :
            old_data['POST'] = dict()

        try :
            old_data['GET'] = dict(request.GET)
        except :
            old_data['GET'] = dict()

        old_data['method'] = request.method

        decorated_view_func = login_required(request)
        if not decorated_view_func.user.is_authenticated: #Only if user not authenticated
            request.session['old'] = old_data  #put old data in request.session['old']
            return decorated_view_func(request)  # return redirect to signin

        return function(request, *args, **kwargs)

    wrapper.__doc__ = function.__doc__
    wrapper.__name__ = function.__name__
    return wrapper


@my_login_required
def testview(request,*args,**kwargs):
    print('SESSION DATA:', request.session.get('old')) #take original post/get data from request.session['old']