1+ import requests
2+ from django import forms
3+ from django .conf import settings
14from django .utils .translation import gettext_lazy as _
25from django .core .exceptions import ValidationError
3- from django .contrib .auth .forms import AuthenticationForm as _AuthenticationForm
6+ from django .contrib .auth import get_user_model
7+ from django .contrib .auth .forms import UserCreationForm , AuthenticationForm as _AuthenticationForm
48
59from api .utils import send_activation_email
610
11+ User = get_user_model ()
12+
713
814class AuthenticationForm (_AuthenticationForm ):
915
@@ -15,3 +21,32 @@ def confirm_login_allowed(self, user):
1521 code = "inactive" ,
1622 )
1723 return super ().confirm_login_allowed (user )
24+
25+
26+ class RegistrationForm (UserCreationForm ):
27+
28+ recaptcha_token = forms .CharField (
29+ label = _ ("reCAPTCHA token" ),
30+ widget = forms .HiddenInput (attrs = {"name" : "g-recaptcha-response" }),
31+ strip = False ,
32+ required = False ,
33+ help_text = _ ("Google recaptcha token hidden field" ),
34+ )
35+
36+ def clean_recaptcha_token (self ):
37+ recaptcha_token = self .data .get ("g-recaptcha-response" )
38+ if settings .GOOGLE_RE_CAPTCHA_KEY and settings .GOOGLE_RE_CAPTCHA_SECRET :
39+ success = requests .post ('https://www.recaptcha.net/recaptcha/api/siteverify' , data = {
40+ 'secret' : settings .GOOGLE_RE_CAPTCHA_SECRET ,
41+ 'response' : recaptcha_token ,
42+ }).json ()["success" ]
43+ if not success :
44+ raise ValidationError (
45+ _ ('Error verifying reCAPTCHA, please try again.' ),
46+ code = "captcha_invalid" ,
47+ )
48+ return recaptcha_token
49+
50+ class Meta (UserCreationForm .Meta ):
51+ model = User
52+ fields = ('username' , 'email' , 'password1' , 'password2' )
0 commit comments