Repository navigation
Expand file tree
/
Copy pathRequireCommitRules.php
More file actions
69 lines (54 loc) · 2.3 KB
/
Copy pathRequireCommitRules.php
File metadata and controls
69 lines (54 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use App\Contracts\Services\HumanVerificationProvider;
use App\Enums\ApiErrorCode;
use App\Exceptions\ApiException;
use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response;
final readonly class RequireCommitRules
{
public function __construct(private HumanVerificationProvider $humanVerification) {}
/**
* A first-time poster reads the commit rules on the web before their first commit, so it has to come from the web
* composer, which says they read them. After that, they can commit from anywhere.
*
* @param Closure(Request): (Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
$user = $request->user();
assert($user instanceof User);
if ($user->commit_rules_accepted_at !== null) {
return $next($request);
}
$fromWeb = ! $request->is('api/*');
if ($fromWeb && $request->boolean('commit_rules_accepted')) {
$token = $request->input('human_verification_token');
if (! is_string($token) || ! $this->humanVerification->isHuman($token)) {
throw ValidationException::withMessages([
'body' => __('Confirm that you are human first: reload the page and commit again.'),
]);
}
$user->update(['commit_rules_accepted_at' => now()]);
return $next($request);
}
$message = __('Welcome! Your first commit has to come from the web, so you can read the commit rules first: :url. After that, commit from anywhere.', [
'url' => url('/'),
]);
// The `devnull commit` script prints plain text...
if ($request->routeIs('cli-commit.store')) {
return response($message."\n", 403)->header('Content-Type', 'text/plain; charset=utf-8');
}
// The mobile app reads JSON with a code...
if (! $fromWeb) {
return new ApiException(ApiErrorCode::CommitRulesRequired, $message)->render();
}
throw ValidationException::withMessages([
'body' => __('Read the commit rules first: reload the page and commit again.'),
]);
}
}