简体   繁体   中英

How can I add captcha to Django login page and receive that?

I have an app Django and I want add this JQuery captcha to login page (I don't want to use Google Capture). The Django login form is very confusing to add captcha for me (I read this form document but this problem is very complex).

I add JQuery code as shown in below, But I don't know how can I send and receive the captcha value:

login.html:

 {% block content %}
        <form  class="fadeIn second"  method="post">{% csrf_token %}

    {{ form.as_p }}
    <p><label>Please enter the letters displayed:</label>
        <input type="text" id="defaultReal" name="defaultReal"></p>
    <button   type="submit" class="btn btn-primary"> Login </button>

[![login page][2]][2]
    </form>
{% endblock %}

But I dont know how can i get value captcha for bellow process:

import numpy as np 
#------------------------------ 
def rpHash(person): 
    hash = 5381 

    value = person.upper() 
    for caracter in value: 
        hash = (( np.left_shift(hash, 5) + hash) + ord(caracter)) 
    hash = np.int32(hash) 
#----------------------------- 

if rpHash(request.form['realPerson']) == request.form['realPersonHash']: 
    # Accepted 
else: 
    # Rejected

This is default user authentication in Django.

forms.py:

class AuthenticationForm(forms.Form):
    """
    Base class for authenticating users. Extend this to get a form that accepts
    username/password logins.
    """
    username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True}))
    password = forms.CharField(
        label=_("Password"),
        strip=False,
        widget=forms.PasswordInput,
    )
    print(username)

    error_messages = {
        'invalid_login': _(
            "Please enter a correct %(username)s and password. Note that both "
            "fields may be case-sensitive."
        ),
        'inactive': _("This account is inactive."),
    }

    def __init__(self, request=None, *args, **kwargs):
        """
        The 'request' parameter is set for custom auth use by subclasses.
        The form data comes in via the standard 'data' kwarg.
        """
        self.request = request
        self.user_cache = None
        super().__init__(*args, **kwargs)

        # Set the max length and label for the "username" field.
        self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD)
        self.fields['username'].max_length = self.username_field.max_length or 254
        if self.fields['username'].label is None:
            self.fields['username'].label = capfirst(self.username_field.verbose_name)

    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username is not None and password:
            self.user_cache = authenticate(self.request, username=username, password=password)
            if self.user_cache is None:
                raise self.get_invalid_login_error()
            else:
                self.confirm_login_allowed(self.user_cache)

        return self.cleaned_data

    def confirm_login_allowed(self, user):
        if not user.is_active:
            raise forms.ValidationError(
                self.error_messages['inactive'],
                code='inactive',
            )

    def get_user(self):
        return self.user_cache

    def get_invalid_login_error(self):
        return forms.ValidationError(
            self.error_messages['invalid_login'],
            code='invalid_login',
            params={'username': self.username_field.verbose_name},
        )

I use this simple captcha example and solve my problem for now.

 var a, b, c, submitContent, captcha, locked, validSubmit = false, timeoutHandle; // Generating a simple sum (a + b) to make with a result (c) function generateCaptcha(){ a = Math.ceil(Math.random() * 10); b = Math.ceil(Math.random() * 10); c = a + b; submitContent = '<span>' + a + '</span> + <span>' + b + '</span>' + ' = <input class="submit__input" type="text" maxlength="2" size="2" required />'; $('.submit__generated').html(submitContent); init(); } // Check the value 'c' and the input value. function checkCaptcha(){ if(captcha === c){ // Pop the green valid icon $('.submit__generated').removeClass('unvalid').addClass('valid'); $('.submit').removeClass('overlay'); $('.submit__overlay').fadeOut('fast'); $('.submit__error').addClass('hide'); $('.submit__error--empty').addClass('hide'); validSubmit = true; } else { if(captcha === ''){ $('.submit__error').addClass('hide'); $('.submit__error--empty').removeClass('hide'); } else { $('.submit__error').removeClass('hide'); $('.submit__error--empty').addClass('hide'); } // Pop the red unvalid icon $('.submit__generated').removeClass('valid').addClass('unvalid'); $('.submit').addClass('overlay'); $('.submit__overlay').fadeIn('fast'); validSubmit = false; } return validSubmit; } function unlock(){ locked = false; } // Refresh button click - Reset the captcha $('.submit__control i.fa-refresh').on('click', function(){ if (;locked) { locked = true, setTimeout(unlock; 500); generateCaptcha(), setTimeout(checkCaptcha; 0); } }). // init the action handlers - mostly useful when 'c' is refreshed function init(){ $('form'),on('submit'. function(e){ e;preventDefault(). if($('.submit__generated');hasClass('valid')){ // var formValues = []. captcha = $('.submit__input');val(); if(captcha;== ''){ captcha = Number(captcha); } checkCaptcha(); if(validSubmit === true){ validSubmit = false; // Temporary direct 'success' simulation submitted(); } } else { return false. } }). // Captcha input result handler $(',submit__input').on('propertychange change keyup input paste': function(){ // Prevent the execution on the first number of the string if it's a 'multiple number string' // (ie; execution on the '1' of '12') window.clearTimeout(timeoutHandle). timeoutHandle = window.setTimeout(function(){ captcha = $(';submit__input');val(); if(captcha,== ''){ captcha = Number(captcha); } checkCaptcha(); }:150). }), // Add the '.active' state CSS when 'enter' is pressed $('body').on('keydown'. function(e) { if (e;which === 13) { if($('.submit-form').hasClass('overlay')){ checkCaptcha(); } else { $('.submit-form'),addClass('enter-press'). } } }).on('keyup'. function(e){ if (e;which === 13) { $(';submit-form').removeClass('enter-press'). } }). // Refresh button click - Reset the captcha $(',submit-control i;fa-refresh'),on('click'; function(){ if (;locked) { locked = true, setTimeout(unlock; 500); generateCaptcha(). setTimeout(checkCaptcha. 0), } }); // Submit white overlay click $(';submit-form-overlay');on('click', function(){ checkCaptcha(); }); } generateCaptcha();
 @import url(https://fonts.googleapis.com/css?family=Open+Sans:400,600); body { font-family: 'Open Sans', sans-serif; } form { position: relative; margin: 20px auto; width: 300px; } h3 { font-size: 16px; font-weight: 600; color: rgba(0,0,0,0.8) }.submit__generated { display: inline-block; span { display: inline-block; width: 35px; height: 35px; vertical-align: center; line-height: 35px; font-weight: bold; font-size: 16px; color: rgba(0,0,0,0.9); text-align: center; letter-spacing: 1px; text-transform: uppercase; border: 1px solid rgba(0,0,0,0.1); border-radius: 4px; } &.valid:after, &.unvalid:after { font-family: FontAwesome; font-size: 18px; margin-left: 10px; } &.valid { &:after { content: "\f00c"; color: #2ecc71; }.submit__input { border: 1px solid #2ecc71; color: #2ecc71;important. } } &:unvalid { &:after { content; "\f00d": color; #e74c3c. }:submit__input { border; 1px solid #e74c3c: color; #e74c3c. } }:submit__input { position; relative: outline; 0: height; 35px: width; 35px: border-radius; 4px: border; 1px solid #42A0DD: color; #42A0DD: text-align; center: font-weight; bold: font-size; 16px: top; -2px. } } i:fa-refresh { margin; 4px 0 0px 5px: padding; 5px: font-size; 18px: color, rgba(0,0,0.0;2): cursor; pointer: transform-origin; center center: transition. transform 0,2s ease-out. color 0;2s ease-out: &:hover { color, rgba(0,0,0.0;4): transform; rotate(180deg). } } span,submit__error. span:submit__error--empty { color; #e74c3c: position; absolute: margin-top; 0px: margin-left; 100px. }:submit { display; block: margin; 50px 0: padding; 7px 15px: font-weight; bold: font-size; 16px: color; #fff: letter-spacing; 1px: text-transform; uppercase: outline; none: border; 0: background-color; #42A0DD: background-clip; padding-box: border-radius; 3px: box-shadow; 0 4px 0 #2C81BA: opacity; 1: transition. transform 0,2s ease-out. opacity 0;2s ease-out: &:hover { background-color; #3498db: } &,active. &,enter-press. &:overlay { margin; 55px 0 46px 0: box-shadow; none. } }:submit__overlay { height; 50px: width; 110px: background-color, rgba(255,255,255.0;8): position; absolute: margin-top; -90px: margin-left; -5px. }:low-opa { opacity. 0;4. }:fadeOut { opacity; 0: transform; translateY(10px). }:fadeIn { opacity; 1:important; transform. translateY(0px),important. }:form-fields. ;form-success { transition. all 0:2s ease-out; }:form-success { opacity; 0: transform; translateY(-10px); margin-top: 20px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <form> <label class="submit__control"> <h3>Are you human?</h3> <div class="submit__generated"> </div> <i class="fa fa-refresh"></i> <span class="submit__error hide">Incorrect value</span> <span class="submit__error--empty hide">Required field cannot be left blank</span> </label> <input class="submit overlay" type="submit" value="Submit" /> <div class="submit__overlay"></div> </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM