1658943780
Recently, there have been different implementations to prevent spamming of different web services. One of these implementations is using a reCAPTCHA feature. A reCAPTCHA is an automated test to determine if the user of a web application is a human or a bot. This way, privileges or access are only granted to human users, thus reducing unwanted usage.
In this tutorial, readers will learn what reCAPTCHA’s are and how to implement them in a web application.
See more at: https://blog.openreplay.com/prevent-spam-and-detect-bots-with-recaptcha
1624410000
Create a Twitter bot with Python that tweets images or status updates at a set interval. The Python script also scrapes the web for data.
📺 The video in this post was made by freeCodeCamp.org
The origin of the article: https://www.youtube.com/watch?v=8u-zJVVVhT4&list=PLWKjhJtqVAbnqBxcdjVGgT3uVR10bzTEB&index=14
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!
#python #a twitter bot #a twitter bot with python #bot #bot with python #create a twitter bot with python
1658943780
Recently, there have been different implementations to prevent spamming of different web services. One of these implementations is using a reCAPTCHA feature. A reCAPTCHA is an automated test to determine if the user of a web application is a human or a bot. This way, privileges or access are only granted to human users, thus reducing unwanted usage.
In this tutorial, readers will learn what reCAPTCHA’s are and how to implement them in a web application.
See more at: https://blog.openreplay.com/prevent-spam-and-detect-bots-with-recaptcha
1671876604
Google reCAPTCHA v3 is an invisible type of captcha where the user doesn’t have to interact. It tracks the user behavior on the site and returns a score between 0 to 1 with the response.
This score is use for validation on the server side.
In this tutorial, I show how you can add Google reCAPTCHA v3 to your form in CodeIgniter 4.
You can skip this step if you already registered for Google reCAPTCHA v3 and have site and secret keys.
localhost
if you want to test it on your local system.Accept the reCAPTCHA Terms of Service
and click the Submit button..env
file which is available at the project root.NOTE – If dot (.) not added at the start then rename the file to .env.
GOOGLE_RECAPTCHAV3_SITEKEY = 6LdP-nIhAAAAAA6rzq7BTh_jKqIYeKMoaALxkKte
GOOGLE_RECAPTCHAV3_SECRETKEY = 6LdV-nIhAAAAAL-uFI4w9kQUaqMkeU2K3KojlXyE
.env
file.security.tokenName
,security.headerName
, security.cookieName
, security.expires
,and security.regenerate
.security.tokenName
value with 'csrf_hash_name'
. With this name read CSRF hash. You can update it with any other value.security.regenerate = false
.security.tokenName = 'csrf_hash_name'
security.headerName = 'X-CSRF-TOKEN'
security.cookieName = 'csrf_cookie_name'
security.expires = 7200
security.regenerate = true
app/Config/Filters.php
file.'csrf'
in 'before'
if commented.// Always applied before every request
public $globals = [
'before' => [
// 'honeypot',
'csrf',
// 'invalidchars',
],
'after' => [
'toolbar',
// 'honeypot',
// 'secureheaders',
],
];
Create a rule to verify reCaptcha v3 response.
CaptchaValidation.php
file in app/Config/
folder.CaptchaValidation
class.verifyrecaptchaV3()
method. Here, the method name is also a rule name..env
file and assign it to $secretkey
.https://www.google.com/recaptcha/api/siteverify?secret=".$secretkey."&response=".$str."&remoteip=".$_SERVER['REMOTE_ADDR']
$responseData->success
is true
and $responseData->score
is >
0.6 then return true
otherwise, assign error message in $error
and return false
.NOTE – You can update value of
$score
from 0.6 to any other value. Make sure to set it between 0.5 to 1.
Completed Code
<?php
namespace Config;
class CaptchaValidation{
public function verifyrecaptchaV3(string $str, ?string &$error = null): bool
{
$secretkey = getenv('GOOGLE_RECAPTCHAV3_SECRETKEY');
if(($str) && !empty($str)) {
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretkey."&response=".$str."&remoteip=".$_SERVER['REMOTE_ADDR']);
$responseData = json_decode($response);
$score = 0.6; // 0 - 1
if($responseData->success && $responseData->score > $score) { // Verified
return true;
}
}
$error = "Invalid captacha";
return false;
}
}
To use the above-created validation rule need to define it in the Validation.php
file.
app/Config/Validation.php
file.Config\CaptchaValidation
class.CaptchaValidation::class
in $ruleSets
Array.Completed Code
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Validation\CreditCardRules;
use CodeIgniter\Validation\FileRules;
use CodeIgniter\Validation\FormatRules;
use CodeIgniter\Validation\Rules;
use Config\CaptchaValidation; // Custom reCAPTCHA v3 validation
class Validation extends BaseConfig
{
// --------------------------------------------------------------------
// Setup
// --------------------------------------------------------------------
/**
* Stores the classes that contain the
* rules that are available.
*
* @var string[]
*/
public $ruleSets = [
Rules::class,
FormatRules::class,
FileRules::class,
CreditCardRules::class,
CaptchaValidation::class, // Custom reCAPTCHA v3 validation
];
/**
* Specifies the views that are used to display the
* errors.
*
* @var array<string, string>
*/
public $templates = [
'list' => 'CodeIgniter\Validation\Views\list',
'single' => 'CodeIgniter\Validation\Views\single',
];
// --------------------------------------------------------------------
// Rules
// --------------------------------------------------------------------
}
Create PagesController
Controller –
php spark make:controller PagesController
app/Controllers/PagesController.php
file.index
view.Validate the submitted values. Here, for validating recaptcha specify – 'recaptch_response' => 'required|verifyrecaptchaV3',
.
verifyrecaptchaV3
is a custom validation rule created in the previous step.
If <form >
is not validated then return to the page with error messages otherwise store the success message in SESSION flash and redirect to route('/')
.
Completed Code
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
class PagesController extends BaseController
{
public function index(){
return view('index');
}
public function submitContactUs(){
// Validation
$input = $this->validate([
'name' => 'required',
'email' => 'required',
'subject' => 'required',
'message' => 'required',
'recaptcha_response' => 'required|verifyrecaptchaV3',
],[
'recaptcha_response' => [
'required' => 'Please verify captcha',
],
]);
if (!$input) { // Not valid
$data['validation'] = $this->validator;
return redirect()->back()->withInput()->with('validation', $this->validator);
}else{
// Set Session
session()->setFlashdata('message', 'Request Submitted Successfully!');
session()->setFlashdata('alert-class', 'alert-success');
}
return redirect()->route('/');
}
}
app/Config/Routes.php
file.$routes->get('/', 'PagesController::index');
$routes->post('page/submitContactUs', 'PagesController::submitContactUs');
index.php
file in app/Views/
folder.<head >
section –<!-- reCAPTCHA JS-->
<script src="https://www.google.com/recaptcha/api.js?render=<?= getenv('GOOGLE_RECAPTCHAV3_SITEKEY') ?>"></script>
Here, also specify sitekey.
action
URL to <?=site_url('page/submitContactUs')?>
. Define onSubmit
event on <form >
that calls onSubmit(event)
.<form>
element is not validated. In the <form >
also display an error message if recaptcha is not validated.#recaptcha_response
to store recapatcha token response on <form >
submit.Script
onSubmit()
function that calls on <form >
submit.grecaptcha.execute
on submit
action to get a token.#recaptcha_response
.<form >
.Completed Code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How to add Google reCAPTCHA v3 in CodeIgniter 4</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" >
<!-- reCAPTCHA JS-->
<script src="https://www.google.com/recaptcha/api.js?render=<?= getenv('GOOGLE_RECAPTCHAV3_SITEKEY') ?>"></script>
<!-- Include script -->
<script type="text/javascript">
function onSubmit(e) {
e.preventDefault();
grecaptcha.ready(function() {
grecaptcha.execute("<?= getenv('GOOGLE_RECAPTCHAV3_SITEKEY') ?>", {action: 'submit'}).then(function(token) {
// Store recaptcha response
document.getElementById("recaptcha_response").value = token;
// Submit form
document.getElementById("contactForm").submit();
});
});
}
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 mt-5" style="margin: 0 auto;">
<?php
// Display Response
if(session()->has('message')){
?>
<div class="alert <?= session()->getFlashdata('alert-class') ?>">
<?= session()->getFlashdata('message') ?>
</div>
<?php
}
?>
<h2 class="mb-4">Contact US</h2>
<?php $validation = \Config\Services::validation(); ?>
<form id="contactForm" method="post" action="<?=site_url('page/submitContactUs')?>" onSubmit="onSubmit(event)">
<?= csrf_field(); ?>
<!-- Recaptcha Error -->
<?php if( $validation->getError('recaptcha_response') ) {?>
<div class="alert alert-danger">
<?= $validation->getError('recaptcha_response'); ?>
</div>
<?php }?>
<div class="form-group mb-4">
<label class="control-label col-sm-2" for="name">Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" placeholder="Enter Name" name="name" value="<?= old('name') ?>">
</div>
<!-- Error -->
<?php if( $validation->getError('name') ) {?>
<div class='text-danger mt-2'>
* <?= $validation->getError('name'); ?>
</div>
<?php }?>
</div>
<div class="form-group mb-4">
<label class="control-label col-sm-2" for="email">Email:</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" placeholder="Enter Email" name="email" value="<?= old('email') ?>">
</div>
<!-- Error -->
<?php if( $validation->getError('email') ) {?>
<div class='text-danger mt-2'>
* <?= $validation->getError('email'); ?>
</div>
<?php }?>
</div>
<div class="form-group mb-4">
<label class="control-label col-sm-2" for="subject">Subject:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="subject" placeholder="Enter Subject" name="subject" value="<?= old('subject') ?>" >
</div>
<!-- Error -->
<?php if( $validation->getError('subject') ) {?>
<div class='text-danger mt-2'>
* <?= $validation->getError('subject'); ?>
</div>
<?php }?>
</div>
<div class="form-group mb-4">
<label class="control-label col-sm-2" for="message">Message:</label>
<div class="col-sm-10">
<textarea class="form-control" id="message" name="message"><?= old('message') ?></textarea>
</div>
<!-- Error -->
<?php if( $validation->getError('message') ) {?>
<div class='text-danger mt-2'>
* <?= $validation->getError('message'); ?>
</div>
<?php }?>
</div>
<div class="form-group ">
<div class="col-sm-offset-2 col-sm-10">
<input type="hidden" id="recaptcha_response" name="recaptcha_response" value="">
<button type="submit" class="btn btn-info">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Using this you can protect your website without forcing the user to verify whether it is human or a bot.
You can also view this tutorial if you want to know Google reCAPTCHA v2 implementation in CodeIgniter 4.
If you found this tutorial helpful then don't forget to share.
Original article source at: https://makitweb.com/
1658948400
Recentemente, houve diferentes implementações para evitar spam de diferentes serviços da web. Uma dessas implementações está usando um recurso reCAPTCHA. Um reCAPTCHA é um teste automatizado para determinar se o usuário de um aplicativo da Web é um humano ou um bot. Dessa forma, privilégios ou acessos são concedidos apenas a usuários humanos, reduzindo assim o uso indesejado.
Neste tutorial, os leitores aprenderão o que são reCAPTCHAs e como implementá-los em uma aplicação web.
Um reCAPTCHA é um CAPTCHA(Teste de Turing Público Completamente Automatizado para Separar Computadores e Humanos) que é gratuito, fácil de adicionar e um recurso avançado de segurança do site de propriedade do Google. Ele foi desenvolvido para gerenciar o uso indesejado de sites por bots e evitar spam, implementando várias técnicas para identificar se um usuário de página da Web é um humano ou um bot. Essas técnicas envolvem apresentar ao usuário um teste que é fácil para humanos resolverem, mas difícil para bots ou software malicioso verificar. A implementação desse recurso de segurança em uma página da Web evita o abuso do site enquanto ainda permite que usuários humanos usem o site como deveriam, ou seja, usuários legítimos podem realizar suas atividades normais de acesso e utilização do site após passar no teste reCAPTCHA. O GIF abaixo contém exemplos de tipos de reCAPTCHA que você pode ter encontrado em uma página da web:
A implementação do recurso de segurança reCAPTCHA em um site fornecerá os seguintes benefícios:
No geral, os reCAPTCHAs são seguros, pois não possuem padrões previsíveis no teste selecionado apresentado ao usuário.
Ao longo do tempo, houve desenvolvimentos nas versões do reCAPTCHA, com cada nova versão adicionando uma nova técnica de teste do usuário. Até agora, o Google lançou três versões do reCAPTCHA; v1, v2 e v3.
Para esta versão, o reCAPTCHA monitora o comportamento do site do usuário. Caso o usuário utilize o site de forma suspeita, é apresentada a imagem reCAPTCHA; caso contrário, eles são apresentados com a variante checkbox.
Para demonstrar o recurso reCAPTCHA, teremos um formulário que utiliza um CAPTCHA para permitir que apenas usuários legítimos enviem dados. Para seguir este tutorial, clone o código do formulário inicial do repositório GitHub e execute npm install
no diretório do projeto para instalar todas as dependências necessárias.
Precisaremos de duas coisas: a primeira, uma chave de API para acessar o reCAPTCHA e a segunda, a react-google-recaptcha
dependência. Para obter sua chave de acesso, navegue em seu navegador até aqui :
Nesta página, somos obrigados a inserir o título de nossa chave no Label
campo. Para o tipo reCAPTCHA, usaremos a variante v2 “Não sou um robô”. No campo Domínio, digitaremos “localhost” e, por fim, clicaremos no botão “Enviar” para gerar a chave. Copie as chaves geradas, pois as usaremos em nossa aplicação. Em seguida, instale a react-google-recaptcha
dependência com o seguinte comando na CLI:
npm install --save react-google-recaptcha
Após a conclusão da instalação, podemos importar e usar este pacote em Index.js
:
import ReCAPTCHA from "react-google-recaptcha";
Em seguida, adicione o ReCAPTCHA
componente no formulário logo abaixo do botão de login:
//....
<input
type="text"
placeholder="Doe"
value={value}
onChange={(e) => {
setValue(e.target.value);
}}
/>
</span>
<button className="submit">Log in</button>
<ReCAPTCHA sitekey="your app site key"/>
O ReCAPTCHA
componente requer uma sitekey
propriedade para poder fazer uso dele. Agora, se executarmos a aplicação com o npm run dev
comando, obteremos um resultado semelhante ao da imagem:
O ReCAPTCHA
componente nos permite personalizar o comportamento e a aparência do ReCAPTCHA usando diferentes propriedades. Algumas dessas propriedades incluem:
light
ou dark
. Por padrão, o reCAPTCHA é exibido usando um tema claro, mas adicionar uma theme
propriedade com um valor de dark
renderizará um reCAPTCHA de aparência escura.compact
, normal
ou invisible
. Ele especifica o tamanho do reCAPTCHA ou determina se o reCAPTCHA seria invencível.O OpenReplay é um conjunto de reprodução de sessão de código aberto que permite ver o que os usuários fazem em seu aplicativo da Web, ajudando você a solucionar problemas mais rapidamente. O OpenReplay é auto-hospedado para controle total sobre seus dados.
Comece a aproveitar sua experiência de depuração - comece a usar o OpenReplay gratuitamente .
Para o formulário, queremos que o usuário possa enviar apenas quando tiver concluído o reCAPTCHA. Sempre que um usuário conclui um reCAPTCHA, um token é gerado. Este token é válido por dois minutos e só pode ser usado uma vez. Acessamos esse token em nosso aplicativo para permitir que o usuário envie o formulário após concluir o reCAPTCHA. Para capturar este token, usaremos o hook useRef do React:
//first we add an import for useRef
import { React, useState, useRef } from "react";
Após isso, criaremos uma variável onde armazenaremos o valor do token, usando useRef
:
const getCaptchaRef = useRef(null);
Em seguida, adicione esta variável à ref
propriedade do reCAPTCHA
componente:
<ReCAPTCHA
sitekey= "your site key here"
ref={getCaptchaRef}
/>
A ref
propriedade retorna diferentes funções auxiliares. Algumas dessas funções e seus propósitos correspondentes incluem:
excecuteAsync()
: Esta função envia uma solicitação que retorna o token ou um erro (se ocorrer). No entanto, essa função é aplicável apenas a reCAPTCHAs invisíveis. Para reCAPTCHA visível, a getValue()
função é usada para retornar o token.getValue()
: como o nome indica, esta função retorna o valor do campo reCAPTCHA.reset()
: Isso é usado para redefinir o reCAPTCHA e é aplicável no caso de verificações subsequentes reCAPTCHA
.Podemos usar o ref
para obter nosso token, conforme mostrado abaixo:
<ReCAPTCHA
sitekey= "your site key"
theme="dark"
ref={getCaptchaRef}
onChange={() => {
reCaptchaValue();
}}
/>
Aqui, adicionamos uma função na propriedade do nosso componente onChange
. Usaremos esta função para definir o valor do nosso token:
const reCaptchaValue = async () => {
const token = getCaptchaRef.current.getValue();
};
Em seguida, devemos verificar o token gerado antes de habilitar o recurso de envio. Para fazer isso, precisamos fazer uma POST
solicitação para https://www.google.com/recaptcha/api/siteverify
usar o Node.js no back-end. Crie um novo arquivo, Server.js
, no diretório raiz do seu aplicativo. Para o servidor, precisaremos de duas dependências; Axios
para lidar com nossa POST
solicitação e Express
gerenciar as rotas do servidor. Podemos instalar essas dependências com os seguintes comandos da CLI:
npm i express axios cors
Em seguida, crie um arquivo Server.js
no diretório raiz da pasta do projeto. Em Server.js
, digite o seguinte código:
const express = require("express");
const axios = require("axios");
const cors = require("cors");
const router = express.Router();
const app = express();
const port = 5000;
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use("/", router);
router.post("/status", async (req, res) => {
const { token } = req.body; // get token from the request we will create in index.js
const secret = "SITE SECRET";
await axios.post(
`https://www.google.com/recaptcha/api/siteverify`, // URL
{
secret: secret,
response: token,
}, // URL parameters
);
//return response based on the status of the post request
if (res.status(200)) {
res.send(true);
} else {
res.send(false);
}
});
app.listen(port, () => {
console.log(`server is listening on ${port}`);
});
No código acima, criamos um servidor que roda na porta 5000 e escuta route /status
. Usando este servidor, faremos uma solicitação de postagem para determinar se o token é válido e retornaremos uma resposta. Se o token for válido, o servidor retornará uma resposta adequada. Caso contrário, ele retornaria uma resposta false
. Abra o terminal e inicie o servidor com node Server.js
.
Com isso em vigor, iniciaremos nossa solicitação index.js
em nossa reCaptchaValue
função, conforme mostrado abaixo:
const [valid, setValid] = useState(false)
const reCaptchaValue = async () => {
const token = getCaptchaRef.current.getValue();
console.log(token);
await axios
.post("http://localhost:5000/status", {
response: token,
})
.then((res) => {
console.log(res);
setValid(res.data)
})
.catch((err) => {
console.log(err);
});
};
No código, fizemos uma solicitação de postagem para a URL do nosso servidor com o token retornado pelo reCAPTCHA. Em seguida, definimos o valor de um estado valid
igual ao res.data
retornado do servidor, "true" ou "false".
Por fim, adicionaremos um onClick
manipulador ao nosso botão para realizar diferentes operações com base no valor de valid
:
<button className="submit" onClick={()=>{handleSubmit()}}>Log in</button>
E na handleSubmit()
função:
const handleSubmit = ()=>{
if(valid){
alert("welcome user " + value + " " + value2)
}
else{
alert("please verify you are not a robot")
}
}
Se executarmos nosso aplicativo agora, obteremos o seguinte resultado:
Se o usuário falhar no reCAPTCHA, ele simplesmente solicitará que o usuário tente novamente até que o teste seja bem-sucedido.
Este tutorial nos ensinou sobre o reCAPTCHA e como podemos integrar esse recurso de segurança em um aplicativo Next.
Fonte: https://blog.openreplay.com/prevent-spam-and-detect-bots-with-recaptcha
1659196020
Voight-Kampff relies on a user agent list for its detection. It can easily tell you if a request is coming from a crawler, spider or bot. This can be especially helpful in analytics such as page hit tracking.
gem install voight_kampff
A JSON file is used to match user agent strings to a list of known bots.
If you'd like to use an updated list or make your own customizations, run rake voight_kampff:import_user_agents
. This will download a crawler-user-agents.json
file into the ./config
directory.
Note: The pattern entries in the JSON file are evaluated as regular expressions.
There are three ways to use Voight-Kampff
Through Rack::Request such as in your Ruby on Rails controllers:request.bot?
Through the VoightKampff
module:VoightKampff.bot? 'your user agent string'
Through a VoightKampff::Test
instance:VoightKampff::Test.new('your user agent string').bot?
All of the above examples accept human?
and bot?
methods. All of these methods will return true
or false
.
Version 1.0 uses a new source for a list of bot user agent strings since the old source was no longer maintained. This new source, unfortuately, does not include as much detail. Therefore the following methods have been deprecated:
#browser?
#checker?
#downloader?
#proxy?
#crawler?
#spam?
In general the #bot?
command tends to include all of these and I'm sure it's unlikely that anybody was getting this granular with their bot checking. So I see it as a small price to pay for an open and up to date bot list.
Also, the gem no longer extends ActionDispatch::Request
instead it extends Rack::Request
which ActionDispatch::Request
inherits from. This allows the same functionality for Rails while opening the gem up to other rack-based projects.
Q: What's with the name?
A: It's the machine in Blade Runner that is used to test whether someone is a human or a replicant.
Q: I've found a bot that isn't being matched
A: The list is being pulled from github.com/monperrus/crawler-user-agents. If you'd like to have entries added to the list, please create a pull request with that project. Once that pull request is merged, feel free to create an issue here and I'll release a new gem version with the updated list. In the meantime you can always run rake voight_kampff:import_user_agents
on your project to get that updated list.
Q: __Why don't you use the user agent list from ______________ If you know of a better source for a list of bot user agent strings, please create an issue and let me know. I'm open to switching to a better source or supporting multiple sources. There are others out there but I like the openness of monperrus' list.
Thanks to github.com/monperrus/crawler-user-agents for providing an open and easily updatable list of bot user agents.
PR without tests will not get merged, Make sure you write tests for api and rails app. Feel free to ask for help, if you do not know how to write a determined test.
bundle install
bundle exec rspec
Author: biola
Source code: https://github.com/biola/Voight-Kampff
License: MIT license