How to fix social_core.exceptions.AuthMissingParameter error - django

I am trying to implement a google login onto my project. I already had a relatively working login scheme when I tried to use social_core's oauth with google to log in with a google account. It keeps throwing a social_core.exceptions.AuthMissingParameter error, meaning that somehow, the state isn't being passed at all.
I have been following the walkthrough done here https://fosstack.com/how-to-add-google-authentication-in-django/ as a baseline for how to implement this. When I run the code from this tutorial (besides some basic syntax and version errors), everything runs like a charm. However, when I try to implement it on my project, an error I cannot resolve occurs.
The url.py file I have, I have only imported some files and added the line
path('auth/', include('social_django.urls', namespace='social')),
Other, than that, most of my test code is similar to the blog: like this in my common file.
AUTHENTICATION_BACKENDS = (
'social_core.backends.open_id.OpenIdAuth', # for Google authentication
'social_core.backends.google.GoogleOpenId', # for Google authentication
'social_core.backends.google.GoogleOAuth2', # for Google authentication
'django.contrib.auth.backends.ModelBackend',
)
How the current situation is, is that I can click login, it takes me to a login page where I type in my google account, and then it throws the following exception:
Environment:
Request Method: GET
Request URL: http://localhost:3000/auth/complete/google-oauth2/
Django Version: 2.1.7
Python Version: 3.6.5
Installed Applications:
[##Some personal files###
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'markdownx',
'social_django',
'livereload']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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']
Traceback:
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\django\core\handlers\base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\social_django\utils.py" in wrapper
49. return func(request, backend, *args, **kwargs)
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\social_django\views.py" in complete
33. *args, **kwargs)
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\social_core\actions.py" in do_complete
43. user = backend.complete(user=user, *args, **kwargs)
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\social_core\backends\base.py" in complete
40. return self.auth_complete(*args, **kwargs)
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\social_core\utils.py" in wrapper
259. return func(*args, **kwargs)
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\social_core\backends\oauth.py" in auth_complete
388. state = self.validate_state()
File "C:\Users\Daniel\.virtualenvs\project-djMFGD5K\lib\site-packages\social_core\backends\oauth.py" in validate_state
88. raise AuthMissingParameter(self, 'state')
Exception Type: AuthMissingParameter at /auth/complete/google-oauth2/
Exception Value: Missing needed parameter state
Where I have edited out some of the more personal information, but those files aren't being used currently. I am pretty sure I have my keys done correctly, because the parameters are correct when I print them in the terminal after I run the server, and for the fact that google manages to send me the redirect at all.
Edit: Pretty sure the keys are correct, since when I remove them or type them incorrectly, I get a server not found error rather than a missing parameter error.

Related

user_change_password() got an unexpected keyword argument 'extra_context'

Django 3.0.7
When I try to change password in admin site, I get
TypeError at /admin/auth/user/1/password/
user_change_password() got an unexpected keyword argument 'extra_context'
Namely I pressed "this form" link:
More details
Environment:
Request Method: GET
Request URL: http://localhost:8000/admin/auth/user/1/password/
Django Version: 3.0.7
Python Version: 3.8.0
Installed Applications:
['admin_aux',
'images.apps.ImagesConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'posts',
'sidebars',
'general',
'categories',
'marketing',
'home',
'authors',
'taggit',
'cachalot',
'django_cleanup.apps.CleanupConfig',
'widgets',
'code_samples',
'hyper_links',
'polls',
'applications',
'videos',
'quotations',
'languages',
'people',
'arbitrary_htmls.apps.ArbitraryHtmlsConfig']
Installed 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']
Traceback (most recent call last):
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 231, in inner
return view(request, *args, **kwargs)
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/views/decorators/debug.py", line 76, in sensitive_post_parameters_wrapper
return view(request, *args, **kwargs)
Exception Type: TypeError at /admin/auth/user/1/password/
Exception Value: user_change_password() got an unexpected keyword argument 'extra_context'
How can I localize this problem?
What's happening...
I have no idea tbh. It is worth noting a few things though, that the url, should call a method in the User Auth ModelAdmin at django/contrib/auth/admin called user_change_password. It has the following signature:
def user_change_password(self, request, id, form_url=""):
which is why the error is being raised, because somehow extra_context is being passed to it.
There is also a way for you to change the logged on users password, which does accept a extra_context kwarg. My best guess is that one of the apps has overwritten the standard auth ModelAdmin and done it not quite right. Certainly everything works fine with a fresh django 3.0.7 project.
How can I localize this problem?
I would remove all of your additional apps. Hopefully this will fix the problem. If it doesn't then this becomes more interesting. But if it does, I would add them back in one by one until it breaks, and then you'll figure out which additional app is breaking things.
maybe you even can help me cope with it.
There's a few things I can think of that you could do if you just want to change the password. You can change user details via the shell:
python manage.py shell
Then the following will enable you to change a password:
from auth.models import User
user = User.objects.get(id=1) # Or whatever user you want
user.set_password('my_new_password')
user.save()
This should do the trick. Even easier still, there is a management command that does it (but for this you will need to know the current password). You can simply run:
manage.py changepassword *username*
I had this issue (though in Django 2.2). It started after I took the advice from another Stack Overflow post on adding extra_context to every admin page. This seems harmless, but breaks the "change password" form. In the end I deleted the 'extra_context' changes to urls.py and added the extra_context ONLY to the admin forms I needed using the ModelAdmin add_view and change_view methods.
# New Layer Form
def add_view(self, request, form_url='', extra_context={}):
extra_context['CATALOG_TECHNOLOGY'] = settings.CATALOG_TECHNOLOGY
return super(LayerAdmin, self).add_view(request, form_url, extra_context)
# Edit Layer Form
def change_view(self, request, object_id, extra_context={}):
extra_context['CATALOG_TECHNOLOGY'] = settings.CATALOG_TECHNOLOGY
return super(LayerAdmin, self).change_view(request, object_id, extra_context=extra_context)
Here are the commits for full context:
Breaking Commit
urls.py
Fixing Commits
urls.py
admin.py

wagtail pathoverflow on adding new child page

I have developed a wagtail site and that works just fine. It's just a simple blog. I was able to add a blog index page and blog posts under them. Hover recently when try to add a new page it gives the error
PathOverflow at /admin/pages/add/blog/blogpage/8/
Bellow is the complete traceback.
Environment:
Request Method: POST
Request URL: https://vikatakavi.info/admin/pages/add/blog/blogpage/8/
Django Version: 2.1.5
Python Version: 3.5.2
Installed Applications:
['home',
'search',
'wagtail.contrib.forms',
'wagtail.contrib.redirects',
'wagtail.embeds',
'wagtail.sites',
'wagtail.users',
'wagtail.snippets',
'wagtail.documents',
'wagtail.images',
'wagtail.search',
'wagtail.admin',
'wagtail.core',
'modelcluster',
'taggit',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sitemaps',
'blog']
Installed Middleware:
['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',
'django.middleware.security.SecurityMiddleware',
'wagtail.core.middleware.SiteMiddleware',
'wagtail.contrib.redirects.middleware.RedirectMiddleware']
Traceback:
File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/wagtail/admin/urls/__init__.py" in wrapper
102. return view_func(request, *args, **kwargs)
File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/wagtail/admin/decorators.py" in decorated_view
34. return view_func(request, *args, **kwargs)
File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/wagtail/admin/views/pages.py" in create
224. parent_page.add_child(instance=page)
File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/treebeard/mp_tree.py" in add_child
1013. return MP_AddChildHandler(self, **kwargs).process()
File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/treebeard/mp_tree.py" in process
387. newobj.path = self.node.get_last_child()._inc_path()
File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/treebeard/mp_tree.py" in _inc_path
1114. raise PathOverflow(_("Path Overflow from: '%s'" % (self.path, )))
Exception Type: PathOverflow at /admin/pages/add/blog/blogpage/8/
Exception Value: Path Overflow from: '000100010005ZZZZ'
I'm absolutely clueless on this.
To store a page's position in the page tree, Wagtail uses a technique called Materialized Path, which (in its standard settings) allows a maximum of 1679615 insertions at a particular point in the tree. It seems that you've hit this limit somehow. (The position at each point in the tree is represented as a 4-character alphanumeric code; the 'ZZZZ' as seen in the error message is the highest available code.)
You would run into this limit if you had >1.6 million blog posts, but obviously that's quite unlikely. A more likely possibility is that you've written an import or maintenance script that's performing a very large number of insertions or page movements - for example, if you had a script to randomly reorder pages, and you were running it on a section with 10000 pages, you would run out of index numbers after running it ~160 times.
If you really can't avoid hitting this limit, then you can increase the limit to 60 million by adding the following code somewhere where it will run on startup:
from wagtail.core.models import Page
Page.steplen = 5
However, this won't work on an existing database - you'll need to delete and recreate your database after making this change - and it means the maximum possible depth of the tree is reduced from 63 levels to 50.

Django says OverflowError at /admin/ while trying to access /admin/

I noticed this error while trying to access /admin/. Whenever /admin/model_name or /admin/ or /admin/* is accessed django says OverflowError at /admin/ and regular expression code size limit exceeded. I did a little digging and came across this SO post. I have checked urls.py of app since regex are mostly used in urls. But all I have is a typical admin url, nothing complex.
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
....
]
Stack trace
Environment:
Request Method: GET
Request URL: http://domain/admin/
Django Version: 1.9.8
Python Version: 2.7.6
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'haystack',
'myapp.apps.core',
'myapp.apps.home',
'myapp.apps.accounts',
'myapp.apps.dashboard',
'myapp.apps.app1',
'myapp.apps.app3',
'myapp.apps.app5',
'myapp.apps.app6',
'myapp.apps.app7',
'myapp.apps.app8',
'myapp.apps.app9']
Installed 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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in wrapper
265. return self.admin_view(view, cacheable)(*args, **kwargs)
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
244. return view(request, *args, **kwargs)>
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)>
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in index
505. app_list = self.get_app_list(request)>
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in get_app_list
488. app_dict = self._build_app_dict(request)>
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in _build_app_dict
473. current_app=self.name,
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/core/urlresolvers.py" in reverse
600. return force_text(iri_to_uri(resolver._revers>e_with_prefix(view, prefix, *args, **kwargs)))
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/core/urlresolvers.py" in _reverse_with_prefix>
488. if re.search('^%s%s' % (re.escape(_prefix), pattern), candidate_pat % candidate_subs, re.UNICODE):
File "/usr/lib/python2.7/re.py" in search>
142. return _compile(pattern, flags).search(string)
File "/usr/lib/python2.7/re.py" in _compile>
242. p = sre_compile.compile(pattern, flags)
File "/usr/lib/python2.7/sre_compile.py" in compile
521. groupindex, indexgroup
Exception Type: OverflowError at /admin/
Exception Value: regular expression code size limit exceeded
We are using django+apache.
Any help is much appreciated.
TIA
I have managed to solve this by restarting apache2 with
sudo service apache2 restart.
Of course, I have inspected apache2 error log with
sudo tail-f /var/logs/apache2/error.log
But that gave me same output as stack trace. Aforementioned is a work around for this issue. I am not marking this question as solved since real issue have not been found yet.
Thanks.

Django 1.9: 'AnonymousUser' object is not iterable

I was working on a Django 1.9 project, and suddenly this error popped up when I attempted to view my site's home page as a logged-out user.
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.9.7
Python Version: 2.7.10
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.sites',
'django.contrib.staticfiles',
'captcha',
'debug_toolbar',
'django_extensions',
'djstripe',
'crm',
'launch',
'rentals',
'widget_tweaks']
Installed Middleware:
[u'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
174. response = self.process_exception_by_middleware(e, request)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
172. response = response.render()
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/template/response.py" in render
160. self.content = self.rendered_content
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/template/response.py" in rendered_content
137. content = template.render(context, self._request)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/template/backends/django.py" in render
95. return self.template.render(context)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/template/base.py" in render
204. with context.bind_template(self):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py" in __enter__
17. return self.gen.next()
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/debug_toolbar/panels/templates/panel.py" in _request_context_bind_template
79. context = processor(self.request)
File "/Users/me/projects/rentalguru/src/rentals/processors.py" in allCategories
4. expense_categories = ExpenseCategory.objects.filter(user=request.user)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
122. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/query.py" in filter
790. return self._filter_or_exclude(False, *args, **kwargs)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/query.py" in _filter_or_exclude
808. clone.query.add_q(Q(*args, **kwargs))
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/sql/query.py" in add_q
1243. clause, _ = self._add_q(q_object, self.used_aliases)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/sql/query.py" in _add_q
1269. allow_joins=allow_joins, split_subq=split_subq,
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/sql/query.py" in build_filter
1174. self.check_related_objects(field, value, opts)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/sql/query.py" in check_related_objects
1073. for v in value:
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/utils/functional.py" in inner
205. return func(self._wrapped, *args)
Exception Type: TypeError at /
Exception Value: 'AnonymousUser' object is not iterable
I'm not sure what would be causing this, and there's only one Google search result (for this site) for this error. I searched the code for the is_authenticated() method and didn't find anything, so I'm unsure where to turn. Working through the stack trace didn't show any useful (for me) information.
Here is my view:
class HomePageView(TemplateView):
template_name = 'home.html'
No login decorators or wrapped functions that I can tell.
Let me know if I need to post anything else.
EDIT: Asked for the model, here is the offending context processor instead:
def allCategories(request):
expense_categories = ExpenseCategory.objects.filter(user=request.user)
tags = {'categories': expense_categories}
return tags
I just stumbled myself upon this error. Thankfully the answer was provided in the comments:
As you said you tried to view home page with logged out user and this ExpenseCategory.objects.filter(user=request.user) filtering of Anonymous user (because you are logged out now) seems to be the culprit. Either you should allow only a authenticated user to this view or handle the case where your user is Anonymous
As for myself, I had a view, where I was filtering on a model based on the current user, which apparantly fails, when the user is the AnonymousUser.
I fixed this by adding a check:
if request.user.is_active:
expense_categories = ExpenseCategory.objects.filter(user=request.user)
Note that some people seem to prefer to check request.user.is_authenticated instead.
If you are dealing with a view that shall be accessed by logged in users only, you can also use the #login_required decorator.
For reference:
https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User.is_active
https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User.is_authenticated
https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.decorators.login_required

Getting 403 Forbidden when using Oauth2.0

I am using "Oauth2.0" to access YouTube data API.
the site is hosted on a Django platform, its address is http://listplay1.pythonanywhere.com/
Every time I'd like to authorize myself I refresh the access token and use the new one to get access.
Most of the time it works flawlessly but sometimes I get 403 Forbidden error. when I do the same from the terminal on my pc it works always
Can anyone have an idea in regards to how is it happening only part of the time and more importantly, how to fix it?
Thanks a mill in advance,
*the $$$ parts are hidden on purpose of course.
def auth():
h={'Host':'accounts.google.com','Content-Type':'application/x-www-form-urlencoded','X-GData-Key':'key=$$$'}
content={'client_id':'567194806765-r1pdllkji4tpgv1dc0a9ihrvh0hocoik.apps.googleusercontent.com','client_secret':'$$$','refresh_token':'$$$','grant_type':'refresh_token'}
p=urllib.urlencode(content)
r = requests.post('https://accounts.google.com/o/oauth2/token', data=p,headers=h)
token=r.json().values()[0]
credentials = AccessTokenCredentials(token,'my-user-agent/1.0')
return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,http=credentials.authorize(httplib2.Http()))
and the error
Environment:
Request Method: GET
Request URL: http://listplay1.pythonanywhere.com/thanks/
Django Version: 1.3.7
Python Version: 2.7.5
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'main.myapp']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "./main/myapp/views.py" in thanks
64. Pid=create_playlist(YT="",title=TITLE)
File "/home/LISTPLAY1/LISTPLAY/listplay.py" in create_playlist
261. YT=auth()
File "/home/LISTPLAY1/LISTPLAY/listplay.py" in auth
257. return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,http=credentials.authorize(httplib2.Http()))
File "/home/LISTPLAY1/LISTPLAY/oauth2client/util.py" in positional_wrapper
132. return wrapped(*args, **kwargs)
File "/home/LISTPLAY1/LISTPLAY/apiclient/discovery.py" in build
192. resp, content = http.request(requested_url)
File "/home/LISTPLAY1/LISTPLAY/oauth2client/util.py" in positional_wrapper
132. return wrapped(*args, **kwargs)
File "/home/LISTPLAY1/LISTPLAY/oauth2client/client.py" in new_request
490. redirections, connection_type)
File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py" in request
1570. (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py" in _request
1317. (response, content) = self._conn_request(conn, request_uri, method, body, headers)
File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py" in _conn_request
1252. conn.connect()
File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py" in connect
1018. sock.connect((self.host, self.port))
File "/usr/local/lib/python2.7/dist-packages/httplib2/socks.py" in connect
424. self.__negotiatehttp(destpair[0], destpair[1])
File "/usr/local/lib/python2.7/dist-packages/httplib2/socks.py" in __negotiatehttp
390. raise HTTPError((statuscode, statusline[2]))
Exception Type: HTTPError at /thanks/
Exception Value: (403, 'Forbidden')