Unverified Commit 2f39c063 authored by Johannes Tomren Røsvik's avatar Johannes Tomren Røsvik
Browse files

Add recaptcha verification to signup view

parent b3d0a864
Pipeline #72658 passed with stage
in 1 minute and 8 seconds
......@@ -3,9 +3,16 @@ from projects.models import ProjectCategory
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
import urllib
import json
from .forms import SignUpForm
SITE_VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify'
SITE_SECRET = '<ENTER SITE SECRET HERE>'
RECAPTCHA_RESPONSE_PARAM = 'g-recaptcha-response'
def index(request):
return render(request, 'base.html')
......@@ -13,19 +20,43 @@ def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save()
user.refresh_from_db()
user.profile.company = form.cleaned_data.get('company')
user.is_active = False
user.profile.categories.add(*form.cleaned_data['categories'])
user.save()
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=user.username, password=raw_password)
from django.contrib import messages
messages.success(request, 'Your account has been created and is awaiting verification.')
return redirect('home')
recaptcha_response = request.POST.get(RECAPTCHA_RESPONSE_PARAM)
recaptcha_result = verify_recapcha(recaptcha_response)
if not recaptcha_result['success']:
messages.error(request, 'Invalid reCAPTCHA. Please try again.')
else:
user = form.save()
user.refresh_from_db()
user.profile.company = form.cleaned_data.get('company')
user.is_active = False
user.profile.categories.add(*form.cleaned_data['categories'])
user.save()
raw_password = form.cleaned_data.get('password1')
user = authenticate(
username=user.username,
password=raw_password
)
messages.success(
request,
'Your account has been created and is awaiting verification'
)
return redirect('home')
else:
form = SignUpForm()
return render(request, 'user/signup.html', {'form': form})
def verify_recapcha(recaptcha_response):
url = SITE_VERIFY_URL
values = {
'secret': SITE_SECRET,
'response': recaptcha_response
}
data = urllib.parse.urlencode(values).encode()
req = urllib.request.Request(url, data=data)
response = urllib.request.urlopen(req)
result = json.loads(response.read().decode())
return result
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment