Browse Source

reCAPTCHA integration

develop
Raphael Jackstadt 11 years ago
parent
commit
2b934aaade
  1. 5
      application/config/aauth.php
  2. 141
      application/helpers/recaptchalib_helper.php
  3. 1
      application/language/english/aauth_lang.php
  4. 132
      application/libraries/Aauth.php

5
application/config/aauth.php

@ -55,6 +55,11 @@ $config['aauth'] = array(
//if it is true, the user will be banned temporary when he exceed the login 'try'
'ddos_protection' => true,
'recaptcha_active' => false,
'recaptcha_login_attempts' => 4,
'recaptcha_siteKey' => '',
'recaptcha_secret' => '',
// login attempts time interval
// default 20 times in one hour
'max_login_attempt' => 10,

141
application/helpers/recaptchalib_helper.php

@ -0,0 +1,141 @@
<?php
/**
* This is a PHP library that handles calling reCAPTCHA.
* - Documentation and latest version
* https://developers.google.com/recaptcha/docs/php
* - Get a reCAPTCHA API Key
* https://www.google.com/recaptcha/admin/create
* - Discussion group
* http://groups.google.com/group/recaptcha
*
* @copyright Copyright (c) 2014, Google Inc.
* @link http://www.google.com/recaptcha
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* A ReCaptchaResponse is returned from checkAnswer().
*/
class ReCaptchaResponse
{
public $success;
public $errorCodes;
}
class ReCaptcha
{
private static $_signupUrl = "https://www.google.com/recaptcha/admin";
private static $_siteVerifyUrl =
"https://www.google.com/recaptcha/api/siteverify?";
private $_secret;
private static $_version = "php_1.0";
/**
* Constructor.
*
* @param string $secret shared secret between site and ReCAPTCHA server.
*/
function ReCaptcha($secret)
{
if ($secret == null || $secret == "") {
die("To use reCAPTCHA you must get an API key from <a href='"
. self::$_signupUrl . "'>" . self::$_signupUrl . "</a>");
}
$this->_secret=$secret;
}
/**
* Encodes the given data into a query string format.
*
* @param array $data array of string elements to be encoded.
*
* @return string - encoded request.
*/
private function _encodeQS($data)
{
$req = "";
foreach ($data as $key => $value) {
$req .= $key . '=' . urlencode(stripslashes($value)) . '&';
}
// Cut the last '&'
$req=substr($req, 0, strlen($req)-1);
return $req;
}
/**
* Submits an HTTP GET to a reCAPTCHA server.
*
* @param string $path url path to recaptcha server.
* @param array $data array of parameters to be sent.
*
* @return array response
*/
private function _submitHTTPGet($path, $data)
{
$req = $this->_encodeQS($data);
$response = file_get_contents($path . $req);
return $response;
}
/**
* Calls the reCAPTCHA siteverify API to verify whether the user passes
* CAPTCHA test.
*
* @param string $remoteIp IP address of end user.
* @param string $response response string from recaptcha verification.
*
* @return ReCaptchaResponse
*/
public function verifyResponse($remoteIp, $response)
{
// Discard empty solution submissions
if ($response == null || strlen($response) == 0) {
$recaptchaResponse = new ReCaptchaResponse();
$recaptchaResponse->success = false;
$recaptchaResponse->errorCodes = 'missing-input';
return $recaptchaResponse;
}
$getResponse = $this->_submitHttpGet(
self::$_siteVerifyUrl,
array (
'secret' => $this->_secret,
'remoteip' => $remoteIp,
'v' => self::$_version,
'response' => $response
)
);
$answers = json_decode($getResponse, true);
$recaptchaResponse = new ReCaptchaResponse();
print_r($answers);
if (trim($answers['success']) == true) {
$recaptchaResponse->success = true;
} else {
$recaptchaResponse->success = false;
$recaptchaResponse->errorCodes = $answers['error-codes'];
}
return $recaptchaResponse;
}
}
?>

1
application/language/english/aauth_lang.php

@ -22,6 +22,7 @@ $lang['no_access'] = 'You dont have access.';
//
$lang['wrong'] = 'E-mail or Password is wrong.';
$lang['exceeded'] = 'Login try limit exceeded.';
$lang['recaptcha_not_correct'] = 'reCAPTCHA is incorrect.';
$lang['no_user'] = 'User not Exist';
$lang['not_verified'] = 'Please verify your account.';
$lang['group_exist'] = 'Group already exists';

132
application/libraries/Aauth.php

@ -61,6 +61,9 @@ class Aauth {
$this->CI = & get_instance();
// Dependancies
if(CI_VERSION >= 2.2){
$this->CI->load->library('driver');
}
$this->CI->load->library('session');
$this->CI->load->library('email');
$this->CI->load->database();
@ -68,12 +71,13 @@ class Aauth {
$this->CI->load->helper('string');
$this->CI->load->helper('email');
$this->CI->load->helper('language');
$this->CI->load->helper('recaptchalib');
$this->CI->lang->load('aauth');
// config/aauth.php
$this->CI->config->load('aauth');
$this->config_vars = & $this->CI->config->item('aauth');
$this->config_vars = $this->CI->config->item('aauth');
}
@ -130,6 +134,15 @@ class Aauth {
$this->error($this->CI->lang->line('exceeded'));
return false;
}
if($query->num_rows() > 0 and $this->config_vars['ddos_protection'] and $this->config_vars['recaptcha_active'] and $row->login_attempts >= $this->config_vars['recaptcha_login_attempts']){
$reCAPTCHA_cookie = array(
'name' => 'reCAPTCHA',
'value' => 'true',
'expire' => time()+7200,
'path' => '/',
);
$this->CI->input->set_cookie($reCAPTCHA_cookie);
}
// if user is not verified
$query = null;
@ -164,6 +177,15 @@ class Aauth {
$query = $this->CI->db->get($this->config_vars['users']);
$row = $query->row();
if($this->CI->input->cookie('reCAPTCHA', TRUE) == 'true'){
$reCaptcha = new ReCaptcha( $this->config_vars['recaptcha_secret']);
$resp = $reCaptcha->verifyResponse( $this->CI->input->server("REMOTE_ADDR"), $this->CI->input->post("g-recaptcha-response") );
if(!$resp->success){
$this->error($this->CI->lang->line('recaptcha_not_correct'));
return false;
}
}
// if email and pass matches and not banned
if ( $query->num_rows() > 0 ) {
@ -197,9 +219,18 @@ class Aauth {
$this->CI->input->set_cookie($cookie);
}
$reCAPTCHA_cookie = array(
'name' => 'reCAPTCHA',
'value' => 'false',
'expire' => time()-3600,
'path' => '/',
);
$this->CI->input->set_cookie($reCAPTCHA_cookie);
// update last login
$this->update_last_login($row->id);
$this->update_activity();
$this->reset_login_attempts($row->id);
return TRUE;
}
@ -333,7 +364,7 @@ class Aauth {
*/
public function reset_login_attempts($user_id) {
$data['last_login_attempts'] = null;
$data['login_attempts'] = null;
$this->CI->db->where('id', $user_id);
return $this->CI->db->update($this->config_vars['users'], $data);
}
@ -446,7 +477,6 @@ class Aauth {
$data = array();
if ( strtotime($row->last_login_attempt) == strtotime(date("Y-m-d H:0:0"))) {
$data['login_attempts'] = $row->login_attempts + 1;
$query = $this->CI->db->where('id', $user_id);
@ -501,15 +531,19 @@ class Aauth {
* @param string $name User's name
* @return int|bool False if create fails or returns user id if successful
*/
public function create_user($email, $pass, $name='') {
public function create_user($email, $pass, $name) {
$valid = true;
// if email is already exist
if ( ! $this->check_email($email)) {
if ($this->user_exsist_by_email($email)) {
$this->error($this->CI->lang->line('email_taken'));
$valid = false;
}
if ($this->user_exsist_by_name($name)) {
$this->error($this->CI->lang->line('name_taken'));
$valid = false;
}
if ( ! valid_email($email)){
$this->error($this->CI->lang->line('email_invalid'));
@ -523,6 +557,10 @@ class Aauth {
$this->error($this->CI->lang->line('name_invalid'));
$valid = false;
}
if (empty($name)){
$this->error($this->CI->lang->line('name_invalid'));
$valid = false;
}
if (!$valid) {
return false; }
@ -803,6 +841,60 @@ class Aauth {
return FALSE;
}
/**
* user_exsist_by_id
* Check if user exist by user id
* @param $user_id
*
* @return bool
*/
public function user_exsist_by_id( $user_id ) {
$query = $this->CI->db->where('id', $user_id);
$query = $this->CI->db->get($this->config_vars['users']);
if ($query->num_rows() > 0)
return TRUE;
else
return FALSE;
}
/**
* user_exsist_by_name
* Check if user exist by name
* @param $user_id
*
* @return bool
*/
public function user_exsist_by_name( $name ) {
$query = $this->CI->db->where('name', $name);
$query = $this->CI->db->get($this->config_vars['users']);
if ($query->num_rows() > 0)
return TRUE;
else
return FALSE;
}
/**
* user_exsist_by_email
* Check if user exsist by user email
* @param $user_email
*
* @return bool
*/
public function user_exsist_by_email( $user_email ) {
$query = $this->CI->db->where('email', $user_email);
$query = $this->CI->db->get($this->config_vars['users']);
if ($query->num_rows() > 0)
return TRUE;
else
return FALSE;
}
/**
* Get user id
* Get user id from email address, if par. not given, return current user's id
@ -844,26 +936,6 @@ class Aauth {
return $query = $this->CI->db->get()->result();
}
//tested
/**
* Check email
* Checks if an email address is available
* @param string $email Email to check
* @return bool True if available, False if not
*/
public function check_email($email) {
$this->CI->db->where("email", $email);
$query = $this->CI->db->get($this->config_vars['users']);
if ($query->num_rows() > 0) {
$this->info($this->CI->lang->line('email_taken'));
return FALSE;
}
else
return TRUE;
}
//tested
/**
* Update activity
@ -1911,6 +1983,16 @@ class Aauth {
}
}
public function generate_recaptcha_field(){
$content = '';
if($this->config_vars['ddos_protection'] and $this->config_vars['recaptcha_active'] and $this->CI->input->cookie('reCAPTCHA', TRUE) == 'true'){
$content .= "<script type='text/javascript' src='https://www.google.com/recaptcha/api.js'></script>";
$siteKey = $this->config_vars['recaptcha_siteKey'];
$content .= "<div class='g-recaptcha' data-sitekey='{$siteKey}'></div>";
}
return $content;
}
} // end class
// $this->CI->session->userdata('id')

Loading…
Cancel
Save