Getting user credentials by email - django

I'm making a small solution to restore user credentials. I decided to try to do it with my algorithm. I request the user's mail and compare it with the database of postal addresses. If the mail exists, I want to send the user his credentials (login and password). I have already done the acceptance and verification of mail, as well as configured the sending of emails to postal addresses. But how to get access to credentials with only mail and the fact that the user is not logged in, I do not understand. I know that maybe my solution based on security is not very good, but there was interest and I really want to understand how to do it.
It may be possible to make a quick login and get data from there, or it can do without it? As a result, I have to send the used as a message to views.py this data.
views.py
def recovery(request):
if request.user.is_authenticated:
return redirect("/accounts/exit/")
else:
if request.method == 'POST':
email_form = UserRecoveryForm(request.POST)
if email_form.is_valid():
email = email_form.cleaned_data['email']
try:
send_mail("Восстановление учетных данных.", "message", "from#gmail.com", [email], fail_silently=False)
except BadHeaderError:
return HttpResponse('Ошибка в теме письма.')
return render(request, 'registration/recovery_done.html')
else:
email_form = UserRecoveryForm()
return render(request, 'registration/recovery.html', {'email_form': email_form})
Just in case forms.py
class UserRecoveryForm(forms.ModelForm):
email = forms.EmailField(label='Почта', help_text='На почту мы отправим дополнительную информация в случае необходимости')
class Meta:
model = User
fields = ('email',)
def clean_email(self):
email = self.cleaned_data.get('email')
username = self.cleaned_data.get('username')
if (not(email and User.objects.filter(email=email).exclude(username=username).exists())):
raise forms.ValidationError('Такой почты не существует.')
return email

Related

Django - "check_token" always returns TRUE

When a user registers on my app, an account verification link is sent to his email. When clicking on the link the first time, everything is fine and the account is verified, but when clicking on the same link again, the validation goes through, whereas it should raise an "authentication failed" error, since the "check_token" should return false, right?
Here's the verification serializer:
class VerifyAccountSerializer(serializers.Serializer):
uid = serializers.CharField(min_length=1, write_only=True)
token = serializers.CharField(min_length=1, write_only=True)
class Meta:
fields = ['uid', 'token']
def validate(self, attrs):
uid = attrs.get('uid')
token = attrs.get('token')
uidb64 = force_text(urlsafe_base64_decode(uid))
user = UserAccount.objects.get(pk=uidb64)
if user is None:
raise AuthenticationFailed('Invalid account. Please contant support')
if not PasswordResetTokenGenerator().check_token(user, token):
raise AuthenticationFailed('Account verify link is invalid. Please contant support.')
user.is_guest = False
user.save()
return user
And the view function:
#api_view(['POST'])
def verify_account(request):
if request.method == 'POST':
data = {}
serializer = VerifyAccountSerializer(data=request.data)
if serializer.is_valid():
user = serializer.validated_data
data['user'] = UserSerializer(user).data
data['token'] = AuthToken.objects.create(user)[1]
# delete previous token
tokens = AuthToken.objects.filter(user=user.id)
if len(tokens) > 1:
tokens[0].delete()
return Response(data, status=status.HTTP_200_OK)
data = serializer.errors
return Response(data, status=status.HTTP_400_BAD_REQUEST
It's kinda weird why it's not raising an error, because, in my other serializer for resetting the password via a link as well, I have the exact same thing going on, except there's one more extra field for the password, and if click on that link for the second time, I get a validation error.

django email fails to send in production, works for errors, fails for a particular view

I'm trying to automatically send an email with a django contact us form.
The contact form view works in development properly via django.core.mail.backends.console.EmailBackend
Sending of emails to admins for errors in procution works properly.
However sending emails for the contact view/form doesn't work in production.
No errors are produced in production when submitting the contact form.
the post request appears in the logs, but there isn't any other useful information (that I can see) apart from that.
I'm not sure how best to pinpoint the error?
view:
#require_http_methods(['GET', 'HEAD', 'POST'])
def contact_view(request):
form = ContactForm()
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
contact_name = form.cleaned_data.get('contact_name', '')
contact_email = form.cleaned_data.get('contact_email', '')
email_content = form.cleaned_data.get('message', '')
email = EmailMessage(
subject="New contact form submission",
body=email_content,
to=('support#somedomain.com',),
from_email=f'{contact_name} <{contact_email}>',
reply_to=(contact_email,),
)
email.send()
messages.success(request,
"Your email has been sent. Thanks for contacting us, we'll get back to you shortly")
return redirect('contact')
context = {'form': form}
return render(request, 'pages/contact.html', context)
production email settings:
DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL',
default=' <noreply#some_domain.com>')
EMAIL_SUBJECT_PREFIX = env('DJANGO_EMAIL_SUBJECT_PREFIX', default='[some_domain]')
SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL)
# Anymail with Mailgun
INSTALLED_APPS += ("anymail", )
ANYMAIL = {
"MAILGUN_API_KEY": env('DJANGO_MAILGUN_API_KEY'),
"MAILGUN_SENDER_DOMAIN": env('MAILGUN_SENDER_DOMAIN')
}
EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend"
Your admin emails work because they are using DEFAULT_FROM_EMAIL which is allowed.
Your email provider may not allow you to send emails from the address entered on the contact form.
You should use your email address for the from_email, and use the email address from the form as the reply_to email address.

Django Custom User Email Account Verification

I am looking to add email account verification in Django. I have attempted using the django-registration app to do so, but it doesn't appear that it has been updated to be fully compatible with custom user models which causes too many problems. Is there another reliable and well-documented app out there which will allow me to send a verification email on user registration in django?
How I handle the email registration personally:
First of all, my Profile extending Django Users (models.py):
class Profile(models.Model):
user = models.OneToOneField(User, related_name='profile') #1 to 1 link with Django User
activation_key = models.CharField(max_length=40)
key_expires = models.DateTimeField()
In forms.py, the Registration class :
class RegistrationForm(forms.Form):
username = forms.CharField(label="",widget=forms.TextInput(attrs={'placeholder': 'Nom d\'utilisateur','class':'form-control input-perso'}),max_length=30,min_length=3,validators=[isValidUsername, validators.validate_slug])
email = forms.EmailField(label="",widget=forms.EmailInput(attrs={'placeholder': 'Email','class':'form-control input-perso'}),max_length=100,error_messages={'invalid': ("Email invalide.")},validators=[isValidEmail])
password1 = forms.CharField(label="",max_length=50,min_length=6,
widget=forms.PasswordInput(attrs={'placeholder': 'Mot de passe','class':'form-control input-perso'}))
password2 = forms.CharField(label="",max_length=50,min_length=6,
widget=forms.PasswordInput(attrs={'placeholder': 'Confirmer mot de passe','class':'form-control input-perso'}))
#recaptcha = ReCaptchaField()
#Override clean method to check password match
def clean(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password1 != password2:
self._errors['password2'] = ErrorList([u"Le mot de passe ne correspond pas."])
return self.cleaned_data
#Override of save method for saving both User and Profile objects
def save(self, datas):
u = User.objects.create_user(datas['username'],
datas['email'],
datas['password1'])
u.is_active = False
u.save()
profile=Profile()
profile.user=u
profile.activation_key=datas['activation_key']
profile.key_expires=datetime.datetime.strftime(datetime.datetime.now() + datetime.timedelta(days=2), "%Y-%m-%d %H:%M:%S")
profile.save()
return u
#Sending activation email ------>>>!! Warning : Domain name is hardcoded below !!<<<------
#The email is written in a text file (it contains templatetags which are populated by the method below)
def sendEmail(self, datas):
link="http://yourdomain.com/activate/"+datas['activation_key']
c=Context({'activation_link':link,'username':datas['username']})
f = open(MEDIA_ROOT+datas['email_path'], 'r')
t = Template(f.read())
f.close()
message=t.render(c)
#print unicode(message).encode('utf8')
send_mail(datas['email_subject'], message, 'yourdomain <no-reply#yourdomain.com>', [datas['email']], fail_silently=False)
Now, in views.py, we need to handle all that, let's go :
The register view:
def register(request):
if request.user.is_authenticated():
return redirect(home)
registration_form = RegistrationForm()
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
datas={}
datas['username']=form.cleaned_data['username']
datas['email']=form.cleaned_data['email']
datas['password1']=form.cleaned_data['password1']
#We generate a random activation key
salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
usernamesalt = datas['username']
if isinstance(usernamesalt, unicode):
usernamesalt = usernamesalt.encode('utf8')
datas['activation_key']= hashlib.sha1(salt+usernamesalt).hexdigest()
datas['email_path']="/ActivationEmail.txt"
datas['email_subject']="Activation de votre compte yourdomain"
form.sendEmail(datas)
form.save(datas) #Save the user and his profile
request.session['registered']=True #For display purposes
return redirect(home)
else:
registration_form = form #Display form with error messages (incorrect fields, etc)
return render(request, 'siteApp/register.html', locals())
The activation views :
#View called from activation email. Activate user if link didn't expire (48h default), or offer to
#send a second link if the first expired.
def activation(request, key):
activation_expired = False
already_active = False
profile = get_object_or_404(Profile, activation_key=key)
if profile.user.is_active == False:
if timezone.now() > profile.key_expires:
activation_expired = True #Display: offer the user to send a new activation link
id_user = profile.user.id
else: #Activation successful
profile.user.is_active = True
profile.user.save()
#If user is already active, simply display error message
else:
already_active = True #Display : error message
return render(request, 'siteApp/activation.html', locals())
def new_activation_link(request, user_id):
form = RegistrationForm()
datas={}
user = User.objects.get(id=user_id)
if user is not None and not user.is_active:
datas['username']=user.username
datas['email']=user.email
datas['email_path']="/ResendEmail.txt"
datas['email_subject']="Nouveau lien d'activation yourdomain"
salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
usernamesalt = datas['username']
if isinstance(usernamesalt, unicode):
usernamesalt = usernamesalt.encode('utf8')
datas['activation_key']= hashlib.sha1(salt+usernamesalt).hexdigest()
profile = Profile.objects.get(user=user)
profile.activation_key = datas['activation_key']
profile.key_expires = datetime.datetime.strftime(datetime.datetime.now() + datetime.timedelta(days=2), "%Y-%m-%d %H:%M:%S")
profile.save()
form.sendEmail(datas)
request.session['new_link']=True #Display: new link sent
return redirect(home)
Finally, in urls.py:
url(r'^register/$', 'register'),
url(r'^activate/(?P<key>.+)$', 'activation'),
url(r'^new-activation-link/(?P<user_id>\d+)/$', 'new_activation_link'),
With all that you should have something to start with, use the appropriate templatetags in the .txt emails and HTML and it should work.
NB: This code isn't perfect, there is duplication (for instance, the generation of the random key could be defined in a function), but it does the job. Also: the activation key is not generated using proper cryptographic functions. An alternative is to use a function like the following to generate the keys:
from django.utils.crypto import get_random_string
def generate_activation_key(username):
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!##$%^&*(-_=+)'
secret_key = get_random_string(20, chars)
return hashlib.sha256((secret_key + username).encode('utf-8')).hexdigest()
NB2: Django send_mail doesn't provide any tools to authenticate your emails. If you want to authenticate your emails (DKIM, SPF), I advise you to look into this: https://djangosnippets.org/snippets/1995/
NB3: There is a security issue with the view new_activation_link: it should check if the user requesting the re-send is the right one and also if he isn't already authenticated. I let you correct that.
You may also be interested in the simple but powerful django-verified-email-field.
Simply use VerifiedEmailField in Your forms:
from django import forms
from verified_email_field.forms import VerifiedEmailField
class RegistrationForm(forms.ModelForm):
email = VerifiedEmailField(label='email', required=True)
Or in Your models:
from django.db import models
from verified_email_field.models import VerifiedEmailField
class User(models.Model):
email = VerifiedEmailField('e-mail')
It renders two input fields: e-mail and verification code. The verification code is sent to the e-mail address using AJAX or during field's clean if there is no valid code for given e-mail, so it works even without javascript.

Django send_mail() in GAE

I want a logged in user to be able to send a copy of the model object they created that has been saved in the database. Am using the get(pk=id) to recognize the particular one the user wants to send. The problem is, the send_mail() doesn't recognize the recipient email (to).
#login_required
def email_query(request, id):
history = Carloan_form.objects.get(pk=id)
subject = 'Nigerian Loan Calculator Query e-mail'
from_email = 'xxxx#gmail.com'
email = request.user.email
to = "email"
send_mail(subject,get_template('carloan/loancalc-query.txt').render(Context({'history':history})),\
from_email,[to], fail_silently=False)
return HttpResponse('sent')
Update
#login_required
def email_query(request, id):
history = Carloan_form.objects.get(pk=id)
subject = 'Nigerian Loan Calculator Query e-mail'
from_email = 'ajibike.ca#gmail.com'
email = request.user.email
send_mail(subject,get_template('carloan/loancalc-query.txt').render(Context({'history':history})),\
from_email,[email,], fail_silently=False)
return HttpResponse('/history_query_sent/')
Just decided to pass the email straight into the send_mail() and it worked. Thanks
Because you've set to to the string "email". I doubt that is what you wanted to do.
Why not pass the email variable directly into the send_mail call?

django testing problems

This is my view that I want to be tested.
def logIn(request):
"""
This method will log in user using username or email
"""
if request.method == 'POST':
form = LogInForm(request.POST)
if form.is_valid():
user = authenticate(username=form.cleaned_data['name'],password=form.cleaned_data['password'])
if user:
login(request,user)
return redirect('uindex')
else:
error = "Nie prawidlowy login lub haslo.Upewnij sie ze wpisales prawidlowe dane"
else:
form = LogInForm(auto_id=False)
return render_to_response('login.html',locals(),context_instance=RequestContext(request))
And here's the test
class LoginTest(unittest.TestCase):
def setUp(self):
self.client = Client()
def test_response_for_get(self):
response = self.client.get(reverse('logIn'))
self.assertEqual(response.status_code, 200)
def test_login_with_username(self):
"""
Test if user can login wit username and password
"""
user_name = 'test'
user_email = 'test#test.com'
user_password = 'zaq12wsx'
u = User.objects.create_user(user_name,user_email,user_password)
response = self.client.post(reverse('logIn'),data={'name':user_name,'password':user_password},follow=True)
self.assertEquals(response.request.user.username,user_name)
u.delete()
And when i run this test i got failure on test_login_with_username:
AttributeError: 'dict' object has no attribute 'user'
When i use in views request.user.username in works fine no error this just fails in tests. Thanks in advance for any help
edit:Ok I replace the broken part with
self.assertEquals(302, response.status_code)
But now this test breaks and another one too.
AssertionError: 302 != 200
Here is my code for the view that now fail. I want email and username to be unique.
def register(request):
"""
Function to register new user.
This function will have to care for email uniqueness,and login
"""
if request.method == 'POST':
error=[]
form = RegisterForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
email = form.cleaned_data['email']
if form.cleaned_data['password'] == form.cleaned_data['password_confirmation']:
password = form.cleaned_data['password']
if len(User.objects.filter(username=username)) == 0 and len(User.objects.filter(email=email)) == 0:
#email and username are bouth unique
u = User()
u.username = username
u.set_password(password)
u.email = email
u.is_active = False
u.is_superuser = False
u.is_active = True
u.save()
return render_to_response('success_register.html',locals(),context_instance=RequestContext(request))
else:
if len(User.objects.filter(username=username)) > 0:
error.append("Podany login jest juz zajety")
if len(User.objects.filter(email=email)) > 0:
error.append("Podany email jest juz zajety")
else:
error.append("Hasla nie pasuja do siebie")
#return render_to_response('register.html',locals(),context_instance=RequestContext(request))
else:
form = RegisterForm(auto_id=False)
return render_to_response('register.html',locals(),context_instance=RequestContext(request))
And here is the test that priviously work but now it is broken
def test_user_register_with_unique_data_and_permission(self):
"""
Will try to register user which provided for sure unique credentials
And also make sure that profile will be automatically created for him, and also that he he have valid privileges
"""
user_name = 'test'
user_email = 'test#test.com'
password = 'zaq12wsx'
response = self.client.post(reverse('register'),{'username': user_name,'email':user_email,
'password':password,'password_confirmation':password},follow=True)
#check if code is 200
self.assertEqual(response.status_code, 200)
u = User.objects.get(username=user_name,email = user_email)
self.assertTrue(u,"User after creation coudn't be fetched")
self.assertFalse(u.is_staff,msg="User after registration belong to staff")
self.assertFalse(u.is_superuser,msg="User after registration is superuser")
p = UserProfile.objects.get(user__username__iexact = user_name)
self.assertTrue(p,"After user creation coudn't fetch user profile")
self.assertEqual(len(response.context['error']),0,msg = 'We shoudnt get error during valid registration')
u.delete()
p.delete()
End here is the error:
AssertionError: We shoudnt get error during valid registration
If i disable login test everything is ok. How this test can break another one? And why login test is not passing. I try it on website and it works fine.
The documentation for the response object returned by the test client says this about the request attribute:
request
The request data that stimulated the response.
That suggests to me one of two things. Either it's just the data of the request, or it's request object as it was before you handled the request. In either case, you would not expect it to contain the logged in user.
Another way to write your test that the login completed successfully would be to add follow=False to the client.post call and check the response code:
self.assertEquals(302, response.status_code)
This checks that the redirect has occurred.
response.request is not the HttpRequest object in the view you are expecting. It's a dictionary of data that stimulated the post request. It doesn't have the user attribute, hence the AttributeError
You could rewrite your test to:
use the RequestFactory class introduced in Django 1.3 and call logIn in your test directly instead of using client.post.
inspect client.session after the post to check whether the user has been logged in.
Why one failing test can break another
When you edited the question, you asked
How this test can break another one?
The test_login_with_username was failing before it reached u.delete, so the user created in that test was not deleted. That caused test_user_register_with_unique_data_and_permission because the user test already existed.
If you use the django.test.TestCase class, the database will be reset in between each test, so this wouldn't be a problem.