Getting 403 Forbidden when using Oauth2.0 - django

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')

Related

How to fix social_core.exceptions.AuthMissingParameter error

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.

UnicodeDecodeError with Python 2.7 and suds 4.0 with German language

I have a python-django project and I am trying to save German and Italian in my Postgresql database which is used only by this project. I am trying to send the results I want to save in database through an Html Form that I have added:
accept-charset="UTF-8"
The results are send to my views.py in which I have added on the top
#!/usr/bin/env python
# -*- coding: utf-8 -*-
I have also tried to encode,decode inside views.py into utf-8, ISO-5589-1, latin-1 but it is not working. I believe the error has to do with this article but I don't understand the solution they say the bug is fixed but still not working for me.
https://fedorahosted.org/suds/ticket/361
This is my traceback:
Environment:
Request Method: POST
Django Version: 1.4
Python Version: 2.7.2
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'ui')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.locale.LocaleMiddleware')
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 "/home/hatzimin/web/indivo_ui_server/apps/problems/views.py" in new_problem
281. content_type='application/xml')
File "/home/hatzimin/web/indivo_ui_server/indivo_client_py/client.py" in __call__
154. return func(self.url, *args, **kwargs)
File "/home/hatzimin/web/indivo_ui_server/indivo_client_py/client.py" in post
68. return self.request(self.api_base+uri, uri_params, method="POST", body=body, headers=headers)
File "/home/hatzimin/web/indivo_ui_server/indivo_client_py/client.py" in request
132. return super(IndivoClient, self).request(uri, *args, **kwargs)
File "/home/hatzimin/web/indivo_ui_server/indivo_client_py/oauth2/__init__.py" in request
697. connection_type=connection_type)
File "/home/hatzimin/web/indivo_ui_server/indivo_client_py/oauth2/httplib2/__init__.py" in request
1544. (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
File "/home/hatzimin/web/indivo_ui_server/indivo_client_py/oauth2/httplib2/__init__.py" in _request
1294. (response, content) = self._conn_request(conn, request_uri, method, body, headers)
File "/home/hatzimin/web/indivo_ui_server/indivo_client_py/oauth2/httplib2/__init__.py" in _conn_request
1231. conn.request(method, request_uri, body, headers)
File "/usr/lib/python2.7/httplib.py" in request
955. self._send_request(method, url, body, headers)
File "/usr/lib/python2.7/httplib.py" in _send_request
989. self.endheaders(body)
File "/usr/lib/python2.7/httplib.py" in endheaders
951. self._send_output(message_body)
File "/usr/lib/python2.7/httplib.py" in _send_output
809. msg += message_body
Exception Type: UnicodeDecodeError at /apps/problems/problems/new
Exception Value: 'ascii' codec can't decode byte 0xc3 in position 207: ordinal not in range(128)
Probably suds is returning string of type 'str' encoded in utf-8. You should convert this string to type 'unicode' before working with it.
Try invoking django.utils.encoding.smart_unicode on it right after you receive the string from suds.

iterator should return strings, not bytes (did you open the file in text mode?) while uploading csv in django

I want to upload csv file and store in database. when I click the submit button I get the following error
Environment:
Request Method: POST
Request URL: http://localhost:8000/csv
Django Version: 1.9
Python Version: 3.4.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'django.contrib.admindocs',
'world',
'pft',
'wms',
'djgeojson',
'html5',
'geoexplorer']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python34\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "C:\Python34\Lib\site-packages\django\bin\geodjango\pft\views.py" in add_multiple_accounts
95. csv_result, rows_error = utils.handle_uploaded_file(file, utils.account_valid_fields, utils.create_account_in_db)
File "C:\Python34\Lib\site-packages\django\bin\geodjango\pft\utils.py" in handle_uploaded_file
24. if not valid_fields_method(data.fieldnames):
File "C:\Python34\lib\csv.py" in fieldnames
96. self._fieldnames = next(self.reader)
Exception Type: Error at /csv
Exception Value: iterator should return strings, not bytes (did you open the file in text mode?)
my handle file upload function is below-utils.py
def handle_uploaded_file(file, valid_fields_method, record_creation_function):
file.seek(0)
sniffdialect = csv.reader(codecs.iterdecode(file, 'utf-8')
file.seek(0)
data = csv.DictReader(file, dialect=sniffdialect)
if not valid_fields_method(data.fieldnames):
return False, -1
result, rows_error = record_creation_function(data)
return result, rows_error
I'm using django 1.9 and python 3.4. Please help ! I'm struggling for past 2 days.
TL;DR:
Change this:
file.seek(0)
sniffdialect = csv.reader(codecs.iterdecode(file, 'utf-8')
file.seek(0)
data = csv.DictReader(file, dialect=sniffdialect)
To this:
file.seek(0)
data = csv.DictReader(codecs.iterdecode(file, 'utf-8'))
(By the way, I'd check if seek(0) is really needed.)
Explanation:
You have understood that you need to decode the contents from your file, which is correct. However, to do so, you are using dialect, which is wrong.
dialect is not meant for this kind of stuff. Also, it should be a name registered via csv.register_dialect(), not an arbitrary iterator. But anyhow, dialects can't help you here.
Instead, you should pass the decoded stream directly to DictReader.

ConnectionError in Djrill after upgrading to Mac OSX 10.10.5

I just upgraded to Mac OSX 10.10.5 today and now I get a ConnectionError every time I try to send an email locally in GAE using the djrill Django app.
Exception Type: ConnectionError
Exception Value: ('Connection aborted.', error(22, 'Invalid argument'))
I've received this error prior to 10.10.5, but included the following code at the top of my views.py as a workaround.
import imp
import os.path
from google.appengine.tools.devappserver2.python import sandbox
sandbox._WHITE_LIST_C_MODULES += ['_ssl', '_socket']
# Use the system socket.
psocket = os.path.join(os.path.dirname(os.__file__), 'socket.py')
imp.load_source('socket', psocket)
But now if I attempt to execute the following block of code after upgrading to 10.10.5, I encounter the error.
msg = EmailMultiAlternatives(
to=['user#domain.com'],
subject='TEST',
from_email='Admin <admin#projectname.appspotmail.com>',
)
msg.template_name = "template-name"
msg.send()
Here's the full traceback:
Request Method: GET
Request URL: http://localhost:16080/
Django Version: 1.4.13
Python Version: 2.7.10
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'<projectapp>',
'djrill')
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 "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django-1.4/django/core/handlers/base.py" in get_response
109. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/<username>/<projectname>/order_manager/views.py" in _decorated
53. return view_func(request)
File "/Users/<username>/<projectname>/order_manager/views.py" in select_job
102. msg.send()
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django-1.4/django/core/mail/message.py" in send
248. return self.get_connection(fail_silently).send_messages([self])
File "/Users/<username>/<projectname>/djrill/mail/backends/djrill.py" in send_messages
68. sent = self._send(message)
File "/Users/<username>/<projectname>/djrill/mail/backends/djrill.py" in _send
107. response = requests.post(api_url, data=json.dumps(api_params, cls=JSONDateUTCEncoder))
File "/Users/<username>/<projectname>/requests/api.py" in post
109. return request('post', url, data=data, json=json, **kwargs)
File "/Users/<username>/<projectname>/requests/api.py" in request
50. response = session.request(method=method, url=url, **kwargs)
File "/Users/<username>/<projectname>/requests/sessions.py" in request
470. resp = self.send(prep, **send_kwargs)
File "/Users/<username>/<projectname>/requests/sessions.py" in send
578. r = adapter.send(request, **kwargs)
File "/Users/<username>/<projectname>/requests/adapters.py" in send
410. raise ConnectionError(err, request=request)
Exception Type: ConnectionError at /
Exception Value: ('Connection aborted.', error(22, 'Invalid argument'))
I appreciate any advice on how to once again send emails from my GAE local server using djrill after upgrading to OSX 10.10.5. Thanks!
I was troubleshooting a seemingly unrelated issue and stumbled across a suitable workaround. I replaced the latest version of the python requests module in my App Engine project with version 2.3.

Some cache problems

I'm wondering if I can delete a cached content made in template cache. I want to delete it from my view. I have in my template {% cache 500 cache_name sites.number %}
Is it possible to delete all "cache_name" cached content within the view, for example when some action is made?
I want to use per-vie cache. I do all what is described, but when I call: #cache_page(3600, cache="cache_name") I get error:
Exception Type: ValueError Exception
Value: need more than 1 value to
unpack
(Below is the traceback)
What I want to achieve is to cache all my template block or view and have a possibility to delete all cache connected with it when some actions are made. Pagination is included
Traceback:
Environment:
Request Method: GET
Request URL: http://localhost:8000/portfolio/
Django Version: 1.3 beta 1 SVN-15661
Python Version: 2.7.1
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'apps.index']
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 "E:\Python\django\core\handlers\base.py" in get_response
101. request.path_info)
File "E:\Python\django\core\urlresolvers.py" in resolve
252. sub_match = pattern.resolve(new_path)
File "E:\Python\django\core\urlresolvers.py" in resolve
252. sub_match = pattern.resolve(new_path)
File "E:\Python\django\core\urlresolvers.py" in resolve
158. return ResolverMatch(self.callback, args, kwargs, self.name)
File "E:\Python\django\core\urlresolvers.py" in _get_callback
164. self._callback = get_callable(self._callback_str)
File "E:\Python\django\utils\functional.py" in wrapper
124. result = func(*args)
File "E:\Python\django\core\urlresolvers.py" in get_callable
91. lookup_view = getattr(import_module(mod_name), func_name)
File "E:\Python\django\utils\importlib.py" in import_module
35. __import__(name)
File "E:\Python\apps\index\views.py" in <module>
29. #cache_page(600, cache='my_cache')
File "E:\Python\django\views\decorators\cache.py" in cache_page
58. return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], cache_alias=cache_alias, key_prefix=key_prefix)
File "E:\Python\django\utils\decorators.py" in _make_decorator
81. middleware = middleware_class(*m_args, **m_kwargs)
File "E:\Python\django\middleware\cache.py" in __init__
204. self.cache = get_cache(self.cache_alias, **cache_kwargs)
File "E:\Python\django\core\cache\__init__.py" in get_cache
173. backend, location, params = parse_backend_conf(backend, **kwargs)
File "E:\Python\django\core\cache\__init__.py" in parse_backend_conf
131. mod_path, cls_name = backend.rsplit('.', 1)
Exception Type: ValueError at /portfolio/
Exception Value: need more than 1 value to unpack
What version of Django are you using? The parameter "cache" is only available in the development version. If you're using Django 1.2, you can only use "key_prefix".
http://docs.djangoproject.com/en/1.2/topics/cache/
The cache middleware caches every page
that doesn't have GET or POST
parameters.