I try to check with unittests if it is possible to access a certain url without the proper permissions.
When I wrote the test everything worked correctly. I don't know if the error started to occurs after a Django update because I didn't check the test after the update and just started to write new tests which failed. So I checked my old test which is now failing too.
class MemberTestMethods(TestCase):
def setUp(self):
# Create user
user = User.objects.create_user('temp', 'temp#temp.tld', 'temppass')
user.first_name = 'temp_first'
user.last_name = 'temp_last'
user.save()
# login with user
self.client.login(username='temp', password='temppass')
# Create member
member = Member.objects.create(salutation=Member.MR, first_name='Temp', last_name='Temp')
member.save()
def test_member_list_permission(self):
"User should only access member list if view permission is set"
user = User.objects.get(username='temp')
response = self.client.get(reverse('members:list'))
self.assertEqual(response.status_code, 403)
user.user_permissions.add(Permission.objects.get(codename='view_member'))
response = self.client.get(reverse('members:list'))
self.assertEqual(response.status_code, 200)
After running python manage.py test I get the following error
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
WARNING:django.request:Forbidden (Permission denied): /de/reporting/
Traceback (most recent call last):
File "/home/***/.virtualenvs/pyVerein/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/***/.virtualenvs/pyVerein/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/***/.virtualenvs/pyVerein/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/***/.virtualenvs/pyVerein/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/home/***/.virtualenvs/pyVerein/lib/python3.6/site-packages/django/contrib/auth/mixins.py", line 52, in dispatch
return super().dispatch(request, *args, **kwargs)
File "/home/***/.virtualenvs/pyVerein/lib/python3.6/site-packages/django/contrib/auth/mixins.py", line 84, in dispatch
return self.handle_no_permission()
File "/home/***/.virtualenvs/pyVerein/lib/python3.6/site-packages/django/contrib/auth/mixins.py", line 43, in handle_no_permission
raise PermissionDenied(self.get_permission_denied_message())
django.core.exceptions.PermissionDenied
Previously the test ran successfully while checking for HTTP-Code 403 like it is describe in the documentation (https://docs.djangoproject.com/en/2.1/topics/testing/tools/#exceptions)
The full Sourceode is available at Github (https://github.com/HamburgerJungeJr/pyVerein/tree/pyReportJasper/pyVerein/members)
Am I missing a change in the Django-Test system?
I just found the solution. The PyReportJasper-package set the global logging level to INFO. After changing this the error is gone.
Related
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',
...
}
I encounter this error for my django project. my app is called "scoresubmission"
basially i have a feature in the website to allow user download report.
So in my views.py file i have report function and import report.py file, where it shows how report is built
It shows the error happens in this line of code:
submission=Submission.objects.get(month=month,year=reportyear,program=program)
Views.py
def report(request):
from scoresubmission.report import reportA, reportB, reportC
reportType = request.POST["reportType"]
reportYear = int(request.POST["reportYear"])
if reportType == 'a':
report_content = reportA(reportYear)
response = HttpResponse(report_content, content_type="text/csv")
response['Content-Disposition'] = 'inline; filename=5SAuditYearlySummaryReport_%d.xlsx' %reportYear
report.py where it has the relevant code
for facility in facilities:
worksheet.write(row,col,facility.name,facility_format)
for i in range(12): # 12 months
month=i+1
programs=Program.objects.filter(facility_id=facility.id)
avg_totalscore=0
count=1
for program in programs:
print(program)
try:
submission=Submission.objects.get(month=month,year=reportyear,program=program)
print(submission)
avg_score=Result.objects.filter(submission=submission).aggregate(Avg('NewScore'))
#print avg_score.get('NewScore__avg')
avg_totalscore=(avg_totalscore + avg_score.get('NewScore__avg'))/count
count=count+1
except submission.DoesNotExist:
pass
#print avg_totalscore
if avg_totalscore!=0:
worksheet.write(row,i+3,avg_totalscore,red_format)
else:
worksheet.write(row,i+3,'-',red_format)
Traceback (most recent call last):
File "C:\Users\CHLOZHAO\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\CHLOZHAO\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\CHLOZHAO\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\CHLOZHAO\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\D Drive\5S Audit Website\my5saudit\scoresubmission\views.py", line 185, in report
report_content = reportA(reportYear)
File "C:\D Drive\5S Audit Website\my5saudit\scoresubmission\report.py", line 79, in reportA
except submission.DoesNotExist:
UnboundLocalError: local variable 'submission' referenced before assignment
In your except you need to refer to the class Submission, not the object, since it does not per se exists at that time:
try:
submission=Submission.objects.get(month=month,year=reportyear,program=program)
print(submission)
avg_score=Result.objects.filter(submission=submission).aggregate(Avg('NewScore'))
#print avg_score.get('NewScore__avg')
avg_totalscore=(avg_totalscore + avg_score.get('NewScore__avg'))/count
count=count+1
except Submission.DoesNotExist: # reference to the class, not the object
pass
If Sibmission.objects.get(..) fails, then the submission variable is never assigned, and hence submission.DoesNotExist makes no sense.
You acutally should never use the object, and always use the model class itself to refer to the DoesNotExist exception class.
I have a django rest Backend app, and i use swagger to look and document my apis to the FE.
This worked fine, but I made some changes and now I get this error:
Internal Server Error: /
Traceback (most recent call last):
File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/rest_framework/views.py", line 497, in dispatch
response = self.handle_exception(exc)
File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/rest_framework/views.py", line 457, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/rest_framework/views.py", line 468, in raise_uncaught_exception
raise exc
File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/rest_framework/views.py", line 494, in dispatch
response = handler(request, *args, **kwargs)
File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/rest_framework_swagger/views.py", line 32, in get
schema = generator.get_schema(request=request)
File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/rest_framework/schemas/coreapi.py", line 153, in get_schema
links = self.get_links(None if public else request)
File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/rest_framework/schemas/coreapi.py", line 140, in get_links
link = view.schema.get_link(path, method, base_url=self.url)
AttributeError: 'AutoSchema' object has no attribute 'get_link'
HTTP GET / 500 [0.15, 127.0.0.1:44214]
/home/notsoshabby/Desktop/panda_pitch/django_project/settings.py
This error is not very clear as the AutoSchema is not a part of my code and the traceback is not showing me where in My code the problem is.
I made too many changes to go one by one and check which one caused that.
Anyone experienced this issue before? Any ideas on how to debug to find which change causes this issue?
I ran into the same issue, the fix is described here: https://www.django-rest-framework.org/community/3.10-announcement/
To summarize, Django Rest Framework 3.10 (released a few days ago) deprecated the CoreAPI based schema generation, and introduced the OpenAPI schema generation in its place. Currently to continue to use django-rest-swagger as is you need to re-enable the CoreAPI schema generation by adding the following config to the settings file:
REST_FRAMEWORK = { ... 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema' }
I was trying to setup oauth2 authentication in a Django app. Here's my settings:
*other parts ommited*
# AUTH STUFF
AUTHENTICATION_BACKENDS = (
'social_core.backends.atlassian.AtlassianOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
SOCIAL_AUTH_ATLASSIAN_KEY = ' *my atlassian key here* '
SOCIAL_AUTH_ATLASSIAN_KEY_SECRET = ' *my atlassian secret key here* '
LOGIN_URL = '/auth/login/atlassian-oauth2'
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'
SOCIAL_AUTH_URL_NAMESPACE = 'social'
SESSION_COOKIE_SECURE = False
# i had to do that^, based on what i have read from
# https://stackoverflow.com/questions/37617308/session-value-missing-after-redirect-with-django-python-social-auth
# but it still doesn't work, sadly...
And then here's my view for the login page:
def index(request):
session_id = request.session.session_key
session_id = hashlib.sha256(str(session_id).encode('utf-8')).hexdigest()
auth_url = 'https://auth.atlassian.com/authorize?audience=api.atlassian.com&client_id=*my_client_id_here*&scope=read%3Ajira-user%20read%3Ajira-work%20manage%3Ajira-project&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcomplete%2Fatlassian%2F&state=$'+ session_id +'&response_type=code&prompt=consent'
print(auth_url)
context = {
'message': 'You are now authenticated'
if request.user.is_authenticated else 'You are not authenticated',
'auth_url': auth_url
}
return render(request, 'core/home.html', context)
to explain the stuff below --
the url that I used for Authorization grant before was just:
<a href="{% url "social:begin" "* name of backend here *" %}"> which is from the docs https://python-social-auth-docs.readthedocs.io/en/latest/configuration/django.html. It worked for facebook and google for me - but not with atlassian. So I checked the guide for the atlassian oauth2 (https://developer.atlassian.com/cloud/jira/platform/oauth-2-authorization-code-grants-3lo-for-apps/) and it said that I had to use the Jira Platform Rest API Authorization URL. So it worked for me. I was able to access the page where it asked for authorization from an Atlassian user.
When I click accept, Django Gives me an error that says "AuthStateMissing at /complete/atlassian/". The traceback shows that it raise AuthStateMissing(self, 'state'). I read from the Atlassian Guide that I had to have a state that is "a value that is associated with the user you are directing to the authorization URL, e.g., a hash of the user’s session ID", so I took the hash of the cookie of a user, then placed it to the auth_url -- but it still doesn't work.Here's the request information:
Here's the message from the terminal:
[15/May/2019 02:36:13] "GET /home/ HTTP/1.1" 200 1008
Internal Server Error: /complete/atlassian/
Traceback (most recent call last):
File "/home/vasiliy/.virtualenvs/dj_atlassian/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/vasiliy/.virtualenvs/dj_atlassian/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/vasiliy/.virtualenvs/dj_atlassian/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/vasiliy/.virtualenvs/dj_atlassian/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/home/vasiliy/.virtualenvs/dj_atlassian/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/vasiliy/.virtualenvs/dj_atlassian/lib/python3.7/site-packages/social_django/utils.py", line 49, in wrapper
return func(request, backend, *args, **kwargs)
File "/home/vasiliy/.virtualenvs/dj_atlassian/lib/python3.7/site-packages/social_django/views.py", line 33, in complete
*args, **kwargs)
File "/home/vasiliy/.virtualenvs/dj_atlassian/lib/python3.7/site-packages/social_core/actions.py", line 43, in do_complete
user = backend.complete(user=user, *args, **kwargs)
File "/home/vasiliy/.virtualenvs/dj_atlassian/lib/python3.7/site-packages/social_core/backends/base.py", line 40, in complete
return self.auth_complete(*args, **kwargs)
File "/home/vasiliy/.virtualenvs/dj_atlassian/lib/python3.7/site-packages/social_core/utils.py", line 259, in wrapper
return func(*args, **kwargs)
File "/home/vasiliy/.virtualenvs/dj_atlassian/lib/python3.7/site-packages/social_core/backends/oauth.py", line 388, in auth_complete
state = self.validate_state()
File "/home/vasiliy/.virtualenvs/dj_atlassian/lib/python3.7/site-packages/social_core/backends/oauth.py", line 90, in validate_state
raise AuthStateMissing(self, 'state')
social_core.exceptions.AuthStateMissing: Session value state missing.
really hope you guys could help. thanks
in my settings.py file.
SOCIAL_AUTH_REDIRECT_IS_HTTPS = True
My production server uses nginx to redirect HTTP to HTTPS, and this was the cause for the session state to go missing. Good luck-- hope this helps!
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.