examples/custom-middleware/lib/Example/Middleware/ApiKey.pm

filter: Statementstmt 100% 29 / 29 Branchbran 100% 4 / 4 Conditioncond 60.0% 3 / 5 MC/DCmcdc 33.3% 1 / 3 Subroutinesub 100% 9 / 9 Podpod 100% 1 / 1 totaltotal 92.1% 47 / 51 CC 6 SCAR 8.3
CC
6
Cov
95%
_header
4.0
__ANON__
3.0
wrap
1.0
CRAP 2.3
« examples/sse-custom-events/app.pl ↑ Summary examples/periodic-events/app.pl »
1 package Example::Middleware::ApiKey;
2 1 ▶use v5.40;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 1 ▶use experimental 'signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use PAGI::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use parent 'PAGI::Middleware';
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 # A guard middleware: require a matching X-Api-Key header or short-circuit with a
9 # 401, never reaching the handler. It is configured with a key, so it is
10 # pre-instantiated and scoped to a route ([ ...->new(key => ...) ]) rather than
11 # named — route-scoped middleware take no constructor args.
12  
13 1 ▶sub _init ($self, $config) { $self->{key} = $config->{key} }
Subroutine _init: called CC=1 SCAR=0.0
14  
15 1 ▶sub wrap ($self, $app) {
Subroutine wrap: called CC=1 SCAR=0.0
Pod documented
16 1 my $want = $self->{key};
17 2 ▶ return async sub ($scope, $receive, $send) {
Subroutine __ANON__: called CC=3 SCAR=11.0
18 2 my $given = _header($scope, 'x-api-key');
19 2 ▶ if (!defined $given || $given ne $want) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $given or $given ne $want) 1 1 2
Condition66%2/3
not defined $given or $given ne $want
l!l&&r!l&&!r
101
MC/DC50%1/2
not defined $given or $given ne $want
not defined $given $given ne $want
Truth table66%2/3
not(A) or B
A= not defined $givenB= $given ne $want
ABresult
1X1
011
000
20 1 my $res = PAGI::Response->json({ error => 'unauthorized' }, status => 401);
21 1 return await $res->respond($send); # short-circuit; $app never runs
22 }
23 1 await $app->($scope, $receive, $send);
24 1 };
25 }
26  
27 # Scan the raw scope headers (an arrayref of [lc-name, value] pairs).
28 2 ▶sub _header ($scope, $name) {
Subroutine _header: called CC=4 SCAR=13.9
29 2 ▶ for my $pair (@{ $scope->{headers} // [] }) {
Condition50%1/2
$scope->{"headers"} // []
l!l
20
MC/DC0%0/1
$scope->{"headers"} // []
$scope->{"headers"}
Truth table50%1/2
A
A= $scope->{"headers"}
Aresult
11
00
30 3 ▶ return $pair->[1] if lc($pair->[0]) eq $name;
Branch: 1 branch
BranchTrueFalseTotal
if lc $pair->[0] eq $name 1 2 3
31 }
32 1 return undef;
33 }
34  
35 1 1;
« examples/sse-custom-events/app.pl ↑ Summary examples/periodic-events/app.pl »