[Solved] Add Recaptcha to Registration Form on Laravel 5.7 w/ Spark 7.0

Laravel Spark is a great for setting up user management, subscriptions, and an API quickly. Without Spark, these steps would take weeks. With spark it takes only a few hours.

But Spark does have some issues: mainly the documentation. For such and large system—particularly one that is paid ($99 per site)—there should be better documentation.

Context

Adding custom fields to the registration form is supposed to be easy. This customization is explicitly documented. However the steps do not work for added a Recaptcha to the registration form.

Normally, you would not need a captcha on the registration form because users have to pay to sign up. However, our app has a free tier. Another solution to this problem is requiring email verification. But email verification has its own problems.

Regardless, this is a problems others have had as well.

What is the issue

There are three problems with using Recaptcha on the registration page:

    1. Spark registration page does not support custom fields with dashes in the name. This is not documented. The Recaptcha custom field is called “g-recaptcha-response”.
    2. The Recaptcha field is created dynamically which does not work with the Vue powered form that ships with Spark.
    3. Spark registration calls the validator twice which causes Recaptcha validation to fail the second time.

The solution

  1. Remove dashes from the field name. Call it “grecaptcharesponse” instead of “g-recaptcha-response”.
  2. Manually put the recaptcha verification token into the “grecatpcharesponse” field before submitting the form
  3. Only call the validator once

Step by Step

  1. Create recaptcha validator
    php artisan make:rule Recaptcha
  2. Install Guzzle
    composer require guzzlehttp/guzzle
  3. Paste this into app/Rules/Recaptcha.php
<?php

namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use GuzzleHttp\Client;

class Recaptcha implements Rule
{
    public function passes($attribute, $value)
    {
        // this hack prevents the validator from failing the second time it is called.
        if (isset($GLOBALS['G_RECAPTCHA_RESULT']))
        {
            return $GLOBALS['G_RECAPTCHA_RESULT'];
        }

        $client = new Client();

        $response = $client->post(
            'https://www.google.com/recaptcha/api/siteverify',
            ['form_params'=>
                [
                    'secret' => env('RECAPTCHA_PRIVATE_KEY'),
                    'response' => $value
                ]
            ]
        );

        $body = json_decode((string)$response->getBody());
        $GLOBALS['G_RECAPTCHA_RESULT'] = $body->success;
        return $body->success;
    }

    public function message()
    {
        return 'Check the box "I\'m not a robot"';
    }
}
  1. Include the validator we just created at the top of your SparkServiceProvider.
    use App\Rules\Recaptcha;
  2. Add this to the booted method of your SparkServiceProvider:
Spark::validateUsersWith(function () {
    return [
        'name' => 'required|max:255',
        'grecaptcharesponse' => ['required', new Recaptcha],
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|confirmed|min:6',
        'terms' => 'required|accepted',
    ];
});
  1. Add this code to resources/js/app.js
Spark.forms.register = {
    grecaptcharesponse: 'abc'
};
  1. Add this to resources/views/vendor/spark/auth/register-common-form.blade.php where you want the recaptcha form to appear
<div class="form-group row">
    @push('scripts-header')
        <script src='https://www.google.com/recaptcha/api.js'></script>
    @endpush
    <label class="col-md-4 col-form-label text-md-right">Are you human?</label>

    <div class="col-md-6">
        <div class="g-recaptcha" data-sitekey="{{env('RECAPTCHA_PUBLIC_KEY')}}"></div>

        <span class="invalid-feedback" style="display: block;">
            @{{ registerForm.errors.get('grecaptcharesponse') }}
        </span>
    </div>
</div>
  1. Add this just before the closing head tag in your layout file:
    @stack['scripts-header']
  2. Update “sendRegistration” method in resources/js/spark/auth/register-stripe.js
sendRegistration() {
    if ($('#g-recaptcha-response').val())
    {
        this.registerForm.grecaptcharesponse = $('#g-recaptcha-response').val();
        grecaptcha.reset();
    }
    else
    {
        // put something here instead of an empty string so you get the 
        // Recaptcha error message instead of the "required" error message.
        this.registerForm.grecaptcharesponse = "abc";
    }

    Spark.post('/register', this.registerForm)
        .then(response => {
            window.location = response.redirect;
        });
}

Conclusion

That ended up being a little longer than I intended. Other gotchas you may encounter:

  • Laravel has recently moved the location of the assets files so your file structure may be different
  • You will need to publish the Spark vendor files in order to edit them

You can see this in action at BitcoinAbuse.com.

[Solved] Boot from USB on Dell XPS 13 9370

Ubuntu works very well on XPS laptops, but it is not so easy getting the laptop to boot from a USB.

Step 1: Change POST Behavior from “Fastboot” to “Thorough”

  1. At boot, Press the F2 key (or alternately press the F12 key then select the option to enter the BIOS setup).
  2. In POST Behavior, Select – Fastboot the select the Thorough option.

Step 2: Put USB in the right USB Type-C port

This is the main trick I have been unable to find documented anywhere else. The BIOS only recognizes bootable media in the right USB port.

  1. Create bootable Ubuntu USB (Or any other linux distro)
  2. Put USB in the right USB Type-C port. Only the right USB port will be detected in the boot options.
  3. Reboot the system, press F12.
  4. Select your USB in the boot options.

[Solved] Tmobile Moto G6 phone will not send or receive MMS messages

I had this problem on a my new phone. Found the solution on a T-Mobile forum but it was difficult to find. This post is to link back to the correct solution so it’s easier to find and to save the correct solution:


https://support.t-mobile.com/thread/146169

The problem has to do with the phone’s APN settings – which need to be tweaked.

1. Access your Android phone’s settings (gray settings icon that looks like a gear).

2. On the settings menu – select “Network & Internet”

3. On the “Network and Internet” menu – select “mobile network” (which should say “t-mobile” beneath the words “mobile network”)

4. On the “mobile network” menu – select “Access Point Names” (often abbreviated APN).

5. On the “APNs” menu – you should see two options: “T-mobile US” and “Tmobile MMS”. There should be a green dot next to “T-Mobile US”. Select that “T-Mobile US” option (NOT the Tmobile MMS).

6. This will open an “edit access point” menu, and you will need to make the following edits:

First – click on the MMSC option and add the following text: mms.msg.eng.t-mobile.com/mms/wapenc

Second – click on the “APN type” option. It will probably say something like: “default,supl,hipri,fota” (without the quotation marks). You will need to tweak the end of it so the whole thing instead reads “default,supl,hipri,fota,mms” (without the quotation marks). As indicated here – there are no spaces between these commas.

Third – after making these two adjustments to your APN – make sure you click on the menu dots (three vertical dots) at the top right hand part of the “edit access point” menu. This will open up a drop down menu – and then you should select “Save”. If you don’t do this – the settings will not take effect.

Thanks to cflaniken3.

Solved: Laravel 5 Calling the Wrong Controller

I recently encountered an issue that took me far longer to solve that it should have. Laravel is an excellent framework for building PHP websites. I have used it to build several sites now and it is by far the best framework I have seen. The latest version, Laravel 5, is powerful and well documented. With Composer, Laravel is easily extendable and allows you to pull in common php packages.

Up to this point, I had used Composer to pull in packages and manage dependencies without really knowing how it worked. Unfortunately, due to my lack of understanding, Composer’s Autoload feature caused an issue that was very hard to debug.

In the site I was making, I created a new configuration file that was used to dynamically set routes so I could create new sections and add those sections to the navigation menus in one step.

Next, I created a template controller that I would simply copy, rename, and start working with for each of these new sections.

Everything was working fine until I used Composer to install a new package on my production system. I installed Guzzle to which is need to interface with MailGun. When you install a new package Composer updates composer.json, installs the package, and reruns dump-autoload.

After setting up email, I thought the site was ready for production. All the sudden, one of my many dynamically created sections was not working. For some reason, the route for this one section was calling the Template Controller instead of the proper controller.

First, I though one of Laravel’s many layers of caching was the issue. I disabled Laravel’s route caching, configuration caching and view caching. I even turned off mod_pagespeed and CloudFlare just to be sure no caching was the problem. But it still was not working.

I decided to hard code the routes to skip over my dynamic route generator. But still for just one section the Template Controller was being called instead of the proper controller. I checked the routes file again and again to ensure there was no earlier route being called.

Eventually, I removed the Template Controller entirely and the section in question would error out saying TemplateController.php was not found. But how was this controller being called? The section was working before. Everything was working on my development machine. Just in production, this one section of the site was not working. For some reason, this route:

Route::get('/quarters',
['as' => 'quarters', 'uses' => 'Content\[email protected]']);

would call the TemplateControl[email protected]

At this point I had completely deleted the Template Controller. Something must be calling Template Controller somewhere.

So I decide to SSH into my production server and run:

$ grep -R 'TemplateController' public_html/

That grep command searches the entire web directory recursively for the string ‘TemplateController.’

grep_solution

As you can see, the string was first found in an error log file. But the final match led to the solution.

We can see a file called `vendor/composer/autoload_classmap.php` contains a line that seems to be mapping the `QuartersController` class to the `TemplateControllers` class. How did that get there?

It turns out, that when I created the `TemplateController` file, I did it by copying the `QuartersController` and stripping out all of the code specific the that section. Unfortunately, I forgot to change the name of the class in the `TemplatesController.php` file. I accidentally left that class name as `QuartersController`.

Now, that should not be an issue. I am not even using the `TemplatesController` class. It is only there for a starting point when creating new sections.

What I did not know at the time is when your run composer dump-autoload , composer scans your entire project’s source code and creates a `autoload_classmap.php` file. The classmap files allows the application to more quickly find the file containing a particular class.

Because I had two classes with the same name (one of them not being used), composer mapped to the wrong file. I changed the TemplateController.php class name, reran dump-autoload and everything worked again!

This error only surfaced after installing Guzzle because after a package install, composer runs dump-autoload automatically.

The moral here is that you can only use a tool without knowing how it works for so long before it comes back to bite you.