move into sonardesk

This commit is contained in:
Mark Gregory
2026-10-12 13:25:16 +01:00
parent 563f0979b3
commit b4e040999d
212 changed files with 7976 additions and 0 deletions
@@ -0,0 +1,108 @@
<?php
namespace App\Services\Accounts;
use App\Models\User;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use RuntimeException;
final class PurchasedAccountProvisioner
{
public function ensure(
?string $email,
?string $name = null,
bool $sendSetupLink = true
): ?User {
$email = strtolower(trim((string) $email));
if ($email === '' || ! filter_var($email, FILTER_VALIDATE_EMAIL)) {
return null;
}
/*
* Fast path for the normal case.
*
* Paddle can deliver several related webhook events concurrently, so
* this lookup alone cannot guarantee that another request will not
* create the user between this SELECT and our INSERT.
*/
$user = $this->findByEmail($email);
if ($user) {
return $user;
}
$created = false;
try {
$user = User::create([
'name' => $this->displayName($name, $email),
'email' => $email,
'email_verified_at' => now(),
'password' => Str::random(64),
'is_admin' => false,
]);
$created = true;
} catch (UniqueConstraintViolationException $exception) {
/*
* Another webhook may have created this account after our SELECT
* but before our INSERT. In that case the unique email constraint
* correctly rejects our INSERT; simply reuse the account that won
* the race.
*/
$user = $this->findByEmail($email);
if (! $user) {
/*
* The unique violation was not caused by the email account
* appearing concurrently, so preserve the original failure.
*/
throw $exception;
}
}
/*
* Only the request that actually created the account should send the
* account setup/reset link. Concurrent Paddle events must not result
* in several setup emails being sent to the customer.
*/
if ($created && $sendSetupLink) {
DB::afterCommit(static function () use ($email): void {
Password::sendResetLink(['email' => $email]);
});
}
return $user;
}
private function findByEmail(string $email): ?User
{
return User::query()
->whereRaw('LOWER(email) = ?', [$email])
->first();
}
private function displayName(?string $name, string $email): string
{
$name = trim((string) $name);
if ($name !== '') {
return mb_substr($name, 0, 120);
}
$localPart = strstr($email, '@', true) ?: 'SonarDesk Customer';
$localPart = trim(str_replace(['.', '_', '-'], ' ', $localPart));
return mb_substr(
$localPart !== ''
? ucwords($localPart)
: 'SonarDesk Customer',
0,
120
);
}
}
@@ -0,0 +1,65 @@
<?php
namespace App\Services;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use InvalidArgumentException;
final class IndexNowService
{
/** @param array<int, string> $urls */
public function submit(array $urls): ?Response
{
if (! config('indexnow.enabled')) {
Log::info('IndexNow submission skipped: disabled.');
return null;
}
$key = trim((string) config('indexnow.key'));
if ($key === '') {
throw new InvalidArgumentException('INDEXNOW_KEY is not configured.');
}
$urls = collect($urls)
->filter(fn ($url) => is_string($url) && filter_var($url, FILTER_VALIDATE_URL))
->unique()
->values()
->all();
if ($urls === []) {
throw new InvalidArgumentException('No valid URLs were supplied to IndexNow.');
}
$host = parse_url($urls[0], PHP_URL_HOST);
if (! is_string($host) || $host === '') {
throw new InvalidArgumentException('Could not determine the IndexNow host.');
}
foreach ($urls as $url) {
if (parse_url($url, PHP_URL_HOST) !== $host) {
throw new InvalidArgumentException('All IndexNow URLs must use the same host.');
}
}
$response = Http::asJson()
->acceptJson()
->timeout(10)
->retry(2, 500)
->post((string) config('indexnow.endpoint'), [
'host' => $host,
'key' => $key,
'keyLocation' => 'https://'.$host.'/'.$key.'.txt',
'urlList' => $urls,
]);
if ($response->successful()) {
Log::info('IndexNow URLs submitted.', ['host' => $host, 'count' => count($urls), 'status' => $response->status()]);
} else {
Log::warning('IndexNow submission failed.', ['host' => $host, 'count' => count($urls), 'status' => $response->status(), 'body' => $response->body()]);
}
return $response;
}
}
@@ -0,0 +1,63 @@
<?php
namespace App\Services\Payments;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
final class CustomerAccountProvisioner
{
public function ensure(?string $email, ?string $name = null): ?User
{
$email = strtolower(trim((string) $email));
if ($email === '' || ! filter_var($email, FILTER_VALIDATE_EMAIL)) {
return null;
}
$user = User::whereRaw('lower(email) = ?', [$email])->first();
if ($user) {
return $user;
}
$displayName = trim((string) $name);
if ($displayName === '') {
$displayName = Str::headline(Str::before($email, '@')) ?: 'SonarDesk Customer';
}
$user = User::firstOrCreate(
['email' => $email],
[
'name' => $displayName,
// The customer never receives or knows this password. They choose their
// own password through Laravel's signed, single-use reset flow.
'password' => Str::random(64),
// Access still requires possession of the mailbox because account setup
// is completed using the reset link sent to this address.
'email_verified_at' => now(),
],
);
if ($user->wasRecentlyCreated) {
DB::afterCommit(function () use ($email): void {
try {
$status = Password::sendResetLink(['email' => $email]);
if ($status !== Password::RESET_LINK_SENT) {
Log::warning('SonarDesk customer account created but setup email was not sent.', [
'email' => $email,
'status' => $status,
]);
}
} catch (\Throwable $exception) {
// A mail outage must never undo a paid licence. The customer can
// also use Forgot Password once mail is restored.
report($exception);
}
});
}
return $user;
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Services\Payments;
use Illuminate\Http\Request;
use RuntimeException;
final class LemonSqueezyWebhookVerifier implements WebhookVerifier
{
public function verify(Request $request, string $rawBody): void
{
$secret = (string) config('sonardesk.lemon_squeezy.webhook_secret');
$signature = (string) $request->header('X-Signature');
if ($secret === '' || $signature === '') {
throw new RuntimeException('Lemon Squeezy webhook verification is not configured.');
}
$expected = hash_hmac('sha256', $rawBody, $secret);
if (! hash_equals($expected, $signature)) {
throw new RuntimeException('Lemon Squeezy webhook signature is invalid.');
}
}
}
@@ -0,0 +1,10 @@
<?php
namespace App\Services\Payments;
use Illuminate\Http\Request;
interface WebhookVerifier
{
public function verify(Request $request, string $rawBody): void;
}