Can anyone please help?

22 views
Skip to first unread message

Milson Munakami

unread,
Apr 30, 2020, 8:06:28 AM4/30/20
to django...@googlegroups.com

Can anyone please help me to resolve this issue?

https://stackoverflow.com/q/61514512/1316060

My url path in project's url.py is defined as follows:

path('endpoint/', views.Endpoint.as_view(), name='get_endpoint'),

The views.py include the following class to handle this routing:

@method_decorator(csrf_exempt, name='dispatch') 
class Endpoint(View):
    def get(self, request, *args, **kwargs):
        ############ Here I can see the User Session ##########
        if not request.user.is_authenticated:
            return redirect('authentication_router')

        return redirect(
            'https://app.globus.org/file-manager?method=POST&action=%s&cancelurl=%s&folderlimit=1&filelimit=0&label=%s'
            % (
            request.build_absolute_uri(), "/", "To Transfer your Files Select the Folder first!")
        )

    def post(self, request, *args, **kwargs):  # On return from OAuth Page
        ############ Here, User Session return nothing so user is AnonymousUser ##########
        if request.POST.get('folder[0]'):  # A Endpoint folder was selected
            endpoint_path = os.path.join(request.POST.get('path'), request.POST.get('folder[0]'))
        else:
            endpoint_path = request.POST.get('path')     

        profile = request.user.userprofile # request.user does not has userprofile
        profile.endpoint_path = endpoint_path
        profile.save()

        return HttpResponseRedirect(reverse('authentication_router'))

The problem is when the get is called it finds the request.user value as authenticated user but once the redirect from OAUTH page with POST hits the class it loss all request user session and gives error at this line:

profile = request.user.userprofile

As, request.user seems loss its session and has value of AnonymousUser even though till GET method it is preserving the user's login session values.

My settings.py file includes:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    **'django.contrib.sessions',**
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'myapp',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    **'django.contrib.auth.middleware.AuthenticationMiddleware',**
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

I am testing it in localhost:8000 .Please let me know what I am missing this code. Same code is perfectly working in Django 1.8 and Python 2.7. Recently, I am trying to upgrade it to work with Django 3 and Python 3. Only difference I can see is in settings.py in Django 1.8 version includes: 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',in MIDDLEWARE_CLASSES which is removed in latest version of Django.


--
Thank you,

Milson

Virus-free. www.avg.com

Amitesh Sahay

unread,
Apr 30, 2020, 2:16:32 PM4/30/20
to django...@googlegroups.com
It should be Endpoint.as_view()


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAP1qhGui2o%3DDJD57Rq7GaiVO-s9wOgSdw1G-bNLPSYCL9Wkeuw%40mail.gmail.com.

Milson Munakami

unread,
Apr 30, 2020, 2:23:17 PM4/30/20
to django...@googlegroups.com
Hi Sahay,

That is already
 
path('endpoint/', views.Endpoint.as_view(), name='get_endpoint'),

--
Thank you,

Milson Munakami

Mobile: 208.220.2943 

Amitesh Sahay

unread,
Apr 30, 2020, 2:34:28 PM4/30/20
to django...@googlegroups.com
I think "views." is incorrect. It should not appear as prefix. However , it also depends on how you have impoted 

Did you import as below?

from views import view_name

OR

import views


Amitesh Sahay

unread,
Apr 30, 2020, 2:36:44 PM4/30/20
to django...@googlegroups.com
You can also try keeping the same name for the endpoint as below

path('endpoint/', views.Endpoint.as_view(), name='endpoint'),
On Thu, 30 Apr 2020 at 23:52, Milson Munakami

Milson Munakami

unread,
Apr 30, 2020, 2:40:00 PM4/30/20
to django...@googlegroups.com
Amitesh,

My class Endpoint(View)is imported from :from django.views import View Class level view even I tried to use function level view it is showing same problem in get the request.user is something authenticated but in post the user session is lost.


Milson Munakami

unread,
Apr 30, 2020, 2:41:30 PM4/30/20
to django...@googlegroups.com
But when I refresh the page it shows I am still logged in user. Only problem is when the external page redirects it can't see the logged in user. SOmething in setting am I missing per as you can see all Middlewares are included correctly!.

Milson Munakami

unread,
Apr 30, 2020, 2:50:43 PM4/30/20
to django...@googlegroups.com
I am importing app level views like this in `urls.py`
from . import views

Milson Munakami

unread,
May 1, 2020, 11:51:41 AM5/1/20
to django...@googlegroups.com

Interesting findings :
1. If I put Querystring to redirect that works fine and I can correctly get request.user sessions
2. It breaks to --> AnonymousUser as soon as I try to use: request.session variables inside the returned POST method of the Endpoint View Class.
3. Though, when I navigate to another pages and refresh- the user seems logged in already
Am I missing something in setting to hold those session redirected from external page

 This is my solution which is working fine as I want but I doubt it is optimal solution:  

-----------------------------

def redirect_params(url, params=None):
response = redirect(url)
if params:
query_string = urllib.parse.urlencode(params)
response['Location'] += '?' + query_string
return response

----------------

@method_decorator(csrf_exempt, name='dispatch')
class Endpoint(View):
def get(self, request):

if not request.user.is_authenticated:
return redirect('oaut_login')

cancel_url = request.build_absolute_uri(reverse('index'))

return redirect(
'https://app.test.org/file-manager?method=POST&action=%25s...'
% (
request.build_absolute_uri(), cancel_url, "Select the Folder to your Endpoint")
)

def post(self, request): # On return

if request.POST.get('folder[0]'): # A folder was selected

endpoint_path = os.path.join(request.POST.get('path'), request.POST.get('folder[0]'))
else:
endpoint_path = request.POST.get('path')

endpoint_id = request.POST.get('endpoint_id')

params = {
'endpoint_path': endpoint_path,
'endpoint_id': endpoint_id
}

return redirect_params('user_home', params)

----------------
def user_home(request):
# print(request.GET.urlencode())
endpoint_path = request.GET.get('endpoint_path')
endpoint_id = request.GET.get('endpoint_id')

endpoint_information_request = requests.get('https://test.api.globusonline.org/v0.10/endpoint/%s' % endpoint_id,
headers={'Authorization': 'Bearer %s' % request.user.userprofile.transfer_token})

endpoint_information_as_json = json.loads(endpoint_information_request.text)
if 'display_name' in endpoint_information_as_json:
endpoint_display_name = endpoint_information_as_json['display_name']
else:
endpoint_display_name = None

# update the User profile with Endpoint selected info
profile = request.user.userprofile
profile.endpoint_id = endpoint_id
profile.endpoint_display_name = endpoint_display_name
profile.save()

return HttpResponseRedirect(reverse('index'))
  
Reply all
Reply to author
Forward
0 new messages