Show recaptcha after 3 wrong attemps and process it in Django? - django

I am using Class-based view with Django: I want to show the captcha only after 3 times and process captcha only after it is shown. Till now, I can only show the captcha after one wrong attempt:
def post(self, request):
response = captcha.submit(
request.POST.get('recaptcha_challenge_field'),
request.POST.get('recaptcha_response_field'),
'[[ MY PRIVATE KEY ]]',
request.META['REMOTE_ADDR'],)
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
state = "The username or password is incorrect."
if user is not None:
login(request, user)
return HttpResponseRedirect('/index/')
else:
#captcha = CaptchaField()
public_key = settings.RECAPTCHA_PUBLIC_KEY
script = displayhtml(public_key=public_key)
return render_to_response('index.html', {'state':state, 'captcha':'captcha', 'script':script}, context_instance=RequestContext(request))
I want to show the captcha after three times and process it using response.is_valid. How can I do this?

The simplest solution is probably to store the number of attempts in a cookie, incrementing it on each failed attempt. Obviously this can be tampered with, which brings me to signed cookies:
https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.get_signed_cookie
https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpResponse.set_signed_cookie
Essentially a signed cookie will raise an exception if the value has been tampered with.
You can also store the counter in the session, but I don't see any point in prematurely creating a session object when a cookie will do the trick.

Related

Django security and authentication

I have a few questions regarding tokens and username/pass pairs.
I have a django rest API set up which uses tokens once a user has registered. However I do not know how to return the token to the user in a safe matter? Currently I use:
response_data = UserSerializer(instance=new_user).data
response_data['token'] = token.key
return Response(response_data, status=status.HTTP_201_CREATED)
But in this way i can clearly see all of the details in my Response body in the browser? Even my password. How should I return it to the client ?
When registering a User I do it this way:
serialized = UserSerializer(data=request.DATA)
if serialized.is_valid():
print(serialized.validated_data)
new_user = get_user_model().objects.create(**serialized.validated_data)
token = Token.objects.create(user=new_user)
Will this create my user properly ? Will the password be hashed?
Thank you
P.S. here is the whole method:
#api_view(['POST'])
def register_user(request):
print (request)
serialized = UserSerializer(data=request.DATA)
if serialized.is_valid():
print(serialized.validated_data)
new_user = get_user_model().objects.create(**serialized.validated_data)
token = Token.objects.create(user=new_user)
response_data = UserSerializer(instance=new_user).data
response_data['token'] = token.key
return Response(response_data, status=status.HTTP_201_CREATED)
else:
return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
I would handle #1 by setting a cookie, if that works for your use case. Relevant SO Post: How to set cookie in Django view and then render template.
For #2, I believe you should use create_user rather than create. Check the Django docs here. A quick way to check and see if your passwords are getting hashed properly is to pop open a shell, grab a user object, and see what the password looks like:
>>u = User.objects.get(id=1)
>>u.password
u'pbkdf2_sha256$12000$e30c2ea7a76f83b7c1a975ddc24286b675e714ebbbc72ccd5f0401730231ab57'
You will easily be able to tell whether or not the password has been hashed.

Django: Check user name from two different models

I have two models: Faculty and Student. Both have a username and password.
I want to check if the username and password input provided is present in either of them. In the view, I can do a simple check on one model like this:
try:
user = Student.objects.get(username=username, password=password)
except Student.DoesNotExist:
error_message = "**Incorrect login. Please try again."
context = {'error_message' : error_message}
return render_to_response('myapp/login.html',context, context_instance=RequestContext(request))
Can you point out how to do the same for both Faculty and Student at the same time?
The simplest way is probably just to try the second query if the first fails:
context = {}
try:
user = Student.objects.get(username=username, password=password)
except Student.DoesNotExist:
try:
user = Faculty.objects.get(username=username, password=password)
except Faculty.DoesNotExist:
error_message = "**Incorrect login. Please try again."
context['error_message'] = error_message
# rest of your view here
return render_to_response('myapp/login.html', context, context_instance=RequestContext(request))
By the way, you can save yourself some effort if you use django.shortcuts.render instead of render_to_response:
from django.shortcuts import render
...
return render(request, 'myapp/login.html', context)
I suggest, you should use custom user model to join your models and classic django auth utils.

pass data from database in httpresponse redirect

Am new to django framework,am just trying to create seperate login form other than administrator login.I need to authenticate a user using username and password, fetch the details of that user from database and pass that data to a templae (home page) to display it.
My code is as follows:-
view.py:-
def login_user(request):
user = ''
passw = ''
username1 = ''
if request.POST:
user = request.POST.get('username')
passw = request.POST.get('password')
#password1 = ''
try:
userdata = Employee.objects.get(username = user, password = passw)
user_id = request.session["user_id"] = userdata.id
employee_details = Employee.objects.get(id=user_id)
request.session['user_id'] = employee_details.id
return HttpResponseRedirect('/home/', kwargs={'user_id': employee_details.id}))
except Employee.DoesNotExist:
state = "Username or password incorrect !"
return render_to_response('login.html',
{'username' : username1,'state' : state},
context_instance = RequestContext(request))
else:
state = "Please login here:"
return render_to_response('login.html' , {'state' : state} ,
context_instance = RequestContext(request))
i tried using kwargs={'user_id': employee_details.id} but it is not working.How can i pass datas to home page after redirecting?
Thanks
You can not redirect user using POST request. Use GET parameter instead.
In your case the requested data is already stored in session. Just try to read from the session on next request. Django contrib.auth uses user.is_authenticated method for the job.
i tried using kwargs={'user_id': employee_details.id} but it is not working.How can i pass datas to home page after redirecting?
You can:
use session variables
use "get" variables (pass variables encoded in the URL like '/home/?a=1&b=2', see urllib.urlencode)
However you should be using the standard Django user related functions and methods. See "How to log a user in". TLDR:
check credentials: user = authenticate(username=username, password=password)
test if user is not None and any other tests you want (is he active, has some privilege, etc)
mark the request.user as authenticated: login(request, user)

Unable to redirect to #login_required URL in django_webtest case

I'm using django_webtest to test my application. I faced with problem when try to test sign-up page. This page should create user and make other initial actions, authenticate newly created user and redirect it to the page specified in next parameter of GET request.
Here is the code of view method:
def _redirect_path(referrer, restricted_paths=()):
if not referrer or referrer in (reverse(name) for name in restricted_paths):
return reverse('home')
else:
return referrer
...
def sign_up(request):
if request.user.is_authenticated():
return redirect(reverse('home'))
if request.method == 'POST':
form = forms.SignUpForm(request.POST)
if form.is_valid():
with transaction.commit_on_success():
user = form.save()
profile = Profile.objects.create(user=user)
tokens.create_token(profile, 'unsubscribe')
mail.send_welcome_letter(request, user)
messages.success(request, _('You have successfully signed up. Welcome!'))
authenticated_user = auth.authenticate(username=user.username, password=form.cleaned_data['password'])
if authenticated_user:
auth.login(request, authenticated_user)
remember_user(request, authenticated_user)
redirect_path = _redirect_path(form.clean_referrer(), ('password_reset', 'sign_up'))
return redirect(redirect_path)
else:
raise Exception("Newly created user couldn't be authenticated.")
else:
referrer = request.GET.get('next')
form = forms.SignUpForm(initial={'referrer': referrer})
return render_to_response('sign_up.html', {'form': form}, context_instance=RequestContext(request))
Now I try to test its behavior when user entered example.com/sign_up/?next=/settings/ in his browser, fill all fields of form correctly and submit it.
View that handles /settings/ has decorator #login_required, but after user is successfully signed up, he should be authenticated, so I expect that after submit user will go to example.com/settings/ (and he goes when I test it manually).
But when I run test:
def test_user_creation_redirect_to_settings(self):
form = self.app.get('/sign_up/', {'next': '/settings/'}).form
self.fill_sign_up_form(form)
submit_response = form.submit()
self.assertRedirects(submit_response, '/settings/')
it returns "AssertionError: Couldn't retrieve redirection page '/settings/': response code was 302 (expected 200)". When I debugged, I have seen that *submit_response* is really 302 FOUND with location path /settings/. But when method assertRedirects tries to get target page, it faces with redirect again - example.com/settings/ redirects to example.com/login/?next=/settings/. So user is not logged in after submit.
OK, I tried to log in him with test client's login method:
def test_user_creation_redirect_to_settings(self):
form = self.app.get('/sign_up/', {'next': '/settings/'}).form
self.fill_sign_up_form(form)
submit_response = form.submit()
submit_response.client.login(username='User', password='secret')
self.assertRedirects(submit_response, '/settings/')
But still the same. Seems, this method is not works:
def test_user_creation_redirect_to_settings(self):
form = self.app.get('/sign_up/', {'next': '/settings/'}).form
self.fill_sign_up_form(form)
submit_response = form.submit()
inside = self.client.login(username='User', password='secret')
print inside and 'Login successful in self client'
print 'Authenticated: %s' % bool('_auth_user_id' in self.client.session)
inside = submit_response.client.login(username='User', password='secret')
print inside and 'Login successful in response client'
print 'Authenticated: %s' % bool('_auth_user_id' in submit_response.client.session)
prints
Login successful in self client
Authenticated: True
Login successful in response client
Authenticated: False
Could you please help me to understand why login functionality doesn't work in test case and how to log in user before redirect.
Thanks!
Have you tried using the follow method in your tests? Doing so follows redirects.
form.submit().follow()
This is a django-webtest bug that was fixed in django-webtest 1.5.3.

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.