Authenticate the django user using phone email and username - python

I am trying to achieve a login functionality like so that users can log into using their Email or Phone number or it's username as well but Django provides only email field in it's User model so that I've created an another model with One-To-One-Relation to User model and provided the phone number column but now I don't know how to achieve such functionality which I mentioned earlier.
my models.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
user_type = models.IntegerField(choices=USER_TYPE, default=3)
mobile = models.BigIntegerField(unique=True)
my views.py
(I know it's a mess but I can't figure out how to have such functionality)
def login(request):
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
messages.success(request, 'You are logged in successfully!')
return redirect('/dashboard')
else:
user = auth.authenticate(profile_phone=username, password=password)
if user is not None:
auth.login(request, user)
messages.success(request, 'You are logged in successfully!')
return redirect('/dashboard')
else:
user = auth.authenticate(email=username, password=password)
if user is not None:
auth.login(request, user)
messages.success(request, 'You are logged in successfully!')
return redirect('/dashboard')
else:
messages.error(request, 'Invalid username or password')
return redirect('/login')
else:
if request.user.is_authenticated:
messages.success(request, 'You are already logged in')
return redirect("/dashboard")
return render(request, "accounts/login.html")

It is not true that the Django user model only provides an email field. It also has a username field as you want. Check documentation here. If you want to add a phone number or another field, you can implement like this:
from django.contrib.auth.models import User
class MyUser(User):
user_type = models.IntegerField(choices=USER_TYPE, default=3)
mobile = models.BigIntegerField(unique=True)
and the class will include everything that the base User model has.
Also, Django provides a built-in login method that you can also use. Check this tutorial.

Related

Django login authentication always returns none

I am using django contrip auth for authenticate user. Signup function always working and register and login user successfully but after that I m logged out and try to login again but this time login function doesnt work.
I add this codes my settings file
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
AUTH_USER_MODEL = 'app.User'
My User model seems like that in models.py
class User(AbstractUser):
pass
My Login and Register function
def dlogin(request):
if request.method=='GET':
return render(request, "login.html")
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
# Attempt to sign user in
user = authenticate(request, username=username, password=password)
print(user)
# Check if authentication successful
if user is not None:
login(request, user)
cur_user = request.user
return render(request,'index.html',{
'success':'login successful',
'user':cur_user
})
else:
return render(request,'login.html',{
'error':'Invalid username and/or password.'
})
#csrf_exempt
def signup(request):
if request.method != "POST":
return render(request, 'signup.html')
# Get form information
username = request.POST["username"]
password = request.POST["password"]
confirmation = request.POST["confirmation"]
# Ensure password matches confirmation
if password != confirmation:
return render(request,'register.html',{
'message':'Passwords dont match'
})
# Attempt to create new user
user = User.objects.create_user(username,password)
user.save()
login(request, user)
return redirect('index')
I did some research and couldn't find any problem in my code. Does anyone can help me?
I fixed it
I change this in signup function
user = User.objects.create_user(username,password)
to this
user = User.objects.create_user(username=username,password=password)
and it works but i dont know why

I want different authentication system for normal user and admin user in Django?

I create a website where there is a normal user and admin. They both have different log in system.But the problem is when a user logged in as a user, he also logged in into admin page. Also when a admin logged in, he also logged in into user page.
def userlogin(request):
error = ""
if request.method == 'POST':
u = request.POST['emailid']
p = request.POST['pwd']
user = authenticate(username=u, password=p)
try:
if user:
login(request, user)
error = "no"
return redirect(profile)
else:
error = "yes"
except:
error = "yes"
return render(request, 'login.html', locals())
def login_admin(request):
error = ""
if request.method == 'POST':
u = request.POST['uname']
p = request.POST['pwd']
user = authenticate(username=u, password=p)
try:
if user.is_staff:
login(request, user)
error = "no"
else:
error ="yes"
except:
error = "yes"
return render(request,'login_admin.html', locals())
This model is used for normal user signup
class Signup(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
contact = models.CharField(max_length=10)
branch = models.CharField(max_length=30)
role = models.CharField(max_length=15)
username = models.CharField(max_length=15, unique=True)
image = models.ImageField(upload_to="images/img", default="")
upvotesuser = models.IntegerField(default=0)
I want to achive different authentication system for user and also for admin.
Make some roles explicitly in SignUp model as follows as Django provides that too:
admin
staff
simple user/regular user
Define the role of each user in the SignUp model. If a regular user is logged in it will definitely be filtered from the signUp model and that will return him/her as a regular/simple user.
You don't need to create another model for signup
You can easily check the current user permissions
E.g
is_admin
is_staff
is_superuser
Then redirect depending on the permisions

How can i authenticate any user for login with an extra field (other then username/ email and password) in django

I am creating a user profile using django’s authentication system (from django.contrib.auth.models import User). Before this I am trying to extend the field of user using an extra field (i.e- userprofile= ceo/developer/marketinghead) in models.py. Here is my models.py file
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class extendeduser(models.Model):
userprofile_choice=(
('ceo', 'ceo'),
('developer', 'developer'),
('marketinghead', 'marketinghead'),
)
userprofile=models.CharField(choices= userprofile_choice, max_length=255, blank=False)
user=models.OneToOneField(User, on_delete=models.CASCADE)
def __str__(self) -> str:
return self.userprofile
now I am sucessfully registering the new user. Now I have created differrent html pages based on their profile. So at the time of login I take an extra input from user which is userprofile. And based on this I have created views.py for redirecting the user at correct place. Here is my views.py file :-
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
uf = request.POST['userprofile']
user = auth.authenticate(username=username, password=password)
user_profile = extendeduser.objects.filter(user = user)
# print(user_profile[0])
# print(uf)
# print(user.get_username)
# print(user.__dict__)
#print(user.get_userprofile)
if user is not None:
if uf==user_profile[0]:
if uf=='ceo':
auth.login(request, user)
messages.success(request, "You are logged-In")
return redirect('wtoday')
elif uf=='developer':
auth.login(request, user)
messages.success(request, "You are logged-In")
return redirect('swhome')
elif uf=='marketinghead':
auth.login(request, user)
messages.success(request, "You are logged-In")
return redirect('sswhome')
else:
messages.warning(request, 'Invalid Credentials!!')
return redirect('login')
else:
messages.warning(request, 'Invalid Credentials!')
return redirect('login')
else:
messages.warning(request, 'Invalid Credentials')
return redirect('login')
return render(request, 'accounts/login.html')
Everything is fine but this "if uf==user_profile[0]:" line of code is not working. basically it is checking that the "userprofile" field of any particular user which is store in database is same as at the time of login or not. I am saying this line of code is not working because when i comment that line and then without checking user profile from the databae i just redirecting them based on the data which he fiels at the time of login then it works. But I didn't want this.
Please help me out!!
You can't compare uf and userprofile[0], because uf is a string and userprofile[0] is an extendeduser object. Maybe if uf == str(userprofile[0]): is what you want.

I have problem with django login view about auth lib

I have problem about auth system. It only work by username and password, but I need use email rather than username
def login_view(request):
if request.user.is_authenticated or request.user.is_staff or request.user.is_superuser:
return redirect('/account/')
elif request.method == "POST":
email = request.POST['email']
# username = request.POST['username'] # it work
password = request.POST['password']
user = authenticate(request, email=email, username=username, password=password)
if not grecaptcha_verify(request):
context = {'message_bad':'...'}
elif user is not None:
login(request, user)
return redirect('/account/')
else:
context = {'message_bad':'...'}
else:
context = {}
return render(request, "login.html", context)
Please help me or how can I change login() codes at auth lib .
if what you have said about not having models is accurate then you will need to create a custom user model that has a custom backend where you can use the email instead of a username
id recommend following this tutorial for that
https://rahmanfadhil.com/django-login-with-email/

Authentication with custom user model

I want to make login and registration for a custom user with only 5 fields: user name, name, password, linkedin id and mobile number.
I made registration successfully but I am stuck with login, I cannot authenticate my user.
Is there any way to authenticate my user, or how can I login?
Currently I am getting logged in by
user = Consultants.objects.get(Q(username= username) & Q(password= password))
But i want to make login by
user=authenticate(username=username,password=password)
Note:I don't want to use django default User Model For it.
Please help me in this.
Thanks in advance.
models.py
class Consultants(models.Model):
first_name=models.CharField(max_length=255,blank=True,null=True)
username=models.CharField(max_length=255,blank=True,null=True)
password=models.CharField(max_length=50,blank=True,null=True)
mobile_no=models.CharField(max_length=255,blank=True,null=True)
linkedin_id=models.CharField(max_length=255,blank=True,null=True)
is_active=models.BooleanField(default=False)
views.py
def register(request):
context = RequestContext(request)
registered = False
print "inside register view"
if request.method == 'POST':
consultant_form = ConsultantsForm(data=request.POST)
if consultant_form.is_valid():
consultant = consultant_form.save(commit=False)
consultant.save()
registered = True
else:
print consultant_form.errors
else:
consultant_form = ConsultantsForm()
return render_to_response(
'register.html',
{'consultant_form': consultant_form, 'registered': registered},
context_instance=RequestContext(request))
def login_user(request):
context = RequestContext(request)
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
print type(username)
try:
user = Consultants.objects.get(Q(username= username) & Q(password= password))
user = authenticate(username=username, password=password)
if user.is_active:
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, user)
a= request.user.username
return HttpResponse("welcome......you are succesfuly log in")
else:
return HttpResponse("Your account is disabled.")
except ObjectDoesNotExist:
return HttpResponse("INvalid User")
Note:I don't want to use django default User Model For it Please help
me in this. Thanks inadvance
Is your Consultants class inheriting from the base Django user class?
The authenticate() function is used to authenticate the base user model, you may not be setting a password for the user when they are created?
Another way to go about this would instead create a Profile model with all of these extra fields with a OneToOneField to the base user model, and authenticate though the Django ORM.
I think it's better to inheriting from django embedded user class, you can follow these steps:
extend your custom user class from AbstractBaseUser and PermissionsMixin
Assign and fill this config in settings.py:
AUTH_USER_MODEL = 'YOUR_CUSTOM_CLASS_IN_FULL_QUALIFIED_NAME' e.g.: 'your_app_name.Consultants'
Voila, you can use django default user crud, also authentication

Categories