prevent user to access login page in django when already logged in? - django

def admin_login(request):
if request.method == 'POST':
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request,username = username, password = password)
if user is not None:
if(user.is_superuser):
auth_login(request, user)
return redirect(reverse("dashboard"))
else:
messages.info(request, "invalid credentials")
return redirect(reverse("admin"))
return render(request,'login.html')
this is mylogin function for admin , how to prevent user to access login page once logged in?

You can check if the user who is requesting is authenticated and if so, you can redirect him to another page. You can check user if he is authenticated like this
if request.user.is_authenticated:
# redirect
so your view function will be like this
def admin_login(request):
if request.user.is_authenticated:
return redirect(reverse("admin"))
if request.method == 'POST':
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request,username = username, password = password)
if user is not None:
if(user.is_superuser):
auth_login(request, user)
return redirect(reverse("dashboard"))
else:
messages.info(request, "invalid credentials")
return redirect(reverse("admin"))
return render(request,'login.html')

do this in beginning of your login function
def user_login(request, *args, **kwargs):
if(request.user.is_authenticated):
print('user authenticated')
return HttpResponseRedirect('/')

Related

Django Login form issue

Views.py
def Tourist_login(request):
if request.method == 'POST':
form = Tourist_login_form(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username,password=password)
print(user)
if user is not None:
login(request,user)
messages.success(request,'logged in')
return redirect('home')
else:
messages.error(request,"Invalid login credentials!")
return redirect('touristlogin')
else:
return redirect('touirstlogin')
else:
form = Tourist_login_form()
return render(request,'accounts/tourist_login.html',{'form':form})
In the above code , authenticate function returns none value. But if I'm passing input in form through superuser credentials then it is working fine. I'm not able why is it not taking the username and password passed by the user and only taking superuser username and password.
Please try using this way:
from django.contrib.auth.models import auth
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
messages.success(request,'logged in')
return redirect('home')

Any Possibility to put condition on Password Required in Django Custom Auth?

I want the registered user to log in with the Email or PhoneNumber and the Password first. If the user forgot the Password then there should be the possibility to log in with OTP bypassing the Password which would be provided via SMS on the User Phone Number. So Is there any possibility to achieve that?
Here are official docs where the password field is always required.
https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#a-full-example
I know we can change the username to the email or for a phone number if we want but how do we put the condition to login with Password/Random OTP. So how we can achieve that? a suggestion would be appreciated. Thanks
You can make your own CustomLoginBackend as
from django.contrib.auth import get_user_model
class CustomLoginBackend(object):
def authenticate(self, request, email, password, otp):
User = get_user_model()
try:
user = User.objects.using(db_name).get(email=email)
except User.DoesNotExist:
return None
else:
if password is not None:
if getattr(user, 'is_active', False) and user.check_password(password):
return user
else:
if getattr(user, 'is_active', False) and user.otp == otp: #<-- otp included in user table
return user
return None
Then in your login views.
from django.contrib.auth import authenticate, login
from django.contrib import messages
def login_view(request):
if request.method == 'POST':
email = request.POST.get('email', None)
password = request.POST.get('password', None)
otp = request.POST.get('otp', None)
user = authenticate(request, email=email, password=password, otp=otp)
if user is not None:
login(request, user)
# redirect to a success page
return redirect('dashboard')
else:
if password is not None:
# return either email or password incorrect
messages.error(request, "Invalid Email or Password")
return redirect('login')
else:
# return invalid otp
messages.error(request, "Invalid OTP")
return redirect('login')
return render(request, 'login.html')
And at last don't forgot to add AUTHENTICATION_BACKENDS in your settings.py as
AUTHENTICATION_BACKENDS = ['path_to_your.CustomLoginBackend ',]
Yes we can do that using forced login here is an example how i have did this please have a look i have a profile which is one to one relation with user
def login_otp(request):
mobile = request.session['mobile']
context = {'mobile':mobile}
if request.method == 'POST':
otp = request.POST.get('otp')
profile = Profile.objects.filter(mobile=mobile).first()
if otp == profile.otp:
user = User.objects.get(id = profile.user.id)
login(request , user)
return redirect('cart')
else:
context = {'message' : 'Wrong OTP' , 'class' : 'danger','mobile':mobile }
return render(request,'login_otp.html' , context)
return render(request,'login_otp.html' , context)

Why django form valdation error does not work in my form

I want to show user validation error but seems that this is not working in my login form here is the code
my forms.py
class LoginForm(forms.Form):
username = forms.CharField(widget=forms.TextInput())
password = forms.CharField(widget=forms.PasswordInput())
remember_me = forms.BooleanField(required=False, label='Remember Me',help_text='Keep me logged in.',widget=forms.CheckboxInput())
def clean(self, *args, **kwargs):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
if username and password:
user = authenticate(username=username, password=password)
if not user:
raise forms.ValidationError("This user doesn't exist")
if not user.check_password(password):
raise forms.ValidationError("Incorrect Password")
if not user.is_active:
raise forms.ValidationError("User no longer Active")
return super(LoginForm,self).clean(*args,**kwargs)
my views.py for login
def my_login(request):
if 'next' in request.GET:
messages.add_message(request, messages.WARNING, 'To Continue, Please login here!')
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
remember_me = form.cleaned_data['remember_me']
user = authenticate(username=username, password=password)
if user:
login(request, user)
if not remember_me:
request.session.set_expiry(0)
return redirect('accounts:home')
else:
request.session.set_expiry(1209600)
return redirect('accounts:home')
else:
messages.info(request, 'Please check your credentials.')
return redirect('accounts:login')
else:
form = LoginForm()
return render(request, "login.html", {'form': form})
i know i am redirecting the form if form credential is wrong but if i don't i will throw error didn't return a httpresponse it return none instead also want to what is the best way to redirect or show exact validation error of which credential is wrong

How to pass user information to other page in Django 3.0?

I am new Django i am creating a simple login page and wants to redirect to home page with user info as soon as user clicks login button in login form user should be redirected to the home page with username
def login1(req):
if req.method == 'POST':
user = ppl.objects.filter(username = req.POST['text'])
print(req.POST['text'])
pwd = ppl.objects.filter(pwd = req.POST['pass'])
print(req.POST['pass'])
if user and pwd:
return HttpResponseRedirect(reverse('home', {'u':user}))
else:
return render(req,'login.html',{'error':"username and password does not match"})
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)
return redirect('home')
else:
return redirect('login')
else:
return render(request, 'login.html')
And in your home page template or any other template you can call {{ request.user.username }} to see the current logged in user

django login user, after successful login user stay on same page

I have to implement Login in django, But the login can be done at product purchase time, on creating comment, and so on.
Here i am redirecting user on Index page after login.
But i have to make user stay on same page from which(order, rating) page he is login.
How i can do this ?
Here what i have implemented:
def login_view(request):
if request.method=='POST':
form=UserLoginForm(request.POST or None)
if form.is_valid():
email = form.cleaned_data["email"]
password = form.cleaned_data["password"]
try:
user = Customer.objects.get(email=email)
if user.check_password(password) :
if user.is_active and user.is_customer:
if user.mobile_verified :
user = authenticate(username=user.email, password=password)
login(request, user)
if request.POST.get('card_data'):
for items in request.POST.get('card_data').split(","):
cart = Cart(user=user, product_id=items)
cart.save()
total_cart = user.card_user.count()
else:
total_cart = 0
messages.success(request, "Login successfully.")
responss = redirect("Peru:home")
responss.delete_cookie('add_card_token')
return responss
else:
messages.success(request,"Mobile number is not verified")
return redirect("Peru:home")
else :
messages.info(request, "Your account may not be activated")
return redirect("Peru:home")
else:
messages.error(request,"Email or Password does not match")
return redirect("Peru:home")
except Exception as e:
messages.error(request, "User may not exists !")
return redirect("Peru:home")
else:
return redirect("Peru:home", forms=form)
else:
return redirect('Peru:home')
You need to pass next URL in template and in login view check for next url.
In template:
Login
And in login view:
from django.utils.http import is_safe_url
def login(request):
redirect_to = request.POST.get('next', request.GET.get('next', ''))
# check form validity
# authenticate user
if redirect_to and is_safe_url(url=redirect_to, host=request.get_host()):
return redirect(redirect_to)
else:
return redirect('index')