Forbidden (CSRF cookie not set.): /auth for obtaining_auth_token - django

I am trying to get an auth token for the client (OrderClient.py). This keeps failing with
Forbidden (CSRF cookie not set.): /auth.
Here is my views
from rest_framework.decorators import api_view,permission_classes,authentication_classes
from rest_framework.response import Response
from .serializers import OrderSerial
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
from rest_framework.permissions import IsAuthenticated
#api_view(['POST'])
#authentication_classes([SessionAuthentication, TokenAuthentication])
#permission_classes([IsAuthenticated])
def make_order(request,*args,**kwargs):
user1=request.user
serializer = OrderSerial(user=user1)
print(serializer.is_valid())
data={'abc':'cde'}
return Response(data=data)
Here is my urls.py
from django.urls import path
from Products.views import home_view,Phone_input_view,Phone_list_view,Phone_edit_view
from Products.api.views import make_order
from rest_framework.authtoken.views import obtain_auth_token
urlpatterns = [
path('',home_view),
path('auth/', obtain_auth_token),
path('createPhone/',Phone_input_view),
path('viewPhoneList/',Phone_list_view),
path('edit/<int:id>',Phone_edit_view),
path('order/', make_order)
]
I have added the 'rest_framework.authtoken' to installed apps in settings.
I was expecting to retrieve the token and successfully sign in
Here is the link to my github repository: https://github.com/henselwilson/TrialProject

Related

Error in authenticate a websocket with token authentication on django channels?

I face an error when calling the websocket url with passing a JWT token for authentication purpose:
my websocket request is:
ws://127.0.0.1:8000/chat/chat_2/?token=
the error is:
raise ValueError("No route found for path %r." % path)
ValueError: No route found for path 'chat/chat_2/'.
I'm using a custom authentication middleware:
middleware.py
"""
General web socket middlewares
"""
from channels.db import database_sync_to_async
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser
from rest_framework_simplejwt.exceptions import InvalidToken, TokenError
from rest_framework_simplejwt.tokens import UntypedToken
from rest_framework_simplejwt.authentication import JWTTokenUserAuthentication
from channels.middleware import BaseMiddleware
from channels.auth import AuthMiddlewareStack
from django.db import close_old_connections
from urllib.parse import parse_qs
from jwt import decode as jwt_decode
from django.conf import settings
from django.contrib.auth import get_user_model
User = get_user_model()
#database_sync_to_async
def get_user(validated_token):
try:
user = get_user_model().objects.get(id=validated_token["user_id"])
print(f"{user}")
return user
except User.DoesNotExist:
return AnonymousUser()
class JwtAuthMiddleware(BaseMiddleware):
def __init__(self, inner):
self.inner = inner
async def __call__(self, scope, receive, send):
# Close old database connections to prevent usage of timed out connections
close_old_connections()
# Get the token
token = parse_qs(scope["query_string"].decode("utf8"))["token"][0]
# Try to authenticate the user
try:
# This will automatically validate the token and raise an error if token is invalid
UntypedToken(token)
except (InvalidToken, TokenError) as e:
# Token is invalid
print(e)
return None
else:
# Then token is valid, decode it
decoded_data = jwt_decode(
token, settings.SECRET_KEY, algorithms=["HS256"]
)
print(decoded_data)
# Get the user using ID
scope["user"] = await get_user(validated_token=decoded_data)
return await super().__call__(scope, receive, send)
def JwtAuthMiddlewareStack(inner):
return JwtAuthMiddleware(AuthMiddlewareStack(inner))
routing.py:
from . import consumers
from django.urls.conf import path
websocket_urlpatterns = [
path("ws/chat/<str:room_name>/", consumers.ChatConsumer.as_asgi()),
path(
"ws/personal_chat/<str:room_name>/",
consumers.PersonalConsumer.as_asgi(),
),
]
asgi.py:
import os
import ChatApp.routing
from django.core.asgi import get_asgi_application
django_asgi_app = get_asgi_application()
from ChatApp.middlewares import JwtAuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Hookax.settings")
application = ProtocolTypeRouter(
{
"http": django_asgi_app,
"websocket": JwtAuthMiddlewareStack(
URLRouter(ChatApp.routing.websocket_urlpatterns)
),
}
)
The project based on:
Django 3.2.7
Channels 3.0.4
Any suggestions solution?

Django DRF APITestCase post url results in 404 error

I'm learning DRF test cases, and in my test.py file, my URL in the client post-call is coming back in a 400 status error:
Here's my urls.py:
from django.contrib import admin
from django.urls import path, include
#from rest_auth.views import LoginView, LogoutView
urlpatterns = [
path('admin/', admin.site.urls),
path("api/", include("profiles.api.urls")),
path("api-auth/", include("rest_framework.urls")),
path("api/rest-auth/", include("rest_auth.urls")),
path("api/rest-auth/registration/", include("rest_auth.registration.urls"))
]
from django.conf.urls.static import static
from django.conf import settings
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Here's my test.py file
import json
from django.contrib.auth.models import User
from django.urls import reverse
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase
from rest_framework import status
from profiles.models import Profile
from profiles.api.serializers import ProfileSerializer
class RegistrationTestCase(APITestCase):
def test_registration(self):
data = {"username": "testuser1", "email": "test#localhost.app", "password1": "A41&14all", "password2": "A41#14all"}
response = self.client.post("/api/rest-auth/registration/", data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
It appears that the line self.client.post.... fails to find the endpoint.
What am I missing?
thanks!

router.register(), AttributeError: module 'rest_framework.views' has no attribute

I don't know what I am doing wrong. I have been battling with this error for hours. I have opened all the suggestions I saw and implemented what they suggested but still, the error is pending
router.register(r'^hmos/$', views.HMOList),
AttributeError: module 'rest_framework.views' has no attribute 'HMOList'
This is "core/urls.py"
from django.conf.urls import url
from .views import *
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from rest_framework_jwt.views import obtain_jwt_token,refresh_jwt_token
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('hmos', views.HMOList)
urlpatterns = format_suffix_patterns(urlpatterns)
This is "core/views.py"
from django.shortcuts import render_to_response
import json
from rest_framework.parsers import MultiPartParser, FileUploadParser, FormParser
from django.db.models import Q
from rest_framework import permissions
from django.contrib.auth import authenticate, login,logout
from rest_framework import generics, status, views
from rest_framework.permissions import IsAuthenticated
from .models import *
from .serializers import *
from rest_framework.response import Response
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from .utils import generate_responder_serial
from rest_framework.parsers import MultiPartParser, FileUploadParser, FormParser
from django.conf import settings
import os
from django.db.models import Q
#from rest_framework.authentication import (BaseJSONWebTokenAuthentication)
from rest_framework import viewsets
def jwt_response_payload_handler(token, user=None, request=None):
return {
'token': token,
'user': SystemUserSerializer(user).data
}
def create(self, request, *args, **kwargs):
new_data = {'name': request.data['name'].strip(), 'address': request.data['address'],
'state': request.data['state'], 'mobile1': request.data['mobile1'],
'mobile2': request.data['mobile2'], }
if HMO.objects.filter(name = request.data['name'].strip()):
raise serializers.ValidationError('HMO name already exists')
serializer = HMOSerializer(data=new_data)
if serializer.is_valid():
try:
serializer.save()
except Exception as e:
return Response( e)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response({
'status' : 'Bad request',
'message': 'HMO could not be created with received data.',
'errors' : serializer.errors # for example
}, status=status.HTTP_400_BAD_REQUEST)
This is promedic/urls.py
from django.conf.urls import url, include
from django.urls import path
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.views import serve
from rest_framework_swagger.views import get_swagger_view
schema_view = get_swagger_view(title='Pastebin API')
urlpatterns = [
url(r'^$', schema_view),
url(r'^admin/', admin.site.urls),
url('api/core/', include('core.urls')),
]
In "core/urls.py" you should have :
from .views import HMOList
router.register(r'hmos', HMOList)
urlpatterns = router.urls

Does django server support url callbacks (webhooks)?

I am trying to implement url callbacks. And trying to test it. But seems like it is not working. I have been following this article for callbacks implementation.
I have defined two urls in urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^agent205', 'agent205.views.test'),
url(r'^agent206', 'agent205.views.test2'),
)
and their views in views.py
__author__ = 'rai'
from django.shortcuts import HttpResponse, render_to_response, render
from django.http.request import HttpRequest
import urllib, urllib2, json
from django.contrib.auth.decorators import login_required
import json
from rest_framework.views import APIView
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def test(request):
data = {'foo': 'bar', 'hello': 'world'}
print request.body
return HttpResponse(json.dumps(data), content_type='application/json')
#csrf_exempt
def test2(request):
return HttpResponse(json.dumps(request.body), content_type='application/json')
Then I test from postman like
I am getting HTTP 200 OK response instead of getting 202 Accepted. What should I do for callback to work? Or am I missing something
If your issue is to return a 202 HTTP status code instead of the default 200, you could try to use the status parameter as follows:
#csrf_exempt
def test(request):
data = {'foo': 'bar', 'hello': 'world'}
print request.body
return HttpResponse(json.dumps(data), content_type='application/json', status=202)

Django cross site ajax(get) not getting response

I need to get the userid of user logged in to my django site. I am using Django 1.3.1.
Template
$.get(http://www.tomjoyapp.com/pinTag/, { URL: document.URL},
function(data){
alert("Data Loaded: " + data.responseText);
});
view
import os
from django.template.loader import get_template
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import Context, RequestContext
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def pinTag(request):
user=request.user.id
return HttpResponse(str(user))
I need to get the userid as response if he is logged in to my django app.
I am getting the status as 200 OK. But No response.