Skip to content

Instantly share code, notes, and snippets.

@sam-thecoder
Created December 30, 2018 08:27
Show Gist options
  • Save sam-thecoder/7403563e7d686d3f70d7731669b68e91 to your computer and use it in GitHub Desktop.
Save sam-thecoder/7403563e7d686d3f70d7731669b68e91 to your computer and use it in GitHub Desktop.
def login_page(request, template_name="login.html"):
context = {'title': 'Login Page'}
file_name, answer, _, result_id = generate_captcha()
context['captcha_url'] = '/' + file_name
context['ref_id'] = result_id
return render_to_response(template_name, context)
def login_ajax(request):
response = {'status': None}
if request.method == 'POST':
data = json.loads(request.body)
username, password, ans, ref_id = data['username'], data['password'], data['captcha-result'], data['captcha-ref-id']
actual_ans = retrieve_answer(ref_id)
if ans == actual_ans: #Captcha Verification Complete, move on to password verification
user_exists = User.objects.filter(username=username)
if user_exists: #check password...
user = user_exists[0]
password_ok = user.check_password(password)
if password_ok: #ok move to logging in user
django_login(request, user)
#just incase...
response['status'] = 'ok'
else: #password failed...
response['status'] = 'failed'
file_name, ans, _, ref_id = generate_captcha()
response['captcha-url'] = '/' + file_name
response['ref-id'] = ref_id
response['error-message'] = 'Wrong Username/Password Combination'
else: #no matching user found
response['status'] = 'failed'
file_name, ans, _, ref_id = generate_captcha()
response['captcha-url'] = '/' + file_name
response['ref-id'] = ref_id
response['error-message'] = 'Wrong Username/Password Combination'
else: #Captcha Verification Failed, return new Captcha and ID so user can try again
response['status'] = 'failed'
file_name, ans, _, ref_id = generate_captcha()
response['captcha-url'] = '/' + file_name
response['ref-id'] = ref_id
response['error-message'] = 'Wrong Answer to Calculation'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment