Django, request.user prints AnonymousUser, even if i logged in - django

views.py
class StorageView(viewsets.ModelViewSet):
serializer_class = StorageSerializer
def get_queryset(self):
if self.request.user.is_authenticated:
user = self.request.user
queryset = Storage.objects.filter(username=user.username)
return queryset
else:
print(self.request.user)
return []
urls.py
from django.urls import path, include
from django.urls import re_path as url
urlpatterns = [
path('auth/', include('rest_auth.urls')),
path('auth/register/', include('rest_auth.registration.urls'))
]
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# CORS
'corsheaders',
# REST
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'rest_auth.registration',
'django.contrib.sites',
# App
'backend'
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'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',
]
SITE_ID = 1
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_SESSION_REMEMBER = True
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_UNIQUE_EMAIL = True
REST_FRAMEWORK = {
'DATETIME_FORMAT': "%m/%d/%Y %I:%M%P",
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
I logging in via form or api, but is_authenticated method don't see me
Login via api
postman screenshot
Condition in get_queryset() function in views.py always evaluates to false, even if i logged in it keeps printing "AnonymousUser", why? How to check if user is logged in, in my case?

Provide
permission_classes = [IsAuthenticated]
in your views.
and pass
Authorization token with every request
axios
.get(
`http://localhost:8000/anything`,
{
headers: {
Authorization: `Token ${token}`,
},
}
)

Related

Django + Vue 403 Forbidden Error On axios.get

I'm trying to log the user but the Django rest API can't see the current jwt token of the logging user and I'm getting a 403 error. The API is working fine on the Postman with all the Authentication aspects. I have tried some advised solutions but they don't seem to work.
Attempt 1
axios.defaults.headers.common["authorization"] =
"Bearer " + localStorage.getItem("jwt");
await axios.get(api-link)
Attempt 2
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
axios.defaults.xsrfCookieName = "csrftoken";
axios.defaults.withCredentials = true;
await axios.get(api-link)
Attempt 3
await axios.get(api-link.{
{
headers:{header stuff}
},
{withCredentials: true}
)
(Basically adding headers and credentials inside the get request.)
Django settings.py
I couldn't find a standard for this, currently I'm using this one for testing:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'users',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = ['http://127.0.0.1:8000', 'http://localhost:8000']
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
]
}
CSRF_COOKIE_NAME = "XSRF-TOKEN"

Credential error when trying to preserve data

I am developing an api in Django Rest Framework, which at the moment only registers new users, but I have a problem and that is that now I am adding a bit of security, which is being controlled by means of tokens, but at the time of entering the token of an authenticated user for the creation of users generates an error of The authentication credentials were not provided, but I send the token as follows:
This is plugin rest client visual studio code
My authentication:
### Login user
POST http://localhost:8000/auth-token/
Content-Type: application/json
{
"username": "hamel",
"password": "contraseña"
}
This return a token b6773c67ecb940ae4fb7c9d49466a01fd46f5eb4
My register of user:
### Create User
POST http://localhost:8000/api/v1/users
Authorization: Token b6773c67ecb940ae4fb7c9d49466a01fd46f5eb4
Content-Type: application/json
{
"first_name": "Carlos",
"last_name": "Carlos",
"username": "carlos",
"email": "correo#rgrgr.com",
"password": "contraseña",
"password2": "contraseña"
}
My setting.py:
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
]
}
This my views.py:
class CreateUser(APIView):
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
def post(self, request, format=None):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
This is my INSTALLED_APPS:
INSTALLED_APPS = [
'users',
'profiles',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
]
This is my MIDDLEWARE:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
This my urls main:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from users.views import CustomToken
urlpatterns = [
path('auth-token/', CustomToken.as_view()),
path('api/v1/', include('users.urls')),
path('admin/', admin.site.urls),
] + static(
settings.MEDIA_URL, document_root=settings.MEDIA_ROOT,
)
This my urls app users:
from django.urls import path
from . import views
urlpatterns = [
path('users', views.CreateUser.as_view()),
]

Session is not storing variables - Django

I've been having trouble storing my tokens on session.
I've found few solutions on stackoverflow but none of them worked.
currently, I store user's token when client send a POST request to /api/login
and here is my views logic
request.session['token'] = auth.token.key
request.session.modified = True
I'm 100% sure auth.token.key is not None and the logic stores just fine.
but when it comes to /api/update (some sample api),
I always get None
here is how I get the Item from session:
print(request.session.get('token'))
** The Code above always returns None**
I read the Django docs. I set both the session middleware and session app:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'user'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'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',
]
AUTHENTICATION_BACKENDS = (
'user.auth.AuthBackend',
'django.contrib.auth.backends.RemoteUserBackend',
'django.contrib.auth.backends.ModelBackend',
)
I've done all the migrations.django_session table exists.
EDITED:
login view:
I have custome authentication backend
#api_view(['POST'])
def login(request):
# convert json data into dictionary
data = get_data(request)
print(request.session.get('token'))
auth = authenticate(
email = data['email'],
password = data['password']
)
if auth:
# store user's token into sesion
request.session['token'] = auth.token.key
print(request.session['token'])
user = UserModelSerializer(auth.user)
return Response(
user.data,
status = status.HTTP_200_OK
)
else:
return Response(
message("user doestn't exist | incorrect password"),
status = status.HTTP_403_FORBIDDEN
)
Update View (where I can't get the session data):
#api_view(['POST'])
def update(request):
print(request.session.get('token'))
return Response("its ok.")

Django request.user is anonymous in views without login_required decorator

I am working on a Django (v2.0) app with django-allauth as auth backend. I'll explain my problem in steps:
User logs in -> user redirected to home page (can't access home page without login)
In the home page (after logging in), several calls are made for a particular view in the server.
Ex: https://mywebsite.com/api/getstuff/123
Problem: getstuff returns/prints data that is intended for a user who is NOT logged in.
getstuff is defined in urls.py as:
url(r'^api/getstuff/(?P<hash_code>[a-zA-Z0-9]{3})$', views.getstuff, name='getstuff')
in views.py: (views.getstuff)
#csrf_protect
#ensure_csrf_cookie
def getstuff(request,hash_code):
if request.user.is_authenticated:
#do stuff....
print('user is authenticated!')
return HttpResponse(hash_code+'foo-auth')
else:
#do other stuff..
print('user is NOT authenticated')
return HttpResponse(hash_code+'foo-un_auth')
I only see user is NOT authenticated being printed in my case. Shouldn't the output be user is authenticated since the user is already logged in? the request.user object is an AnonymousUser object. All the requests I make are from https.
few configurations from settings.py:
CSRF_USE_SESSIONS = True
CSRF_COOKIE_SECURE = True #tried removing this, still same result as above
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django_extensions',
'django.contrib.sitemaps',
'mysite.core',
'bootstrapform',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.google',
'allauth.socialaccount.providers.github',
'allauth.socialaccount.providers.twitter',
'embed',
'channels',
'djcelery'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'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',
]
AUTHENTICATION_BACKENDS = (
"allauth.account.auth_backends.AuthenticationBackend",
)
I tried clearing cache before accessing the website and logging in - still same result.
Am I missing something? What could be the problem?
Your use of if request.user.is_authenticated: is fine. Change the image src tag to use the domain that you logged into.
<img src="/api/getstuff/123">

Django rest-auth registration. How to return user_id with the key when using token authentication

I am using Djando rest_auth.registration.
My corresponding entry in urls.py is
url(r'^rest-auth/registration/', include('rest_auth.registration.urls'))
My authentication class is rest_framework.authentication.TokenAuthentication
This rest API call works perfectly well.
When I register via this API I get the below response.
{
"key": "3735f13cd69051579156f98ffda338a2d7a89bb5"
}
I also want to include the user_id field in the response. How do I go about doing that. I tried extending the method get_response_data from class RegisterView(CreateAPIView): but unable to do so. Can someone please advise the best practice to achieve this. Code would be ideal. Thanks.
I want to use the rest-auth/registration/ url provided out of box by rest_auth.registration. I do not want to create a separate new URL for this.
My Settings.py as follows
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'sdAPI.apps.SdapiConfig',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'rest_framework_swagger',
'rest_auth.registration',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.google',
'django_extensions',
]
# auth and allauth settings
LOGIN_REDIRECT_URL = '/'
SOCIALACCOUNT_QUERY_EMAIL = True
SOCIALACCOUNT_PROVIDERS = {
'facebook': {
'SCOPE': ['email', 'publish_stream'],
'METHOD': 'oauth2' # instead of 'oauth2'
}
}
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
}
SITE_ID = 1
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
REST_SESSION_LOGIN = False
My urls.py as follows
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^user/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
url(r'^rest-auth/', include('rest_auth.urls')),
url(r'^rest-auth/registration/',include('rest_auth.registration.urls')),
]
I think you only need to override the TOKEN_SERIALIZER option in your REST_AUTH_SERIALIZERS configuration.
from rest_framework.authtoken.models import Token
class TokenSerializer(serializers.ModelSerializer):
class Meta:
model = Token
fields = ('key', 'user')
Then, set it in your settings.py as shown in the docs,
REST_AUTH_SERIALIZERS = {
'LOGIN_SERIALIZER': 'path.to.custom.LoginSerializer',
'TOKEN_SERIALIZER': 'path.to.custom.TokenSerializer',
...
}