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)
Related
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.
I have a django project where I am doing google oauth2. I click on a google signin button, I receive a post request from Googles api, and then I interpret that request and want to redirect the user to a page where they can create their own account.
Right now everything appears to work up until the redirect is suppose to happen. The terminal where my django project is running shows that it was successful (the print statements I wrote to confirm it reaches the render function work, and I see a 200 response also), but I remain on the login page.
I am wondering if the redirect and render are happening on another website session, or otherwise somewhere besides where the user is currently on the website?
Here is the code for my google webhook:
token = request.POST.get('idtoken')
print(token)
try:
idinfo = id_token.verify_oauth2_token(token, requests.Request(), settings.GOOGLE_CLIENT_ID)
print(idinfo)
print('got past token')
google_user_id = idinfo['sub']
google_email = idinfo['email']
try: # authenticates user who already exists as a google signed in user.
user_from_sub = User.objects.get(google_sub_id=google_user_id)
user = user_from_sub.get_user_object()
if user.type == Types.BUSINESS:
backend = 'user_accounts.auth_backends.BusinessAuthBackend'
login(request, user, backend=backend) # TODO: add auth backend cred
elif user.type == Types.CONSUMER:
backend = 'user_accounts.auth_backends.ConsumerAuthBackend'
login(request, user, backend=backend) # TODO: add auth backend cred
else:
login(request, user)
print('logged in')
return redirect(reverse('home'))
except: # user doesn't yet exist, with specified sub id
idinfo['account_type'] = 'consumer'
print(request.GET)
print('creating account')
url = f'http://localhost:8000/oauth2/google/account-creation/?{urllib.parse.urlencode(idinfo)}'
return redirect(url)
except ValueError:
print("authentication failed due to an error")
Here is the code for my account creation view:
def create_google_oauth_user_view(request, *args, **kwargs):
""""""
print('hello')
print(request.GET)
print(request.body)
account_type = request.GET.get('account_type')
idinfo = request.GET
print(f'idinfo: {idinfo}')
if idinfo: # user data was passed
user = User.objects.filter(email=idinfo['email']).first()
if user:
user = user.get_user_object()
else: # no user_info was passed
return HttpResponse(status=400)
if account_type == 'business': # add to special business sign up page
if request.method == 'POST':
form = BusinessGoogleSignUpForm(request.POST, request.FILES, idinfo=idinfo)
if form.is_valid():
data = form.save()
messages.success(request, 'Account Creation Successful')
login(request, data, backend='user_accounts.auth_backends.BusinessAuthBackend')
return redirect(reverse('accounts:add_profile_picture', kwargs={'user_id': data.id}))
else:
form = BusinessGoogleSignUpForm(idinfo=idinfo)
elif account_type == 'consumer': # for regular consumer users
print('got to consumer')
if request.method == 'POST':
form = ConsumerGoogleSignUpForm(request.POST, request.FILES, idinfo=idinfo)
if form.is_valid():
data = form.save()
messages.success(request, 'Account Creation Successful')
login(request, data, backend='user_accounts.auth_backends.ConsumerAuthBackend')
return redirect(reverse('accounts:add_profile_picture', kwargs={'user_id': data.id}))
else:
form = ConsumerGoogleSignUpForm(idinfo=idinfo)
else: # no user type was specified
return HttpResponse(status=404)
print('got to context')
context = {
'user': user,
'form': form,
}
return render(request, 'oauth/google/account_creation.html', context)
As it stands the code always gets to the 'got to context' print statement and returns 200. Any advice or suggestions are welcome.
Have you tried adding an else statement for if the form isn't valid in post requests? If I'm reading it right then, if your form isn't valid, it will just continuously re-render with a pre-populated form with the data you submitted.
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
....
I am writing django app that as a beckend is using mongodb. I am curently writing register part. Here is how I connecto to database in settings.py
if socket.gethostname() == "Production server":
CON = Connection()
DB = CON.fish
else:
CON = Connection()
DB = CON.test
DB.user.ensure_index([("username", ASCENDING),("email",ASCENDING)],unique = True)#,drop_dups=True
Here is mye register view:
def register(request):
"""
handle user registration
code variable is for testing purposes
"""
if request.method== 'GET':
form = RegisterForm(auto_id=False)
code = 1
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
elif request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
password = form.cleaned_data['password']
password_confirmation = form.cleaned_data['password_confirmation']
if password == password_confirmation:
login = form.cleaned_data['login']
email = form.cleaned_data['email']
newsletter = form.cleaned_data['newsletter']
key = register_user(login,email,password,newsletter)
if key:
#send email
send_mail("Dziękujemy za rejestrację"," Klucz aktywacyjny to " + key,settings.EMAIL_HOST_USER,[email])
request.session['email'] = email
return redirect(register_success)
else:
code = 4
error = "Login/email taken"
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
else:
code = 3
error = "invalid password"
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
else:
code = 2
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
Here is my function I use to register user:
def register_user(login,email,password,newsletter):
"""
This function will return activation key for this user if user was added successfully or none otherwise
"""
key = generate_activation_key()
user = {
"username":login,
"email":email,
"password":crypt_password(password),
"date_join": datetime.now(),
"key": key
}
if newsletter:
user['newsletter'] = True
try:
settings.DB.user.insert(user,safe = True)
except DuplicateKeyError, error:
logging.debug("error raise during saving user")
return None
except OperationFailure, error:
logging.critical("Cannot save to database")
logging.critical(error)
else:
#we have no errors users is registred
return key
And when I test it in the browser it seems to be working. But I write test for it and it isn't working anymore. Here is code for test:
def test_valid_credentials(self):
#now try to register valid user
data = {'login':'test','password':'zaq12wsx','password_confirmation':'zaq12wsx','terms':True,'newsletter':True,'email':'test#test.com'}
response = self.c.post(reverse('register'),data)
#our user should be registred
self.assertEquals(302, response.status_code,'We dont have benn redirected')
self.assertEqual(len(mail.outbox), 1,'No activation email was sent')
#clen email box
mail.outbox = []
#now try to add another user with the same data
response = self.c.post(reverse('register'),data)
#template should be rendered with error message about used login and email
self.assertEquals(200, response.status_code)#this fails
And here is error that i get.
self.assertEquals(200, response.status_code)
AssertionError: 200 != 302
So user was registred with the same username and email which shoudn't happen. Any sugestions? Thanks in advance
Why don't you use https://github.com/django-mongodb-engine/mongodb-engine it works almost perfect with Django ORM. Works like a charm for me.
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.