Django - "check_token" always returns TRUE - django

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.

Related

Flask-Mail password token reset not working

The problem I am facing is that the token generated by the password reset does not work. The /reset code works fine, it generates an email with the following url http://127.0.0.1:5000/reset/InBpbG90cGxhbnQxODAxQGdtYWlsLmNvbSI.Y0Gq-A.SUlDTVz5SUYl0VpQQX2UJMzFfJs
( which should supposedly trigger the second code reset/. However instead of directing me to the PasswordForm it just return the error
itsdangerous.exc.BadTimeSignature: Signature b'SUlDTVz5SUYl0VpQQX2UJMzFfJs' does not match
The code used is below: it has two functions the first is to generate the token and send the email, and the second is what happens after the link is clicked.
#users.route('/reset', methods=["GET", "POST"])
def reset():
form = EmailForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first_or_404()
subject = "Password reset requested"
# Here we use the URLSafeTimedSerializer we created in `util` at the
# beginning of the chapter
token = ts.dumps(user.email, salt='recover-key')
recover_url = url_for(
'users.reset_with_token',
token=token,
_external=True)
html = render_template(
'email_password_reset_msg.html',
recover_url=recover_url)
send_email(user.email,'Password Reset Requested', html,user=user.email)
return redirect(url_for('core.index'))
return render_template('email_password_reset.html', form=form)
#users.route('/reset/<token>', methods=["GET", "POST"])
def reset_with_token(token):
try:
password_reset_serializer = URLSafeTimedSerializer(app.config['SECRET_KEY'])
email = password_reset_serializer.loads(token, salt='password-reset-salt', max_age=84600)
except:
flash('The password reset link is invalid or has expired.', 'error')
print('The password reset link is invalid or has expired.', 'error','lol')
return redirect(url_for('core.index'))
form = PasswordForm()
if form.validate_on_submit():
try:
user = User.query.filter_by(email=email).first_or_404()
except:
flash('Invalid email address!', 'error')
return redirect(url_for('login'))
user._password = generate_password_hash(form.password.data)
db.session.add(user)
db.session.commit()
flash('Your password has been updated!', 'success')
return redirect(url_for('users.login'))
return render_template('reset_with_token.html',token=token, form=form)

PasswordResetForm doesn't send email

I'm working on a user system on an app. Everything works fine except one thing.
When I create a user, I generate a password to keep in database and send an email to the new created user to set his own password.
So the password is in the database and I use PasswordResetForm to send an email of password reseting.
Here is the code I use:
reset_password_form = PasswordResetForm(data={'email': user.email})
if reset_password_form.is_valid():
reset_password_form.save(request=request,
use_https=True,
from_email="Webmaster#mysite.com",
html_email_template_name='main/password_reset/password_reset_email.html',
subject_template_name="main/password_reset/password_reset_subject.txt")
And here is the problem, no email is sent.
So to clarify, I already use this Form in case we click on "I forgot my password" and it works very well. So There is no problems of settings for the email server.
As well the reset_password_form.is_valid() is true I can breakpoint in the if.
The user.email exists and contain a real and correct email adress.
I have the feeling that when I call save() on my form it doesn't send the message, did I do a mistake thinking it will do?
My complete view:
def adduser(request, id_user=None):
modify_user = User.objects.get(id=id_user) if id_user is not None else None
if request.method == 'POST':
if modify_user is not None:
userform = EditUserForm(request.POST, instance=modify_user)
else:
userform = AddUserForm(request.POST, instance=modify_user)
profileform = AddProfileForm(request.POST, request.FILES,
instance=modify_user.profile if modify_user is not None else None)
if userform.is_valid() and profileform.is_valid():
user = userform.save(commit=False)
profileuser = profileform.save(commit=False)
if modify_user is not None:
user.save(update_fields=['username', 'first_name', 'last_name', 'email'])
else:
reset_password_form = PasswordResetForm(data={'email': user.email})
if reset_password_form.is_valid():
reset_password_form.save(request=request,
use_https=True,
from_email="Webmaster#mantadivegiliair.com",
html_email_template_name='main/password_reset/password_reset_email.html',
subject_template_name="main/password_reset/password_reset_subject.txt")
user.set_password(User.objects.make_random_password(length=6))
user.save()
profileuser.created_by = request.user
profileuser.user = user
profileuser.save()
profileform.save_m2m()
if modify_user is not None:
messages.add_message(request, messages.SUCCESS,
"{} {} has been updated".format(user.first_name, user.last_name))
else:
messages.add_message(request, messages.SUCCESS,
"{} {} has been created".format(user.first_name, user.last_name))
return redirect('profile', user.id)
else:
for field in userform.errors:
if field == "__all__":
userform['confirm_password'].field.widget.attrs['class'] += ' error'
else:
userform[field].field.widget.attrs['class'] += ' error'
for field in profileform.errors:
profileform[field].field.widget.attrs['class'] += ' error'
else:
userform = AddUserForm(instance=modify_user)
profileform = AddProfileForm(instance=modify_user.profile if modify_user is not None else None)
return render(request, 'main/add_user.html', locals())
The user isn't saved yet when you save the PasswordResetForm. So the save() method won't do anything because it will try to fetch users in the database with the email submitted.
You just need to change the order in which you do things:
else: # user is new user
user.set_password(User.objects.make_random_password(length=6))
user.save()
reset_password_form = ...
reset_password_form.save(...)
profileuser.user = user
...

AttributeError: 'AcceptInvite' object has no attribute 'email'

Im doing some unit testing in my Django project, and am getting error
"AttributeError: 'SignUp' object has no attribute 'email'"
when I run this test.
def test_signup(self):
response = self.c.post('/accounts/signup/', {'email': 'test#test.com', 'password': 'test123', 'password_conf': 'test123',
'org_name': 'test org', 'org_username': 'test org username', 'invite': '4013'})
code = response.status_code
self.assertTrue(code == 200)
The view this is testing simply takes a signup form, and creates a new account with it.
def signup(request):
# """Register a new account with a new org."""
if request.method == "POST":
form = SignUp(request.POST)
if not form.email or not form.password:
raise Exception("Email and Password are required")
if form.password != form.password_conf:
raise Exception("Password does not match confirmation")
if not form.org_name or not form.org_username:
raise Exception('Organization name and username are required')
if not form.invite:
raise Exception('Invitation code is required')
if form.is_valid():
cleaned_data = form.cleaned_data
email = cleaned_data['email']
password = cleaned_data['password']
org_name = cleaned_data['org_name']
org_username = cleaned_data['org_username']
invite_token = cleaned_data['invite']
invitation = OrgInvite.objects.get(token=invite_token)
if invitation.used:
raise Exception("invitation code is invalid")
account = Account(email=email, password=password)
account.save()
org = Org(org_name=org_name, org_username=org_username)
org.save()
invitation.used = False
invitation.save()
login(request)
# Send Email
md = mandrill.Mandrill(settings.MANDRILL_API_KEY)
t = invite_token.replace(' ', '+')
url = "https://www.humanlink.co/verify/{}".format(t)
message = {
'global_merge_vars': [
{'name': 'VERIFICATION_URL', 'content': url},
],
'to': [
{'email': account.email},
],
}
message['from_name'] = message.get('from_name', 'Humanlink')
message['from_email'] = message.get('from_email', 'support#humanlink.co')
try:
md.messages.send_template(
template_name='humanlink-welcome', message=message,
template_content=[], async=True)
except mandrill.Error as e:
logging.exception(e)
raise Exception('Unknown service exception')
The Signup form has an email field, and the data in request.POST should have the email I am sending it with my Client's post method being used in my unit test, so I am really not sure why it still wouldn't have an 'email' attribute.
Form:
class SignUp(forms.Form):
email = forms.EmailField()
password = forms.CharField()
password_conf = forms.CharField()
org_name = forms.CharField()
org_username = forms.CharField()
invite = forms.CharField()
You code suffers from multiple errors. To address your question, in your view method signup you were creating a form, but you shouldn't do form.email or form.password because that's not how django handles form data.
Other related issues, first, you need to call form.is_valid() before you could get any data from form object. Even so, you should use form.cleaned_data['email'] to access the form data.
Secondly. You shouldn't do empty check like that. If you put:
email = forms.EmailField(required=True)
django will automatically verify the emptiness for you already.
Thirdly, raising Exception in views.py method doesn't get your form to return the message to the template you want. If you have custom form validation, you should do it in form class's clean method.
Please check django doc about how to use form properly.

Raising validation error in django form for the api

I am new to django and python development and am naive in my understanding of how to handle exceptions.
I am registering a user through an api call by calling the method register, and would like to push the success status or the error messages while registration.
def register(self,request, **kwargs):
try:
data = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
email = data['email']
password = data['password']
firstname = data['firstname']
lastname = data['lastname']
newdata = {'email' : email , 'password1': password , 'password2':password, 'firstname':'firstname' , 'lastname':lastname }
registrationform = UserEmailRegistrationForm(newdata)
print registrationform.errors.as_text
print registrationform.cleaned_data
cleaned_data = registrationform.cleaned_data
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)
new_user = RegistrationProfile.objects.create_inactive_user(cleaned_data['username'],cleaned_data['email'],cleaned_data['password1'], site)
signals.user_registered.send(sender=self.__class__,
user=new_user,
request=request,**cleaned_data)
registerUser = collections.OrderedDict()
registerUser['return']='0'
registerUser['code']='0'
registerUser['message']='registered user'
return HttpResponse(registerUser, content_type="application/json")
except Exception, e:
logging.exception(e)
registerUser = collections.OrderedDict()
registerUser['return']='0'
registerUser['code']='0'
registerUser['message']='registered user'
return HttpResponse(registerUser, content_type="application/json")
When I execute this, for example with an already registered email, I get the following in registrationform.errors.as_text
bound method ErrorDict.as_text of {'email': [u'A user with that email already exists.']}>
What would be the right way to code exceptions so that I can pass the success message if the form was validated and user was registered, and the error message if there was a validation error?
Any help is much appreciated!
You might want to have a look in the form's is_valid() method: https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.is_valid
For example
if registrationform.is_valid():
//do your stuff
....
register['error'] = False
else:
//return the errors
registerUser['message'] = _('Oops! Please fix the following errors')
register['error'] = True
register['errors'] = registrationform.errors
....

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.