'AnonymousUser' object has no attribute '_meta' | Django Authentication - python

Same authentication system on three different places in project i.e Authenticating user at login, registration, and password reset. At password reset it works fine all the time. At registrations sometime works and sometime doesn't and at login works on rare occasions. Also the error is same all the time.
ERROR
AttributeError at /userauth/user-activate/NA/avnpw3-de3afda5cfeae9690598ace91235106a/smqia40453665072/pW1QdEFRkm42txOZ
'AnonymousUser' object has no attribute '_meta'
Request Method: POST
Request URL: http://127.0.0.1:8000/userauth/user-activate/NA/avnpw3-de3afda5cfeae9690598ace91235106a/smqia40453665072/pW1QdEFRkm42txOZ
Django Version: 3.2.7
Exception Type: AttributeError
Exception Value:
'AnonymousUser' object has no attribute '_meta'
Exception Location: C:\Users\smqia\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py, line 247, in inner
Python Executable: C:\Users\smqia\AppData\Local\Programs\Python\Python39\python.exe
Python Version: 3.9.7
Python Path:
['C:\\xampp\\htdocs\\Projects\\Barter',
'C:\\Users\\smqia\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
'C:\\Users\\smqia\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
'C:\\Users\\smqia\\AppData\\Local\\Programs\\Python\\Python39\\lib',
'C:\\Users\\smqia\\AppData\\Local\\Programs\\Python\\Python39',
'C:\\Users\\smqia\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages']
Server time: Fri, 05 Nov 2021 16:35:02 +0000
CODE
settings.py
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
views.py
username = smqia404
password = ***************
user = authenticate(request, username=username, password=password, backend='django.contrib.auth.backends.ModelBackend')
login(request, user, backend='django.contrib.auth.backends.ModelBackend')

authenticate returns None if the provided credentials are invalid and login expects a User object.
Thus, as docs instructs, you need to check if authenticate returned a user or not.
user = authenticate(request, username=username, password=password, backend='django.contrib.auth.backends.ModelBackend')
if user is not None:
login(request, user, backend='django.contrib.auth.backends.ModelBackend')
else:
# handle non-auth users

if you getting the 'AnonymousUser' object error please check if the user is already saved in the Users Model in the Database or not. if not or credentials are mismating it tells the user was the 'AnonymousUser' other wise authentication system allows us to logging. you can also try login_requried decorator (login required to tell if a user is already existed in Users Models in Database).
to check if the user already existed in the Database or not using ORM.
In interpreter enter python manage.py shell
from django.contrib.auth.models import User
q=User.objects.filter("username"="enter username")
if len(q)>0:
print("user existed")
#try to login using authenticate function
# try to login with out authenticate function
username=User.objects.get_or_404(username="your username")
if username not None and username.password="your password":
#login
else:
# user not found / credentials are mismatch.
else:
#create user in Users Model(Handling if user doesn't exist)
user = User.objects.create_user('username', 'email', 'password')
user.save()
we believe you are missing the save method while registering a user. please check once.
if you need full code about this issue please post again will share it.

Related

Using the django authentication system

I want to login with handler.
I have a code use session but i want to use handler:
I have visit :
https://docs.djangoproject.com/en/1.11/topics/auth/default/
But i don't understand complete.
I want to log user (with username or email and password)
Do you have a code for example or project in stackoverflow or github or . . . ???
login the user is easy if you are using default user model from django.contrib.auth.models
from django.contrib.auth import authenticate, login
def user_login(request):
# check here that request.method is POST or not.
user = authenticate(username=request.POST.get('username'), password=request.POST.get('password'))
if user is not None:
login(request, user)
# send some http response here that login successful or redirect to some other page
else:
# return an error page saying that username password not correct
authenticate function will check for username and password in User table in the database if it founds a user matching query then it returns the user object else it will return None. You might not want to manage sessions as django already sets a cookie for every user that successfully logs in so if user has logged in once then he will not be required to enter password again.

Django Custom Backend Documentation Discrepancy

I am having difficulty understanding how Django's documentation has outlined the overriding of the authenticate method in contrib.auth.models.Users. According to the code below from here, wouldnt the authenticate method succeed if the method was passed a valid username and a valid hash that exists anywhere in the database regardless of whether it matches the password for the supplied primary key field (username, email, etc...) or not. Is there something that check_password is doing that I am not seeing like ensuring that the field that was passed alongside of the password is checked behind the scenes? Because this supplied example appears to have a flaw.
# From Django 1.10 Documentation
def authenticate(self, username=None, password=None):
login_valid = (settings.ADMIN_LOGIN == username)
pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
if login_valid and pwd_valid:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
# Create a new user. There's no need to set a password
# because only the password from settings.py is checked.
user = User(username=username)
user.is_staff = True
user.is_superuser = True
user.save()
return user
return None
Thanks.
authenticate() function returns user for which you attach session using login()
Use authenticate() to verify a set of credentials. It takes
credentials as keyword arguments, username and password for the
default case, checks them against each authentication backend, and
returns a User object if the credentials are valid for a backend. If
the credentials aren’t valid for any backend or if a backend raises
PermissionDenied, it returns None.:
In case of the following authentication backend username and password are passed to it.
Password is compared with one set in Django settings and user object
is queried from database.
If user with that username does not exist backend creates new user.
This backend works even though from security aspect it is not best one :)

Django custom auth backend doesn't seem to be being called?

I'm using Django 1.8.4 on Python 3, and attempting to create an auth backend which validates a cookie from a legacy ColdFusion web site and create / log the Django user in after checking the value in a database. In settings, I am including the backend:
AUTHENTICATION_BACKENDS = (
'site_classroom.cf_auth_backend.ColdFusionBackend',
)
And the code for the backend itself; SiteCFUser is a model against the SQL Server database user model which contains the active cookie token value:
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from users.models import SiteCFUser
class ColdFusionBackend(ModelBackend):
"""
Authenticates and logs in a Django user if they have a valid ColdFusion created cookie.
ColdFusion sets a cookie called "site_web_auth"
Example cookie: authenticated#site+username+domain+8E375588B1AAA9A13BE03E401A02BC46
We verify this cookie in the MS SQL database 'site', table site_users, column user_last_cookie_token
"""
def authenticate(self, request):
User = get_user_model()
print('Hello!')
token=request.COOKIES.get('site_web_auth', None)
print('Token: ' + token)
cookie_bites = token.split('+')
if cookie_bites[0] != "authenticated#site":
# Reality check: not a valid site auth cookie
return None
username = cookie_bites[1]
cf_token = cookie_bites[3]
try:
site_user = SiteCFUser.objects.using('mssqlsite').filter(cf_username=username)
except:
# No user found; redirect to login page
return None
if site_user[0].cftoken == cf_token:
try:
# Does the user exist in Django?
user = User.objects.get(username=username)
except:
# User does not exist, has a valid cookie, create the User.
user = User(username=username)
user.first_name = site_user[0].cf_first_name
user.last_name = site_user[0].cf_last_name
user.email = site_user[0].cf_email
user.save()
else:
return None
def get_user(self, user_id):
User = get_user_model()
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
The problem is, the backend doesn't seem to be called when hitting a URL with a view with #login_required, or even trying to log in through a form with username and password. If I force an error by changing the name of the class in settings, or change the name of the class in cf_auth_backend.py, I do get an error. However, none of the print statements show up in the console. I'm clearly missing something here: any idea what I'm not doing right?
While the accepted answer might have helped the OP, it's not a general answer to the question's title.
Authentication back ends do work simply by listing them in AUTHENTICATION_BACKENDS. But they may appear to be ignored
for various reasons, e.g.:
urls.py needs to point to something like django.contrib.auth.views.login
url(r'^accounts/login/$', django.contrib.auth.views.login)
if it's pointing to some other authentication app. AUTHENTICATION_BACKENDS
may not work.
the authenticate() method must accept a password keyword, either through
password=None or **kwargs. Probably true for username too. It won't
be called if it doesn't accept that keyword argument.
Authentication backends doesn't work that way. They won't be called on each request or on requests where authentication is required.
If you want to log in user based on some cookie, you should call authentication in middleware.

Get user object using userid in django

Hello i am new to django,
i am creating an authentication system using django.
Once a user is logged in i am storing the value in a session.
user = authenticate(username=username, password=password)
request.session['mid'] = user.id
and when i refresh i can receive the session id
uid = request.session['mid']
But i am not sure how to get the userdatas from the user id. can any one tell me how can get the user object using the user id.
Use simple .get() query.
try:
uid = request.session['mid']
userobj = User.objects.get(id=uid)
except User.DoesNotExist:
#handle case when user with that id does not exist
...
Of course, you can store the user id in request.session, and query the id
with django ORM manually.
But after installing the SessionMiddleware and AuthenticationMiddleware middlewares, on a higher level, Django can hook this authentication framework into its system of request objects. I believe most django projects will use the code below to get authenticated user from web requests.
if request.user.is_authenticated():
user = request.user

'AnonymousUser' object has no attribute 'backend'

Using django-socialregistration, got following error:
'AnonymousUser' object has no attribute 'backend'
How,
I click on facebook connect url.
That took me Facebook and ask me to login. So I did, asked permission, I granted.
After that it redirect me to my site. And ask to setup. I provide user and email address.
Once I submit, got error like above:
Trace point:
path/to_file/socialregistration/views.py in post
128. self.login(request, user)
Do anybody know, what's wrong?
Oh man i used to get this error all the time, basically you are calling
self.login(request, user)
without calling
authenticate(username=user, password=pwd)
first
when you call authenticate, django sets the backend attribute on the user, noting which backend to use, see here for more details
https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.authenticate
I had the same error for a newly registering user.
def attempt_login(self, email, password):
user = authenticate(username=email, password=password)
login(self.request, user)
return user
I checked into database and the User has been created after registration, but this error was still there.
I figured out - user's login ( email ) was longer than 30 characters, and the form field had no validation. The username would get truncated in the database, and therefore authenticate was called for non-existent login.
254 - character is the advised length of email field.
Solution: emailfield-max_length-r11092.patch
I just got this error and found this post.. My solution was in the case was in the registration process. When the user was registering, my api and serializer wasn't hashing the password.. So in the api_view i had to manually hash the password like this..
from django.contrib.auth.hashers import make_password
# In the register api..
#ensure_csrf_cookie
#api_view(['POST'])
def register_api(request):
# Anywhere before the serializer
request.DATA['password'] = make_password(request.DATA['password'])
# Then the serializer
serializer = RegisterSerializer(data=request.DATA)
# ... etc.. Note that if you want to login after register you will have
# to store the initial password is some buffer because.. authentication
# the none hashed version.. then
authenticate(username=request.DATA['username'], password=someBuffer)
Hope that helps someone..

Categories