While using the example app of the django social-auth the user can login to the social accounts but when they are redirected back to our portal it gives a value error Missing backend entry.
Actual error:
[01/Nov/2013 15:49:21] "GET /login/twitter/ HTTP/1.1" 302 0
[01/Nov/2013 15:49:25] "GET /complete/twitter/?oauth_token=ZETJZMsQQhdWzawgrt8xI
9DMEfyCb2N8jpXkVpYfC8&oauth_verifier=zmIXXCAfa2foLolK1v8PIBMQLlrQD6uEYiJ8fwjT14HTTP/1.1" 302 0
Internal Server Error: /login/error/
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\python_social_auth-0.1.14py2.7.egg\social\apps\django_app\utils.py", line 31, in wrapper
redirect_uri=uri, *args, **kwargs)
File "..\social_auth\views.py", line 19, in load_strategy
return get_strategy(BACKENDS, STRATEGY, STORAGE, *args, **kwargs)
File "C:\Python27\lib\site-packages\python_social_auth-0.1.14-py2.7.egg\social\strategies\utils.py", line 10, in get_strategy
raise ValueError('Missing backend entry')ValueError: Missing backend entry
Related
I'm building a Django app with Django Rest Framework to host it on my organisation's domain. The domain implements a custom authentication protocol. When someone accesses the domain, say to app1.domainname.com, they are redirected to the organisation's login page (login.domainname.com) and they have to log in with their staff account. After the user is authenticated, the user is redirected back to their initial destination (app1.domain.com). The information of the user is then stored in some custom header fields of the HTTP request sent to the app. E.g.
GET / HTTP/2
Content-Type:
User-Agent: ...
...
X-Username: johndoe1
X-Firstname: John
X-Lastname: Doe
X-Email: johndoe#domainname.com
etc.
I'm trying to implement custom permission for my REST API that looks for these fields in the headers, and then authorise the user based on their user information. This is what I'm currently having:
from rest_framework.permissions import BasePermission
allowed = ['johndoe1', 'dicksmith2', 'username3']
class CutomPerm(BasePermission):
message = "You don't have permission to access this object"
def has_object_permission(self, request, view, obj):
print(request.headers)
username = request.headers['X-Username']
return username in allowed
But when I run the server, it seems like the custom headers are passed through to the backend. For some requests they are, but ultimately the user is not authorised because the has_object_permission method raises a KeyError:
[10/Mar/2020 10:03:29] "GET /api/obj/ HTTP/1.1" 200 81
[10/Mar/2020 10:03:29] "GET /favicon.ico/ HTTP/1.1" 200 11
{'Content-Length': '', 'Content-Type': 'text/plain', 'Host': 'localhost:8000', 'Connection': 'keep-alive', etc., 'X-Username': 'johndoe1', 'X-Firstname': 'John', etc.}
Forbidden: /api/obj/1/
[10/Mar/2020 10:04:35] "GET /api/obj/1/ HTTP/1.1" 403 6581
{'Content-Length': '', 'Content-Type': 'text/plain', 'Host': 'localhost:8000', 'Connection': 'keep-alive', etc.} # no custom headers here
[10/Mar/2020 10:04:35] "GET /favicon.ico/ HTTP/1.1" 200 11
Internal Server Error: /api/obj/1/
Traceback (most recent call last):
File "/path/to/project/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/path/to/project/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 "/path/to/project/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 "/path/to/project/venv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/path/to/project/venv/lib/python3.8/site-packages/rest_framework/viewsets.py", line 114, in view
return self.dispatch(request, *args, **kwargs)
File "/path/to/project/venv/lib/python3.8/site-packages/rest_framework/views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "/path/to/project/venv/lib/python3.8/site-packages/rest_framework/views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "/path/to/project/venv/lib/python3.8/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
raise exc
File "/path/to/project/venv/lib/python3.8/site-packages/rest_framework/views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "/path/to/project/venv/lib/python3.8/site-packages/rest_framework/mixins.py", line 54, in retrieve
instance = self.get_object()
File "/path/to/project/venv/lib/python3.8/site-packages/rest_framework/generics.py", line 99, in get_object
self.check_object_permissions(self.request, obj)
File "/path/to/project/venv/lib/python3.8/site-packages/rest_framework/views.py", line 343, in check_object_permissions
if not permission.has_object_permission(request, self, obj):
File "/path/to/project/project/app/permissions.py", line 11, in has_object_permission
username = request.headers['X-Username']
File "/path/to/project/venv/lib/python3.8/site-packages/django/http/request.py", line 388, in __getitem__
return super().__getitem__(key.replace('_', '-'))
File "/path/to/project/venv/lib/python3.8/site-packages/django/utils/datastructures.py", line 320, in __getitem__
return self._store[key.lower()][1]
KeyError: 'X-Username'
Note that in the 2 header dictionaries printed out, the first one has all the custom headers but the second one doesn't.
I think this is because there are some redirecting happening behind the scene and the final request that gets to the rest framework permission check has lost all of its custom headers. Is there anyway to check for permissions based on the custom headers?
Thanks
Django modifies the http header keys.
You have to access the header as:
username = request.META.get('HTTP_X_USERNAME', None)
if username:
# your logic
pass
checkout Django header docs:
https://docs.djangoproject.com/en/3.0/ref/request-response/#django.http.HttpRequest.META
the final line in this Python code:
from firebase_admin import credentials, initialize_app
from firebase_admin import auth as firebaseAuth
_cred = credentials.Certificate('common/auth/touchstone-firebase-adminsdk-4a750c3d1c53.json')
tsFirebaseApp = initialize_app(_cred)
decoded_token_dict = firebaseAuth.verify_id_token(id_token, tsFirebaseApp)
is throwing this stack trace & I can't find anything explaining it....
ERROR 2017-07-30 20:10:15,986 service.py:191] Encountered unexpected error from ProtoRPC method implementation: TransportError (('Connection aborted.', error(22, 'Invalid argument')))
Traceback (most recent call last):
File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/lib/protorpc-1.0/protorpc/wsgi/service.py", line 181, in protorpc_service_app
response = method(instance, request)
File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/lib/endpoints-1.0/endpoints/api_config.py", line 1331, in invoke_remote
return remote_method(service_instance, request)
File "/Users/dgaedcke/gcloud_tools/google-cloud-sdk/platform/google_appengine/lib/protorpc-1.0/protorpc/remote.py", line 414, in invoke_remote_method
response = method(service_instance, request)
File "/Users/dgaedcke/dev/TouchstoneMicroservices/lib/ferris3/endpoints.py", line 232, in inner
return_val = func(self, request, **kwargs)
File "/Users/dgaedcke/dev/TouchstoneMicroservices/service_backend/user_service.py", line 80, in createOrLoadUser
user, appSettings, err = processUserSignupOrSignin(access_token, request.idpProfileAtts)
File "/Users/dgaedcke/dev/TouchstoneMicroservices/common/auth/login.py", line 38, in processUserSignupOrSignin
firUserAsDict, err = userFromJwTokenIfValid(access_token)
File "/Users/dgaedcke/dev/TouchstoneMicroservices/common/auth/login.py", line 60, in userFromJwTokenIfValid
decoded_token_dict = firebaseAuth.verify_id_token(id_token)
File "/Users/dgaedcke/dev/TouchstoneMicroservices/lib/firebase_admin/auth.py", line 98, in verify_id_token
return token_generator.verify_id_token(id_token)
File "/Users/dgaedcke/dev/TouchstoneMicroservices/lib/firebase_admin/auth.py", line 277, in verify_id_token
audience=project_id)
File "/Users/dgaedcke/dev/TouchstoneMicroservices/lib/google/oauth2/id_token.py", line 115, in verify_firebase_token
id_token, request, audience=audience, certs_url=_GOOGLE_APIS_CERTS_URL)
File "/Users/dgaedcke/dev/TouchstoneMicroservices/lib/google/oauth2/id_token.py", line 76, in verify_token
certs = _fetch_certs(request, certs_url)
File "/Users/dgaedcke/dev/TouchstoneMicroservices/lib/google/oauth2/id_token.py", line 50, in _fetch_certs
response = request(certs_url, method='GET')
File "/Users/dgaedcke/dev/TouchstoneMicroservices/lib/google/auth/transport/requests.py", line 115, in __call__
raise exceptions.TransportError(exc)
TransportError: ('Connection aborted.', error(22, 'Invalid argument'))
INFO 2017-07-30 20:10:15,999 module.py:832] default: "POST /_ah/spi/UserService.createOrLoadUser HTTP/1.1" 500 512
INFO 2017-07-30 20:10:15,999 module.py:832] default: "POST /_ah/api/tstone/v1/user/createOrLoadUser?prettyPrint=false HTTP/1.1" 503 196
I've properly created a service key, downloaded and imported the associated .json config file, and initialized the tsFirebaseApp with the credentials.
I'm not sure what else to try?
Somehow I receive 503 error report related to Google Social Login. Does it mean Google occasionally broke down? I have a hard time to reproduce it on either development server or production server.
Internal Server Error: /accounts/google/login/callback/
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 132, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/allauth/socialaccount/providers/oauth2/views.py", line 55, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/allauth/socialaccount/providers/oauth2/views.py", line 116, in dispatch
response=access_token)
File "/usr/local/lib/python2.7/dist-packages/allauth/socialaccount/providers/google/views.py", line 20, in complete_login
resp.raise_for_status()
File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 840, in raise_for_status
raise HTTPError(http_error_msg, response=self)
HTTPError: 500 Server Error: Internal Server Error for url: https://www.googleapis.com/oauth2/v1/userinfo?access_token=xxxx&alt=json
Environment:
Django==1.8.8
django-allauth==0.24.1
I have a Django REST server which I updated recently from using Python 2.7 to 3.4. The server uses Django REST framework on top of Django, with django-allauth and django-rest-auth for Facebook login support.
Now, after the update, I cannot login to the server with Facebook anymore. When I send a POST to the server, I get the following error:
Internal Server Error: /rest-auth/facebook/
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\django\core\handlers\base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python34\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs)
File "C:\Python34\lib\site-packages\rest_framework\views.py", line 452, in dispatch response = self.handle_exception(exc)
File "C:\Python34\lib\site-packages\rest_framework\views.py", line 449, in dispatch response = handler(request, *args, **kwargs)
File "C:\Python34\lib\site-packages\rest_auth\views.py", line 51, in post if not self.serializer.is_valid():
File "C:\Python34\lib\site-packages\rest_framework\serializers.py", line 187, in is_valid self._validated_data = self.run_validation(self.initial_data)
File "C:\Python34\lib\site-packages\rest_framework\serializers.py", line 370, in run_validation value = self.validate(value)
File "C:\Python34\lib\site-packages\rest_auth\registration\serializers.py", line 31, in validate token.account = login.account
File "C:\Python34\lib\site-packages\django\db\models\fields\related.py", line 668, in __set__ (value, self.field.rel.to._meta.object_name)
File "C:\Python34\lib\site-packages\django\db\models\base.py", line 496, in __repr__ u = six.text_type(self)
File "C:\Python34\lib\site-packages\allauth\socialaccount\models.py", line 104, in __str__ return force_text(self.user)
File "C:\Python34\lib\site-packages\django\db\models\fields\related.py", line 608, in __get__ "%s has no %s." % (self.field.model.__name__, self.field.name)
django.db.models.fields.related.RelatedObjectDoesNotExist: SocialAccount has no user.
[13/Apr/2015 08:53:30]"POST /rest-auth/facebook/ HTTP/1.1" 500 115908
What could be causing this? I have done no changes to the code after updating Python and the libraries, and it worked before the update. I deleted the old database and created a new one via syncdb but it didn't help.
Thanks in advance.
RelatedObject has been removed in Django 1.8 in favour of ForeignObjectRel. Source
The allauth version you are using does not support Django 1.8.
I am making a Hacker News Clone in Django as taught in a Tuts+ Course [Git Repo]
In views.py file, for vote view, I tried using this code to increase security by checking if user has liked the story already.
#login_required
def vote(request):
story = get_object_or_404(Story, pk=request.POST.get('story'))
user = request.user
if user.is_authenticated() and story not in user.liked_stories:
story.points += 1
story.save()
user.liked_stories.add(story)
user.save()
return HttpResponse()
But it gives me this Error:
NameError: global name 'liked_stories' is not defined
[18/Aug/2013 19:26:43] "POST /vote/ HTTP/1.1" 500 11148
I am able to use user.liked_stories in index view so why not in vote view?
Error:
Internal Server Error: /vote/
Traceback (most recent call last):
File "/home/sourabh/.virtualenvs/django/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/home/sourabh/.virtualenvs/django/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 25, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/sourabh/Code/django_apps/HackerNews/stories/views.py", line 53, in vote
if user.is_authenticated() and story not in liked_stories:
NameError: global name 'liked_stories' is not defined
[18/Aug/2013 20:08:35] "POST /vote/ HTTP/1.1" 500 11161
There you go:
if user.is_authenticated() and story not in liked_stories:
In this line the error is thrown. The code you have posted does not resemble the code you are executing.