adrianmak

How to attach google recaptcha in default pw admin login form ?

Recommended Posts

Hi @adrianmak

You can achieve this by using hooks and my ReCaptcha module.

 

First install the MarkupGoogleReCaptcha module then in file ready.php, write the following code :

/*
 *  replace the LAST occurence of $search by $replace in $subject
 */
function str_lreplace($search, $replace, $subject) {

    return preg_replace('~(.*)' . preg_quote($search, '~') . '~', '$1' . $replace, $subject, 1);
}
/*
 *  replace the FIRST occurence of $search by $replace in $subject
 */
function str_freplace($search, $replace, $subject) {

    $from = '/'.preg_quote($search, '/').'/';
    return preg_replace($from, $replace, $subject, 1);
}

$captchamod = wire('modules')->get("MarkupGoogleRecaptcha");

wire()->addHookProperty('Page::captcha', function($event) use ($captchamod) {
    $event->return = $captchamod;
});

wire()->addHookAfter('Page::render', function($event) {

    $template = $event->object->template;
    $page = $event->object;

    if ($template == 'admin' && !wire('user')->isLoggedin()) {
        $captchaScript = $page->captcha->getScript() . '</body>';
        $captchaHtml = $page->captcha->render() . '</form>';
        $event->return = str_freplace('</form>', $captchaHtml, $event->return);
        $event->return = str_lreplace('</body>', $captchaScript, $event->return);
    }
});

wire()->addHookAfter('Session::authenticate', function($event) {

    $page = wire('page');
    $template = $page->template;

    if ($template == 'admin') {
        if ($page->captcha->verifyResponse() == false) {
            wire('session')->logout();
            wire('session')->redirect(wire('config')->urls->admin);
        }
    }
});

 

admin-recaptcha.png.d68de0d46d449b3f5bfb7b868a580862.png

  • Like 8

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By flydev
      MarkupGoogleRecaptcha
      Google reCAPTCHA for ProcessWire.
      This module simply adds reCAPTCHA V2 or Invisible reCAPTCHA to your form.

      How To Install
      Download the zip file at Github or from the modules repository Drop the module files in /site/modules/MarkupGoogleRecaptcha In your admin, click Modules > Refresh Click "install" for "MarkupGoogleRecaptcha" Official install/uninstall doc: http://modules.processwire.com/install-uninstall/
       
      API
      You must create an API key prior to use this module. Goto https://www.google.com/recaptcha/admin to create your own. Next, add the API keys information to the module's settings.

       
      Usage
      Call the module : $captcha = $modules->get("MarkupGoogleRecaptcha"); Call $captcha->getScript(); somewhere to get the javascript used by reCAPTCHA Render reCAPTCHA in a standard HTML <form></form> by calling $captcha->render() or Render reCAPTCHA in an InputfieldForm by passing as argument your form to the render function: $captcha->render($form) Call verifyResponse() to get the result. It return TRUE if the challenge was successful.  
      Example
      Using ProcessWire's form API : $out = ''; $captcha = $modules->get("MarkupGoogleRecaptcha"); // if submitted, check response if ($captcha->verifyResponse() === true) { $out .= "Hi " . $input->post["name"].", thanks for submitting the form!"; } else { $form = $modules->get("InputfieldForm"); $form->action = $page->url; $form->method = "post"; $form->attr("id+name", "form"); $field = $this->modules->get('InputfieldText'); $field->name = "name"; $field->placeholder = "name"; $form->add($field); // CAPTCHA - our form as argument, the function will add an InputfieldMarkup to our form $captcha->render($form); // add a submit button $submit = $this->modules->get("InputfieldSubmit"); $submit->name = "submit"; $submit->value = 'Submit'; $form->add($submit); $out .= $form->render(); // include javascript $out .= $captcha->getScript(); } echo $out;  
      Example using plain HTML Form : $captcha = $modules->get("MarkupGoogleRecaptcha"); // if submitted check response if ($captcha->verifyResponse() === true) { $out .= "Hi " . $input->post["name"] . ", thanks for submitting the form!"; } else { $out .= "<form method='post' action='{$page->url}'>\n" . "\t<input type='text' name='name'>\n" . $captcha->render() // render reCaptcha . "\t<input type='submit'>\n" . "</form>\n"; $out .= $captcha->getScript(); } echo $out;  
       

    • By giannisok
      Simple Contact Form
      Using Google Recaptcha & Valitron validation library



      I just finished creating a simple Contact-Form for a client's website so i thought it would be really helpfull to share it with the community.
      The contact form uses:
      Google recaptcha for validating the user is not a robot (https://github.com/google/recaptcha) Valitron validation library for validating the form fields (https://github.com/vlucas/valitron) Twitter Bootstrap 3.0.0 for form HTML The contact-form is located inside a contact-page, so the bare minimum you need in order to setup your own is:
      contact.php (template file used by your contact-page)  _contact-controller.php (file used as a controller for your contact-form functionality like send email, validate fields etc) 2 extra lines inside your composer.json file
      So, let's start:
      First you need to update your composer.json file adding 2 lines inside the require object:
      "vlucas/valitron": "^1.2", "google/recaptcha": "~1.1" Here is a sample composer.json file:
      {   "name": "processwire/processwire",   "type": "library",   "description": "ProcessWire CMS/CMF",   "keywords": [ "cms","cmf", "content management system" ],   "homepage": "https://processwire.com",   "authors": [     {       "name": "Ryan Cramer",       "email": "ryan@processwire.com",       "homepage": "https://processwire.com",       "role": "Developer"     }   ],   "require": {     "php": ">=5.3.8",     "ext-gd": "*",     "vlucas/valitron": "^1.2",     "google/recaptcha": "~1.1"   },   "autoload": {     "files": [ "wire/core/ProcessWire.php" ]   },   "minimum-stability": "dev" } open console and navigate to processwire root folder (where composer.json file is)
      on this step i assume you have already setup composer for your project, otherwise google it 
      run the following command:
      composer update this will create a vendor folder (if it does not already exist) and download valitron and google recaptcha libraries.
      Then open your contact-page template file(usually named contact.php inside your templates directory) and add the following:
      * Note: The form below uses bootstrap 3.0.0 css, so if you are using something else you need to make the appropriate changes.
      <?php namespace ProcessWire; include('_contact-controller.php') ?> <div class="container"> <div class="row"> <div class=" col-md-4"> <h2>Contact Form</h2> <?php if($session->flashMessage):?> <div class="alert <?=!$session->sent && (!$v->validate() || !$resp->isSuccess()) ? 'alert-danger' : 'alert-success'?>" role="alert"> <?php echo $session->flashMessage;?> </div> <?php endif;?> <form id="contact-form" method="post"> <div class="form-group <?=$v->errors('name') ? 'has-error' : ''?>"> <label for="name">Name</label> <input class="form-control" name="name" id="name" type="text" value="<?=$sanitizer->text($input->post->name)?>"> </div> <div class="form-group <?=$v->errors('email') ? 'has-error' : ''?>"> <label for="email">Email</label> <input class="form-control" name="email" id="email" type="text" value="<?=$sanitizer->text($input->post->email)?>"> </div> <div class="form-group <?=$v->errors('message') ? 'has-error' : ''?>"> <label for="message">Message</label> <textarea class="form-control" name="message" id="message"><?=$sanitizer->text($input->post->message)?></textarea> </div> <div class="form-group"> <!-- Google Recaptcha code START --> <div class="g-recaptcha" data-sitekey="<?=$googleSiteKey?>"></div> <script type="text/javascript" src="https://www.google.com/recaptcha/api.js"> </script> <!-- Google Recaptcha code END --> </div> <button type="submit" class="btn btn-primary">SEND</button> </form> </div> </div> </div> <?php     //here we remove the flash-message because it is already shown above the form.     $session->remove('flashMessage');     //reset 'sent' variable for future submit $session->sent = false; ?>
      Next create a file inside you templates directory with name: _contact-controller.php:
      and set the required variables($googleSiteKey, $contactFormRecipient, $contactPageID)
      <?php namespace ProcessWire; /** *    here we include Valitron & Google recaptcha libraries *    make sure the path is correct in your template */ include(dirname(__FILE__) . "/../../vendor/vlucas/valitron/src/Valitron/Validator.php"); include(dirname(__FILE__) . '/../../vendor/google/recaptcha/src/ReCaptcha/ReCaptcha.php'); /** *    here we add the form field values to Valitron */ $v = new \Valitron\Validator(array(         'name' => $sanitizer->text($input->post->name),         'email' => $sanitizer->email($input->post->email),         'message' => $sanitizer->text($input->post->message),     ) ); /** *    validation rules set for each form field *    For more details on Valitron/Validator usage visit:  *    https://github.com/vlucas/valitron */ $v->rule('required', ['name', 'email', 'message']); $v->rule('lengthMin', 'name', 5); $v->rule('email', 'email'); /** *    set Google recaptcha site-key & secret-key *    create a new key from: https://www.google.com/recaptcha/admin */ $googleSiteKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; $googleSecretKey = 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY'; /** *    set the email of the contact form recipient(usually the website owner) */ $contactFormRecipient = 'your@company.com'; /** *    set the id of contact-page in order to redirect there when the form is sent */ $contactPageID = '1045'; //here we check whether the 'name' field exists inside post variables (which means the form is posted) if ($input->post->name) {     //if fields validation passes     if ($v->validate()) {         $reCaptcha = new \ReCaptcha\ReCaptcha($googleSecretKey);         $resp = $reCaptcha->verify($input->post->{'g-recaptcha-response'}, $_SERVER["REMOTE_ADDR"]);         //if google-recaptcha validation passes         if ($resp->isSuccess()) {                      //This is the HTML message             $message = '                 <html>                     <head>                         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />                         <title>Contact Form | ' . $input->post->name . '</title>                     </head>                     <body>                         <p>' . $input->post->message . '</p>                     </body>                 </html>';             //here we send the form to $contactFormRecipient             wireMail($contactFormRecipient, $input->post->email, "Contact Form | " . $input->post->name, $message);                          //here we set a flash-message to notify the user that the form was successfully sent             $session->flashMessage = 'Thank you for your message! We will get in touch with you shortly.';              //save in session that the form is sent $session->sent = true;             //finally redirect user to contact-page             $session->redirect($pages->get($contactPageID)->url);         } else {             //self explain             $session->flashMessage = 'Error while validating you are not a robot!';         }     } } ?> Thats all!
      You now have a simple contact-form working with captcha and field validation!
      I would be more than happy to help anyone having problems on the setup.