article

Thursday, June 11, 2020

How to add ReCaptcha to Python Flask App without Extension


How to add ReCaptcha to Python Flask App without Extension

In this article we will learn to integrate Google ReCaptcha into flask web application without using any flask extension to prevent bots from submitting spam.

When you register for recaptcha it provides you two keys.

Site Key : For Client Side Integration
Secret Key : For Server Side Integration


Implementing ReCaptcha with python and flask
app.py
 
#app.py
from flask import Flask, render_template, request, flash, redirect, url_for, json
import requests #pip install requests

app = Flask(__name__)

app.config['SECRET_KEY'] = 'cairocoders-ednalan'

def is_human(captcha_response):
    """ Validating recaptcha response from google server
        Returns True captcha test passed for submitted form else returns False.
    """
    secret = "6LeKOaMZAAAAAKw9nhAjnpzrzrC3R0YYRf-kKDH1"
    payload = {'response':captcha_response, 'secret':secret}
    response = requests.post("https://www.google.com/recaptcha/api/siteverify", payload)
    response_text = json.loads(response.text)
    return response_text['success']
 
@app.route("/contact/", methods=["GET", "POST"])
def contact():
    sitekey = "6LeKOaMZAAAAAI7L6TVsZa9A2t6-9LDVYSVqX9ZP"

    if request.method == "POST":
        name = request.form['name']
        email = request.form['email']
        msg = request.form['message']
        captcha_response = request.form['g-recaptcha-response']
        
        if is_human(captcha_response):
            # Process request here
            status = "Detail submitted successfully."
        else:
             # Log invalid attempts
            status = "Sorry ! Please Check Im not a robot."

        flash(status)
        return redirect(url_for('contact'))

    return render_template("contact.html", sitekey=sitekey)
  
if __name__ == '__main__':
 app.run(debug=True)
templates/contact.html
//templates/contact.html
<html>
<head> 
<title>Contact Us</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css">
<script src="https://www.google.com/recaptcha/api.js"></script>
</head>
<body>
<div class="container"> <center><h3>How to add ReCaptcha to Python Flask App without Extension</h3></center> 
<div class="row main" style="padding-top:50px;">
 <div class="main-login main-center">
 <h5>Contact us Feel free to contact us</h5>
        <p>
         {% with messages = get_flashed_messages() %}
           {% if messages %}
          {% for message in messages %}
            <div class="alert alert-primary">
             <strong>{{ message }}</strong>
           </div>
          {% endfor %}
           {% endif %}
         {% endwith %}
        </p>
<form method="POST" action="{{ url_for('contact') }}"> 
    <div class="form-group">
  <label for="name" class="cols-sm-2 control-label">Your Name</label>
  <div class="cols-sm-10">
   <div class="input-group">
    <span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"></i></span>
    <input type="text" class="form-control" name="name" id="name"  placeholder="Enter your Name"/>
   </div>
  </div>
 </div>
 <div class="form-group">
  <label for="email" class="cols-sm-2 control-label">Your Email</label>
  <div class="cols-sm-10">
   <div class="input-group">
    <span class="input-group-addon"><i class="fa fa-envelope fa" aria-hidden="true"></i></span>
    <input type="text" class="form-control" name="email" id="email"  placeholder="Enter your Email"/>
   </div>
  </div>
 </div>
 <div class="form-group">
  <label for="email" class="cols-sm-2 control-label">Message</label>
  <div class="cols-sm-10">
   <div class="input-group">
    <span class="input-group-addon"><i class="fa fa-envelope fa" aria-hidden="true"></i></span>
    <textarea name="message" id="message" class="form-control" rows="3" cols="15" required="required"
                                placeholder="Enter your Message"></textarea>
   </div>
  </div>
 </div> 
    <div class="g-recaptcha" data-sitekey="{{ sitekey }}"></div> <br/> 
    <input type="submit" value="submit" class="btn btn-primary btn-lg btn-block login-button">
</form>
</div>
</div>
</div>
<style>
.form-group{
 margin-bottom: 15px;
}

label{
 margin-bottom: 15px;
}
input,
input::-webkit-input-placeholder {
    font-size: 11px;
    padding-top: 3px;
}
.main-login{
  background-color: #f5f5f5;
    padding:50px;width:600px;
    -moz-border-radius: 2px;
    -webkit-border-radius: 2px;
    border-radius: 2px;
    -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
    -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
    box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);

}
span.input-group-addon i {
    color: #009edf;
    font-size: 17px;padding:10px;
}
.form-control {
    height: auto!important;
padding: 8px 12px !important;
}
.input-group {
    -webkit-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.21)!important;
    -moz-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.21)!important;
    box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.21)!important;
}
.main-center{
  margin-top: 30px;
  margin: 0 auto;
    padding: 10px 40px;
    text-shadow: none;
 -webkit-box-shadow: 0px 3px 5px 0px rgba(0,0,0,0.31);
-moz-box-shadow: 0px 3px 5px 0px rgba(0,0,0,0.31);
box-shadow: 0px 3px 5px 0px rgba(0,0,0,0.31);

}
</style>
</body>
</html> 

Related Post