How to modify my login to verify email? - django

I have already used login class
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
And views file of my app
from .forms import LoginForm
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(username=cd['username'],password=cd['password'])
if user.is_active:
login(request, user)
return HttpResponse('Authenticated!')
else:
return HttpResponse('Disabled account')
else:
form = LoginForm()
return render(request, 'account/login.html', {'form': form})
(hunter) provides email verifier.This is HTTP request example
GET https://api.hunter.io/v2/email-verifier?email=steli#close.io
How to modify my login and views files?

Try to use the code below :
import urllib2
get_request = urllib2.urlopen('https://api.hunter.io/v2/email-verifier?email=' + username)
then the get_request variable will contain a JSON object as mentioned in hunter documentation.
the get_request will be added in after the cd = form.cleaned_data

Related

Django - How to allow registration only for predefined list of e-mails/usernames

I have a following simple view in my views.py for registration on my django site:
def register_user(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
messages.succes(request, ('You have registered'))
return redirect('home')
else:
form = UserCreationForm()
context = {'form': form}
return render(request, 'register.html', context)
That approach would allow anyone to register but I want to allow only selected people to be able to register. I have a simple model for my database
class EmailList(models.Model):
email_addres = models.CharField(max_length=300, blank=True)
def __str__(self):
return self.email_addres
with some e-mail addreses (my site doesn't have usernames, your username is an email addres) and I want to allow registration only for email addresses that are in that database. How would I perform such check?
There is a functionality in Django that limits an access to users that pass a certain test: https://docs.djangoproject.com/en/3.2/topics/auth/default/#limiting-access-to-logged-in-users-that-pass-a-test
You need to create a test function (verifying that the user is in allowed users list), and then use user_passes_test decorator on the view. In case you are using class based views, you need to use a UserPassesTestMixin.
Assuming your code works properly, just grab the contents of the AllowedUsers model and check whether the username is in the queryset.
models.py
class AllowedUsers(models.Model):
allowed_email = models.EmailField(max_length=256)
def __str__(self):
return self.allowed_email
views.py
def register_user(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
object = form.save(commit=False)
allowed_emails = [user.allowed_email for user in AllowedUsers.objects.all()]
if object['username'] in allowed_emails:
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
messages.success(request, ('You have registered'))
return redirect('home')
else:
return redirect('/login/?next=%s' % request.path)
I should say that if it were me, I'd be doing this while overriding the form_valid method of the default LoginView
Alternative views.py
from django.contrib.auth import views as auth_views
from django.forms import ValidationError
class LoginView(auth_views.LoginView):
def form_valid(self, form):
allowed_emails = [user.allowed_email for user in AllowedUsers.objects.all()]
if form.cleaned_data['username'] in allowed_emails:
return super().form_valid(form)
else:
self.add_error('username', ValidationError("The provided username is not allowed"))

Django LoginRequiredMixedIn doesnn't let users sign in

I am building an app that allows users to view posts. However, every time I try to log in if I do not set the LoginRequiredMixin the user will still be able to view posts after logging out. But when I set the LoginRequiredMixin everytime user puts info it keeps going back to main page and nothing happens.
my home/views.py
#login_required
def home(request):
posts = Post.objects.all()
context = {'posts':posts}
return render(request, 'home/home.html', context)
class PostListView(ListView):
model = Post
template_name = 'home/home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
ordering = ['-date_posted']
my home/urls.py:
path('',views.PostListView.as_view(), name='home'),
my main/urls.py
urlpatterns=[
path('signup/',views.signup,name='signup'),
path('signin/',views.user_login, name='user_login'),
path('signout/', views.user_logout, name='user_logout'),
path('',views.main_page,name='main_page'),
path('edit/', views.edit_profile, name='edit_profile'),
path('', include('django.contrib.auth.urls')),
]
my main/views.py:
def main_page(request):
return render(request,'main/user_login.html')
#login_required
def user_logout(request):
logout(request)
return redirect('main:main_page')
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save()
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=user.username, password=raw_password)
return redirect('main:main_page')
else:
form = SignUpForm()
return render(request, 'main/signup.html', {'form': form})
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = authenticate(request, username=username, password=password)
if user is not None:
return redirect(reverse('home:home'))
else:
messages.error(request,'Sorry, the username or password you entered is not valid please try again.')
return HttpResponseRedirect('/')
else:
form=AuthenticationForm()
return render(request, 'main/user_login.html', {"form":form})
int my settings.py I only have:
LOGIN_URL = 'main:main_page'
I have been working a lot on this and I cannot find how to fix this issue.
Thanks in advance!
I guess the authentication is failing. However here is some snippet you can try.
from django.shortcuts import render,redirect
from django.contrib.auth import login,logout
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.decorators import login_required
def loginView(request):
if request.method == 'POST':
# Authentication form is provided by django, it will parse username and password
# in the post request
form = AuthenticationForm(data=request.POST)
if form.is_valid():
user = form.get_user()
login(request, user)
return redirect('home:home')
else:
form = AuthenticationForm()
return render(request, 'main/user_login.html', context={'form': form})
#login_required
def logout_request(request):
logout(request)
return redirect('home:user_login')
In settings.py make sure you have following properties set:
LOGIN_URL = reverse_lazy('home:user_login')
LOGIN_REDIRECT_URL = reverse_lazy('home:home')
LOGOUT_REDIRECT_URL = reverse_lazy('home:user_login')
Note: If you are using custom made user(other than default user model provided by djnago) then make sure you have following property in settings.py set, otherwise AuthenticationForm won't work.
AUTH_USER_MODEL = 'AppName.YourCustomUserModel'

How can i create a login view after registration?

I create models,forms and views for registrarion and i want to create a login view so that after registration user can login.
models.py
from django.contrib.auth.models import AbstractUser
from django_countries.fields import CountryField
g_CHOICES = (('male','male'),('female','female'))
class User(AbstractUser):
gender = models.CharField(max_length=100,choices=g_CHOICES,default="male")
country = CountryField()
location = models.CharField(max_length=30, blank=True)
forms.py
g_CHOICES = (('male','male'),('female','female'))
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
gender = forms.ChoiceField(choices=g_CHOICES)
country = CountryField().formfield()
location = forms.CharField(max_length=30,)
class Meta:
model = User
fields = ['first_name','last_name','username','email',
'password1','password2','gender',
'country','location']
views.py
def register(request):
if request.method == 'POST':
rform = UserRegisterForm(request.POST)
if rform.is_valid():
rform.save()
username = rform.cleaned_data.get('username')
messages.success(request,('Account created for '+str(username)))
return redirect('/')
else:
rform = UserRegisterForm()
return render(request,'reg.html',{'rform':rform})
Now i want to create a view for login please someone help
You need a view that takes the user's username and password from the POST request, then authenticates them and logs them in using 'authenticate' and 'login' from django.contrib.auth package.
from django.contrib.auth import login, authenticate
from django.views import View
class HandleLogin(View):
def get(self, request):
return render(request, "login.html", {})
def post(self, request):
username= request.POST.get("username")
password = request.POST.get("password")
user = authenticate(username, password)
if user is not None:
if user.is_active:
login(request, user)
# Do something for succesfull logged in
else:
# Do something else because user is not active
else:
# Do something about user not existing
For more information: https://docs.djangoproject.com/en/2.2/topics/auth/default/
You can use something like below one:
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 now logged in')
return redirect('dashboard')
else:
messages.error(request, 'Invalid credentials')
return redirect('login')
else:
return render(request, 'accounts/login.html')
Or if you are using a django form you can do this way too and this is more preferred way:
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(request,
username=cd['username'],
password=cd['password'])
if user is not None:
login(request, user)
return HttpResponse('Authenticated '\
'successfully')
else:
return HttpResponse('Invalid login')
else:
form = LoginForm()
return render(request, 'account/login.html', {'form': form})

Django.contrib.auth.login is not working after i redirect to a different url

The login function is not working , after i call login , authenticated is set 'true' but after i redirect to 'main' view authenticated is set 'false'. How to keep the user logged in even after redirection?
class LoginForm(forms.Form):
user = forms.CharField()
password = forms.CharField()
def login(self):
try:
cred = users.objects.get(username = user)
if password==cred.password):
return (True, cred)
return (False, 'Invalid Password.')
except:
return (False, 'Not exist')
from django.contrib.auth import login as auth_login
def login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
valid, message = form.login()
if valid:
auth_login(request, message)
print(request.user.is_authenticated)
# this is not working
return redirect(main)
else:
return redirect(login)
form = LoginForm()
args = {'form': form}
return render(request, 'accounts/login.html', args)
def main(request):
print(request.user.is_authenticated)
You shouldn't write check your user credentials in form class. Do it in your login view. Example:
# views.py
from django.contrib.auth import authenticate, login
from django.urls import reverse
from django.shortcuts import redirect, render
def login_view(request): #changed_the name shouldn't be login
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
user = authenticate(username, password)
if user:
login(user)
return redirect(reverse("main"))
else:
return redirect(reverse("login"))
form = LoginForm()
args = {"form": form}
return render(request, 'accounts/login.html', args)
# urls.py
urlpatterns = [
path("login/", views.login_view, name="login"), # <-- really important
path("main/", views.main_view, name="main")
]
To summarize - to redirect to another page use redirect function. If you set name parameter in url of you view, you can reffer to this view using reverse. Also don't reinvent the wheel and write your own authentication function. Django provides: authenticate(username, password) and login(user) function.

How do you enforce password complexity at user registration with Django authentication?

I'm using the built in Django authentication application. By default it has no password complexity so I'm trying to enable that.
I did find this documentation: https://docs.djangoproject.com/en/1.11/topics/auth/passwords/#module-django.contrib.auth.password_validation
But it specifically calls out that validators aren't applied when a user is created so it's no help to me.
I would really love to see a github project that uses this authentication app so I can see how to properly use this in a project.
Here are my forms.py and views.py files:
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth import password_validation
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(label="Password", widget=forms.PasswordInput)
password2 = forms.CharField(label="Repeat Password", widget=forms.PasswordInput)
class Meta:
model = User
fields = ('username', 'first_name', 'email')
def clean_password2(self):
cd = self.cleaned_data
if cd['password'] != cd['password2']:
raise forms.ValidationError('Passwords don\'t match.')
return cd['password2']
class UserEditForm(forms.ModelForm):
class Meta:
model = User
fields = {'first_name', 'last_name', 'email'}
views.py
from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from .forms import LoginForm, UserRegistrationForm, UserEditForm
from django.contrib.auth.decorators import login_required
from django.contrib import messages
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(username=cd['username'], password=cd['password'])
if user is not None:
if user.is_active:
login(request, user)
return HttpResponse('Authenticated successfully')
else:
return HttpResponse('Disabled account')
else:
return HttpResponse('Invalid login')
else:
form = LoginForm()
return render(request, 'login.html', {'user_form': form})
def register(request):
if request.method == 'POST':
user_form = UserRegistrationForm(request.POST)
if user_form.is_valid():
# create a new user object but avoid saving it yet
new_user = user_form.save(commit=False)
# set the pw
new_user.set_password(user_form.cleaned_data['password'])
# save the user object
new_user.save()
cd = user_form.cleaned_data
user = authenticate(username=cd['username'], password=cd['password'])
login(request, user)
return redirect('/plans/new')
else:
user_form = UserRegistrationForm()
return render(request, 'registration/register.html', {'user_form': user_form})
#login_required
def edit(request):
if request.method == 'POST':
user_form = UserEditForm(instance=request.user, data=request.POST)
if user_form.is_valid():
user_form.save()
messages.success(request, 'Profile updated successfully')
return redirect('/plans')
else:
messages.error(request, 'Error updating profile.')
else:
user_form = UserEditForm(instance=request.user)
return render(request, 'registration/edit.html', {'user_form': user_form})