Default Filter in Laravel Nova

Posted on 20. Februar 2023 Comments

There is currently no way to use a Filter for a Resource in the default view. However, for the desired outcome, it’s possible to use a combination of the Nova indexQuery method and Laravels global scopes.

  1. Create a scope with the desired default filter: php artisan make:scope DefaultFilterScope
  2. Use this scope in the indexQuery method of the Nova Resource like so:
    public static function indexQuery(NovaRequest $request, $query) { return $query->withGlobalScope(DefaultFilterScope::class, new DefaultFilterScope); }
  3. In the other Filters for this Resource, add $query = $query->withoutGlobalScope(DefaultFilterScope::class); in the first line of the apply method, to remove the Global Scope added in the indexQuery method, and just use whatever the Filter does.

Source

404 with content using basic auth with nginx

Posted on 19. Juli 2022 Comments

When using e.g. Laravel Forge you can create a section of the website that’s restricted and uses HTTP Basic Access Authentication for access control. When the credentials aren’t entered correctly, the server returns a 401 error.

Basic Authentication prompt

However, when you would like to restrict a section that’s part of an application, whatever rules you defined in your /etc/nginx/sites-available/domain.tld.conf you have to now add to the new location section.

Example

On a staging server, you want to restrict access to /register and /login. Head to servers/X/sites/Y/security URL by clicking on the server, then select a site and click on „Security“. These entries create 2 files in /etc/nginx/forge-conf/domain.tld/server where ID is the ID you can see in Forge..

  • .htpasswd-ID
  • protected_site-ID.conf
Security Rules in Laravel Forge

However, when you now navigate to e.g. /login and enter your credentials, you will see a 404 for /login in the debug console. A request has been made and returned the content – just with the wrong status code. This is happening because there is no file called „login“ in the webserver public folder and nginx hasn’t been instructed to use PHP for this particular location.

tl;dr: You need to add this line to the location entry in the .conf files:

try_files $uri $uri/ /index.php?$query_string;

The whole file now looks like this:

location /register {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/forge-conf/domain.tld/server/.htpasswd-42;
try_files $uri $uri/ /index.php?$query_string;
}

Send private end-to-end encrypted Broadcast notifications with Laravel through Pusher

Posted on 22. August 2021 Comments

Pusher Channels allow an end-to-end (e2e) encrypted mode for their private channels. If you’re using Pusher as the BROADCAST_DRIVER in Laravel, it’s easy to enable this not only for broadcasted events but also notifications, so you can ->notify() the user without enabling Pusher to see what the content of the message is.

This is assuming you set up the authentication callback routes/broadcasting.php and it’s reachable (by default under /broadcasting/auth.)

  1. Add receivesBroadcastNotificationsOn() for the Notifiable Model (e.g. User)
    public function receivesBroadcastNotificationsOn()
    {
        // `private-` is added automatically
        return 'encrypted-App.Models.User.' . $this->id;
    }

The default implementation would be for a normal (not e2e) private channel and just return the FQCN in dot notation, followed by the Model ID.

Simply adding encrypted- before the channel name you now choose (or stick with the default suffix as above) will signal to Laravel to encrypt the messages before sending them out to pusher.

2. Add a shared key to config/broadcasting.php

'options' => [
                'cluster' => env('PUSHER_APP_CLUSTER'),
                'useTLS' => true,
                'encryption_master_key_base64' => env('PUSHER_APP_E2E_MASTER_KEY_BASE64'),
            ],

The end2end encryption is done synchronously with a shared key, stored base64 encoded. Of course, it’s important to keep this key secret. This encryption does not provide PFS, meaning, if the key ever leaks all old messages can be decrypted. Therefore, it’s probably a good idea to rotate it regularly or possibly not even use the same key for every user by manually changing the config before sending the message.

You can securely generate a key on the commandline or use PHP:

// Commandline
$ openssl rand -base64 32

// PHP
base64_encode(bin2hex(random_bytes(32)));

3. Client side

The client side using a pusher library recognizes the private-encrypted prefix. On successful authentication against /broadcasting/auth (or your custom authentication route) the shared key is transmitted in the response and used by the client to decrypt messages sent on that channel. You don’t need to worry about key distribution.

4. Double Check in the pusher.com debug console

You should only be able to see the none and the cyphertext, but not the plaintext message. If you do, something isn’t setup correctly yet.

5. Misc

The event for notifications to listen to is .Illuminate\\Notifications\\Events\\BroadcastNotificationCreated – don’t forget the . in front of it.

Laravel Nova: Move cards in Resource Detail View

Posted on 3. August 2021 Comments

Laravel Nova currently (v.3.27.0) doesn’t allow for custom cards to be moved to a different position in the resource detail page. Cards and Metrics appear always on top of the resources details.

However, while a bit dirty, a solution can be to let it load that way and then use Javascript to cut and paste the div somewhere else like so:

  1. Give the card an id
<template>
    <card class="flex flex-col justify-center" id="custom-card">

2. Use vanilla JS to move it underneath the first div with the name of the resource + detail-component for the dusk attribute

let customCard = document.querySelector('#custom-card');
        if(customCard) {
            let anotherComponent = document.querySelector('div[dusk=resourcename-detail-component]');
            if(anotherComponent) {
                anotherComponent.appendChild(customCard);
            } else {
                console.error('Could not find another resourcename detail component')
            }
        }

Autoload class alias order in Laravel tinker

Posted on 12. Juli 2021 Comments

When using tinker or tinkerwell without use statements or FQCN it tries to guess which class you mean by going through the autoloaded classes alphabetically. This might not be the class you most often used though, e.g. it is more likely I’d like to use App\Models\User, not the Livewire component of the same name.

$ tinker
UserPsy Shell v0.10.8 (PHP 8.0.8 — cli) by Justin Hileman
>>> User::first()
[!] Aliasing 'User' to 'App\Http\Livewire\User' for this Tinker session.

PHP provides the class_alias function but e.g. writing your own Service Provider for this will not work.

class ClassAliasesProvider extends ServiceProvider
{
    /**
     * Class Aliases defaults for tinker / tinkerwell.dev
     *
     * @return void
     */
    public function boot()
    {
        class_alias(User::class, 'User');
        //
    }
}

Instead, add your classes to the array in config(‚app.alias‘).

        // other default Laravel aliases
        'View' => Illuminate\Support\Facades\View::class,

        // Better autoloading for tinker / tinkerwell
        'User' => \App\Models\User::class,

The next time loading up tinker / tinkerwell, it will use the correct alias.

How to install curl with HTTP/3 and QUIC support on MacOS

Posted on 20. November 2020 Comments

Even if curl is installed via homebrew and not the MacOS default it does not automatically support HTTP/3 & QUIC. You will get this error message:

$ curl -vs --http3 https://quic.rocks:4433
option --http3: the installed libcurl version doesn't support this

After reading https://github.com/cloudflare/quiche/issues/319 and fiddling around with it a arrived at this solution:

$ wget https://raw.githubusercontent.com/cloudflare/homebrew-cloudflare/master/curl.rb
$ brew uninstall curl
$ brew install --HEAD -s curl.rb # takes a while
$ curl --version
curl 7.74.0-DEV
$ curl -vs --http3 https://quic.rocks:4433

Contribute to wappalyzer

Posted on 20. Mai 2020 Comments

Wappalyzer is an open source website analyzer written in node.js. It basically just parses a big json file and uses regular expressions to find patterns in websites HTML, CSS, JavaScript and Server Headers.

  1. Fork the repository https://github.com/AliasIO/wappalyzer
  2. Clone the fork to your computer
  3. Install Docker
  4. ./run links
  5. Write Regex
  6. Check with regex101.com or similar tool
  7. Add valid json to apps.json
  8. Add a 32×32, 64×64 PNG or SVG to the icons folder
  9. Commit to another branch on your fork
  10. Push
  11. Create Pull Request, showing that it’s a relevant project: 1k+ stars on GitHub, Pages using it etc

I just created a pull request for Alpine.js, A rugged, minimal framework for composing JavaScript behavior in your markup, that I like to pull in when Vue or React would be overkill.

Deploy with envoyer and artisan

Posted on 20. Mai 2020 Comments

I just revived JustParks Envoyer Deploy package and updated it for Laravel 5.5+ (handle() and fire() – both work now), 6 and 7. I haven’t written it, so all the credit goes to Dayle Rees/JustPark.

Updated envoyer:deploy package on packagist

As you can tell from the README, Install like so:

composer require repat/envoyer-deploy --dev

Then publish the config file by executing this and selecting the number that says JustPark\Deploy\ServiceProviders\EnvoyerServiceProvider.

php artisan vendor:publish

In the envoyer.php config file, fill in the unique ID that comes after the /deploy in the link you can find in the Deployment Hooks tab in envoyer, e.g. https://envoyer.io/deploy/4aLDdfsfsd4s6fSzeKGNfakekey75R45wOwTQULEDJNrj

You can now deploy with

php artisan envoyer:deploy

Sourcecode for repat/envoyer-deploy on GitHub

Digital Nomad Guide to Self-Isolation in New Zealand during the Corona Virus Outbreak 2020

Posted on 18. März 2020 Comments

Update: Well, as expected this post didn’t age well. New Zealand closed its borders to non-residents.

As anything written about the Corona Virus outbreak doesn’t age well, consider this article was written on Thursday 19th March 2020 and I entered NZ on Tuesday 17th March 2020. Things might’ve drastically changed by the time you read this, so do some more research! Also, this is not legal advice, obviously.

When you’re looking for (temporary) refuge from the recent Corona Virus outbreak and you’re in South-East Asia, New Zealand looks like a good option: it’s a civilized democracy with great healthcare, friendly people, a fairly reasonable government, good internet connection and low amount of confirmed cases so far. Even if you’re „stuck“ here for longer, I’m sure you won’t run out of things to do. Alternatives to New Zealand could be Australia and Singapore.

However, you will need to self-isolate for 14 days, so first things first, here’s the official NZ government website about how to self-isolate. There are always idiots that think they don’t have to follow these rules, but NZ police will do spot checks, as I can tell you also from personal experience. And while the rules are not as strict as in e.g. Singapore, they might also force quarantine or deport you if you break the rules or even change them while you’re still isolating.

Things to consider:

  1. A lot of nationalities (most of Europe, US, Canada) need to sign up for NZETA, the Kiwi version of US ESTA, a visa waiver program. It can take up to 72h and costs only $47 NZD so do it now, just to have the option. It’s valid for 2 years, so it’s not like it’s wasted money. For me it took literally one minute to get the confirmation. You have the right to stay 3 months with this or more if e.g. you’re a British Citizen.
  2. You need a return flight to either your home country or a place you have either a visa for or don’t need a visa. Check with passportindex.org for your passport. Common destinations are Australia, as flights are usually < $100 but you might need a visa, or visa waiver ETA for that too (not for transit) – some countries just need to sign up for free. However, this can also take 2 days or not arrive at all. Another option that’s visa free for a lot of passports is Singapore. You need this at check-in to board the flight to NZ.
  3. A lot of flights are already cancelled and more will probably follow as Air New Zealand for example announced a up to 85% cut of their routes. It seems like other Airlines will do the same as they really struggle at the moment. Chances are, the earlier you decide to come the easier it will be.
  4. New Zealand is far away from pretty much everything and it might be difficult to go back home, especially to Europe where no direct flights are available and you rely on transit hubs such as DXB, BKK or SIN. If something happens to your loved ones far away, it might take days and multiple hops and cancelled flights (so, lots of cash) to even get there in the future. Likewise, if something happens to you (and be it something unrelated to Covid-19, like a car accident), chances are your loved ones can’t come see you, certainly not for 14 days. There are however direct flights to the US possible.
  5. You will be asked if you’re sick before immigration, fill out an extra Covid-19 Form and they have a thermometer although they didn’t take peoples temperature when I arrived. That might have changed.
  6. There’s Uber and Uber Eats. When you arrive in Auckland AKL airport, the Uber pickup station is on your left. Take the exit next to McDonalds. It’s probably a more sensible option than public transport. You can let the Uber Eats delivery person know in the app to leave the food in front of the door or the lobby because you’re self-isolating and track when it arrives in the app.
  7. You can stay in Hotels, AirBnbs (try to get self-checkin) and (for now) camper vans, if they include a shower and toilet (so you don’t share public facilities). However, it seems you have to stay in one place and not take a road trip like these idiots, potentially infecting other people on camp grounds. You also have to inform the host that you’re self-isolating and not everybody will let you. The same goes for camp grounds/trailer parks.
  8. You are allowed to go outside to go e.g. grocery shopping but limit interaction both in distance (2m+) and time (< 15min). Obviously do this the least amount possible and buy lots in one go.
  9. Even though you could grocery shop, there’s online grocery shopping at Countdown.co.nz and New World with either pickup or delivery. They even have a Corona mode now, where they leave the food in front of the door. Obviously delivery is to be preferred but they are receiving a lot of orders nowadays and it can take 3-7 days until you get a delivery window. And just picking up a pre packed order is better than walking through the aisles. You might need to have a NZ telephone number to sign up and you can get SIM cards at the airports.
  10. Consider e.g. nightly walks, when less people are outside anyway. It’s important to take this seriously to make sure you and this wonderful host country stay safe, so stay at home as much as possible but also consider your mental health, getting some fresh air in and some sun light (while it’s still late summer), and read the CDC mental health guidelines as well as the ones from the NZ Minitry of Health.
  11. If you show any symptoms or feel unwell, call 0800 779 977 and also let your hotel, AirBnb host or camper van company know so they can be extra careful cleaning before the next person moves in.

Here’s the leaflet you will get at the airport:

Last but not least, chances are you are in Bali: There’s an Emirates flight directly from DPS-AKL at ~4 in the afternoon (coming from DXB), which has 20MB free WiFi and it’s $16 USD for the whole flight. If the login page doesn’t open go to http://172.19.248.2

Please honor the Kiwi hospitality and stay safe!