transport error from firebase admin when try to validate jwt - python-2.7

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?

Related

Django RestFramework JWT Token: Get User DoesNotExist error

After a user is deleted, the tokens on the client side are still valid until the time has expired. The issue is django restframwework does not handle a request from a deleted user and causes a 500. How can I prevent this?
aceback (most recent call last):
File "/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/lib/python3.6/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/lib/python3.6/site-packages/rest_framework/views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "/lib/python3.6/site-packages/rest_framework/views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "/lib/python3.6/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
raise exc
File "/lib/python3.6/site-packages/rest_framework/views.py", line 493, in dispatch
self.initial(request, *args, **kwargs)
File "/lib/python3.6/site-packages/rest_framework/views.py", line 410, in initial
self.perform_authentication(request)
File "/lib/python3.6/site-packages/rest_framework/views.py", line 324, in perform_authentication
request.user
File "/lib/python3.6/site-packages/rest_framework/request.py", line 220, in user
self._authenticate()
File "/lib/python3.6/site-packages/rest_framework/request.py", line 373, in _authenticate
user_auth_tuple = authenticator.authenticate(self)
File "/lib/python3.6/site-packages/rest_framework_jwt/authentication.py", line 33, in authenticate
payload = jwt_decode_handler(jwt_value)
File "/lib/python3.6/site-packages/rest_framework_jwt/utils.py", line 105, in jwt_decode_handler
secret_key = jwt_get_secret_key(unverified_payload)
File "/lib/python3.6/site-packages/rest_framework_jwt/utils.py", line 26, in jwt_get_secret_key
user = User.objects.get(pk=payload.get('user_id'))
File "/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/lib/python3.6/site-packages/django/db/models/query.py", line 431, in get
self.model._meta.object_name
From the JWT token, you are decoding it to get the user_id - payload['user_id'].
The error is happening because of User.objects.get(pk=payload.get('user_id')).
Instead of doing a get, you could use a get_object_or_404. Use it like so:
from django.shortcuts import get_object_or_404
payload = jwt_decode_handler(jwt_value)
user = get_object_or_404 (User, pk=payload.get('user_id'))
This raises a 404 error when a user will not be found; and that will be bubbled up through your view and handlers to return a 404 statuscode.
The suggestion by Druhn Bala works but would return a 404 error which isn't ideal for my use case. Instead I came up with one that returns a custom response. ValidationError
from rest_framework.exceptions allows you to send a 400 error with a custom response.
def jwt_decode_handler(token):
options = {
'verify_exp': api_settings.JWT_VERIFY_EXPIRATION,
}
# get user from token, BEFORE verification, to get user secret key
try:
unverified_user = jwt.decode(token, None, False)
except User.DoesNotExist:
raise ValidationError({"errors": ['Oops! Something went wrong, please logout and login back in!']})
secret_key = unverified_user.securitysettings.jwt_secret #my custom way of storing a unique jwt uuid per user.
return jwt.decode(
token,
api_settings.JWT_PUBLIC_KEY or secret_key,
api_settings.JWT_VERIFY,
options=options,
leeway=api_settings.JWT_LEEWAY,
audience=api_settings.JWT_AUDIENCE,
issuer=api_settings.JWT_ISSUER,
algorithms=[api_settings.JWT_ALGORITHM]
)
Lastly we set the custom decode handler as the default in settings.py.
JWT_AUTH = {
'JWT_DECODE_HANDLER':
'registration.decoder.jwt_decode_handler',
...
}

Django Client.get() in TestCase returns TypeError from django.utils.cache

I'm attempting to write a unit test for a url in my application. I used django's Client class to simulate a get() request and compare the response's status code.
Here's the test i'm running:
from unittest.mock import patch
from django.shortcuts import reverse
class DashboardViewTest(TestCase):
#patch("ordering.mixins.OrderingAppPermissionRequired.handle_not_logged_in")
#patch("ordering.mixins.OrderingAppPermissionRequired.handle_no_profile")
#patch("ordering.mixins.OrderingAppPermissionRequired.handle_no_id")
def test_order_list_view(self, *mocks):
client = Client()
response = client.get(reverse('ordering:list'))
self.assertEqual(response.status_code, 200)
I'm facing the following error (path redacted for privacy):
Traceback (most recent call last):
File "[python_root]\python\python37\Lib\unittest\mock.py", line 1191, in patched
return func(*args, **keywargs)
File "[project_root]\ordering\tests\test_dashboard.py", line 20, in test_order_list_view
response = client.get(reverse('ordering:list'))
File "[virtual_env_root]\lib\site-packages\django\test\client.py", line 527, in get
response = super().get(path, data=data, secure=secure, **extra)
File "[virtual_env_root]\lib\site-packages\django\test\client.py", line 339, in get
**extra,
File "[virtual_env_root]\lib\site-packages\django\test\client.py", line 414, in generic
return self.request(**r)
File "[virtual_env_root]\lib\site-packages\django\test\client.py", line 495, in request
raise exc_value
File "[virtual_env_root]\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "[virtual_env_root]\lib\site-packages\django\utils\deprecation.py", line 93, in __call__
response = self.process_response(request, response)
File "[virtual_env_root]\lib\site-packages\django\contrib\sessions\middleware.py", line 45, in process_response
patch_vary_headers(response, ('Cookie',))
File "[virtual_env_root]\lib\site-packages\django\utils\cache.py", line 266, in patch_vary_headers
vary_headers = cc_delim_re.split(response['Vary'])
TypeError: expected string or bytes-like object
Help is appreciated. Thank you.

Json is not serializable in django

def ajax_leave_type_data(request):
pk = request.GET.get('id', None)
is_taken= Leave_Types.objects.filter(user_id=pk)
return HttpResponse(json.dumps(is_taken), content_type='application/json')
Thats the error i am getting everytime please give some solution if anyone face this problem before i tried many ways but unable to solve this Thanks in advance
Internal Server Error: /ajax/leave_ty
Traceback (most recent call last):
File "/mnt/e/Leave_Management/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/mnt/e/Leave_Management/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/mnt/e/Leave_Management/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/mnt/e/L_Management/Leave_Management_App/views.py", line 209, in ajax_leave_type_data
return HttpResponse(json.dumps(is_taken), content_type='application/json')
File "/usr/lib/python3.5/json/__init__.py", line 230, in dumps
return _default_encoder.encode(obj)
File "/usr/lib/python3.5/json/encoder.py", line 198, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python3.5/json/encoder.py", line 256, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python3.5/json/encoder.py", line 179, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <QuerySet [<Leave_Types: Casual leaves>, <Leave_Types: Unpaid leaves>, <Leave_Types: Privilege leaves>, <Leave_Types: Sick leaves>]> is not JSON serializable
[13/Oct/2018 17:07:20] "GET /ajax/leave_ty?id=52&csrfmiddlewaretoken=3Fxb3n2PBMRSYWOgPLgRSWZzvQANFiFLTDihrZJ0HklK02YPU39C7eSGY5su7QKX HTTP/1.1" 500 15445
I would return it using Django's JsonResponse
from django.http import JsonResponse
def ajax_leave_type_data(request):
pk = request.GET.get('id', None)
is_taken= Leave_Types.objects.filter(user_id=pk)
return JsonReponse({'is_taken': is_taken})

Python gmail oauth SSL: CERTIFICATE_VERIFY_FAILED

I'm on arch linux.
Copied the gmail example from: https://developers.google.com/gmail/api/quickstart/python
The code is working well on Ubuntu, but on arch I have this error:
Traceback (most recent call last):
File "gmail.py", line 70, in <module>
main()
File "gmail.py", line 58, in main
credentials = get_credentials()
File "gmail.py", line 46, in get_credentials
credentials = tools.run_flow(flow, store, flags)
File "/usr/lib/python2.7/site-packages/oauth2client/util.py", line 140, in positional_wrapper
return wrapped(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/oauth2client/tools.py", line 231, in run_flow
credential = flow.step2_exchange(code, http=http)
File "/usr/lib/python2.7/site-packages/oauth2client/util.py", line 140, in positional_wrapper
return wrapped(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/oauth2client/client.py", line 2138, in step2_exchange
headers=headers)
File "/usr/lib/python2.7/site-packages/httplib2/__init__.py", line 1609, in request
(response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
File "/usr/lib/python2.7/site-packages/httplib2/__init__.py", line 1351, in _request
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
File "/usr/lib/python2.7/site-packages/httplib2/__init__.py", line 1272, in _conn_request
conn.connect()
File "/usr/lib/python2.7/site-packages/httplib2/__init__.py", line 1059, in connect
raise SSLHandshakeError(e)
httplib2.SSLHandshakeError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)
Tested urllib2 with other https and it's working well.
I have no clue on which could be the problem.

Python Traceback Error

Unable to create a response with this api.I am unable to call the function locu_search('new york'). I get the following error shown below. I am using Komodo as my IDE, this started when I created a new python shell.
import urllib2
import json
local_api = '0d5897aae41eeafbd62ad0815af15cc42b2ed7c0'
def locu_search(query):
api_key = local_api
url = 'https://api.locu.com/v1_0/venue/search/?api_key=' + api_key
locality = query.replace('','%20')
final_url = url + "&locality=" + locality + "&category=restaurant"
json_obj = urllib2.urlopen(final_url)
data = json.load(json_obj)
for item in data['objects']:
print item['name'],item['phone']
locu_search('new york')
The error is listed below:
**Traceback (most recent call last):
File "<console>", line 0, in <module>
File "<console>", line 0, in locu_search
File "c:\python27\lib\urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "c:\python27\lib\urllib2.py", line 437, in open
response = meth(req, response)
File "c:\python27\lib\urllib2.py", line 550, in http_response
'http', request, response, code, msg, hdrs)
File "c:\python27\lib\urllib2.py", line 475, in error
return self._call_chain(*args)
File "c:\python27\lib\urllib2.py", line 409, in _call_chain
result = func(*args)
File "c:\python27\lib\urllib2.py", line 558, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 400: BAD_REQUEST**
400 Bad Request should give you a headsup about the problem , this is basically due to a malformed request and I strongly suspect the culprit is in th line url = 'https://api.locu.com/v1_0/venue/search/?api_key=' + api_key , check if api_key token is invalid or no longer valid.