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..
Related
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.
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.
I am writing a web app using Django. I am trying to allow a user to see its profile and only his own.
if(not request.user.id == request.GET.get('user_id', '')):
raise PermissionDenied
My question is: is it safe to check this way or is it possible for a smart kid to somehow alter the value in request.user.id to match the user_id of anyone?
The user must be logged in before accessing this page using this:
user = LDAPBackend().authenticate(username=username, password=password)
if(user is not None):
login(request, user)
Yes it should be safe.
request.user get's only populated when authentication with session cookies. Unless and until someone steals the cookie or token it should be no issue.
One thing i don't understand is why do you need user_id parameter here to be explicitly passed.
if you are putting logged in compulsory to view the page. there are two way i can see this.
/profile
Directly get user profile corresponding to the request.user
/<username>
Query the profile corresponding to the username and compare it with request.user.id
request.user is set using AuthenticationMiddleware for each request:
Adds the user attribute, representing the currently-logged-in user, to every incoming HttpRequest object.
If a user is not logged in then request.user is set to Anonymous User. Have a look at Authentication in Web requests.
So, I am not sure how would a smart kid alter the id of the logged-in user.
Mostly, there is a one-to-one relation between the user and its profile. If that's the case you can modify the queryset to get the profile for request.user directly.
request.user is already an object about the current user who send the request to get the page. You can use login_required or to only allow user login to access (2 solutions : decorator or Mixin).
And then you can use your condition to load the page in the function. Example:
=> url.py:
url(r'^profile/$', login_required(app.views.profile), name='profile'),
=> views.py :
def profile(request):
try:
myProfile = User.objects.get(username=request.user.username)
except ObjectDoesNotExist:
return render(request, "error.html", {'message' : 'No Profile Found'})
return render(request, "app/profile.html",
{'myProfile': myProfile})
Like this you can only display YOUR profile (user who send the request) AND you need to be logged.
EDIT: if you don't want "try and catch" you can use get_object_or_404(User, username=request.user.username)
I am attempting to learn Django's authentication system by contriving a basic login scenario. My views are set up such that a view, logIn, either receives a user's credentials (and prints the success/failure of the login), or it renders a login form.
A second view, privatePage, is designed as a sanity check that the user is actually logged in. The code is as follows:
views.py:
#login_required(login_url='/logIn')
def privatePage(request):
return HttpResponse("You're viewing a private page")
#csrf_exempt
def logIn(request):
if request.method == "POST" and \
request.POST.get('email') and \
request.POST.get('password'):
user = authenticate(username=request.POST['email'],
password=request.POST['password'])
return HttpResponse('Valid login' if user is not None else 'Invalid login')
# render login form
return HttpResponse("<form>...</form>")
I'm finding that after succcessfully logging in via the logIn view, I am still redirected to the login view upon trying to visit privatePage. FYI, I'm attempting to visit the privatePage view directly by URL, as opposed to navigating through provided links (e.g. I'm not sure if I'm violating some CSRF rule).
Any idea what's going on?
You've not actually logged in. You need to login the user after verifying their identity with authenticate:
from django.contrib.auth import login
user = authenticate(email=email, password=password)
if user is not None:
login(request, user)
login should only be used on users that have been confirmed to exist.
What authenticate does:
verifies a user is who they claim to be
It does not perform the actual login.
To keep the user logged in a session must be provided to user with usage of login() method. Login is the process of providing user with a session and authenticate() verifies that the given credentials corresponds to an existing user model object in database . Import django's built in login and authenticate methods from django.contrib.auth import authenticate, login. And then your code looks like
user =authenticate(email, password)
If user:
login(user, request)
Hope it helps :)
After being forced to leave PHP behind and work a bit with Python and Django I have hit a little problem.
What I'm trying to do is to use the built-in user-authentication that comes with Django. Problem is that when I'm trying to use the "login()" function it doesn't save the user in the session, or wherever it should be saved.
My code looks like this:
#csrf_exempt
def dologin(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
# Redirect to a success page.
return render_to_response('bsys/profile.html', {'message': 'Success!', 'user': request.user.get_full_name()})
else:
# Return a 'disabled account' error message
return render_to_response('bsys/login.html', {'message': 'Disabled!'})
else:
# Return an 'invalid login' error message.
return render_to_response('bsys/login.html', {'message': 'Sumthin Wong!'})
So problem is when I run:
request.user.get_full_name()
It says:
Exception Type: AttributeError
Exception Value: 'AnonymousUser' object has no attribute 'get_full_name'
So apparently it doesn't log in the user.
When I do the same, but using:
user.get_full_name()
It works, then the authenticate-function apparently works well too. So there is something about login(), I guess.
What I also tried was to login via the admin-login as an admin, then using the same request.user.get_full_name() from another view and it works fine.
Any ideas to solve this? Maybe I just missed some essential part of the framework.
I think the way you check that the user is logged in is causing this.
instead of:
if user is not None:
try with:
if user.is_authenticated:
This was it will get round the AnonymousUser case.
(it may be, don't remember from the top of my head)
if user.is_authenticated():
Why are you rendering a template on successful login? Like with all POSTed HTTP requests, it's a good idea to redirect on success to reduce the chance of the user resubmitting the request.
More relevantly, I believe this will fix your problem because the templates, when they get their context populated with the auth context processor, will have their {{ user }} variable set to the value of request.user, which is an anonymous user at the beginning of the request. If you redirect, the new request will have a non-anonymous request.user, so the template's value should be populated properly.