Mojolicious-Plugin-WebPush
view release on metacpan or search on metacpan
lib/Mojolicious/Plugin/WebPush.pm view on Meta::CPAN
my ($c, $error) = @_;
$c->render(status => 500, json => { errors => [ { message => $error } ] });
}
sub _make_route_handler {
my ($subs_session2user_p, $subs_create_p) = @_;
sub {
my ($c) = @_;
my ($decode_ok, $body) = _decode($c->req->body);
return _error($c, $body) if !$decode_ok;
eval { validate_subs_info($body) };
return _error($c, $@) if $@;
return $subs_session2user_p->($c, $c->session)->then(
sub { $subs_create_p->($c, $_[0], $body) },
)->then(
sub { $c->render(json => { data => { success => \1 } }) },
sub { _error($c, @_) },
);
};
}
lib/Mojolicious/Plugin/WebPush.pm view on Meta::CPAN
}, sub {
{ errors => [ { message => $_[0] } ] }
});
}
sub register {
my ($self, $app, $conf) = @_;
my @config_errors = grep !exists $conf->{$_}, @MANDATORY_CONF;
die "Missing config keys @config_errors\n" if @config_errors;
$app->helper('webpush.create_p' => sub {
eval { validate_subs_info($_[2]) };
return Mojo::Promise->reject($@) if $@;
goto &{ $conf->{subs_create_p} };
});
$app->helper('webpush.read_p' => $conf->{subs_read_p});
$app->helper('webpush.delete_p' => $conf->{subs_delete_p});
$app->helper('webpush.authorization' => (grep !$conf->{$_}, @AUTH_CONF)
? sub { die "Must provide @AUTH_CONF\n" }
: _make_auth_helper($app, $conf)
);
$app->helper('webpush.verify_token' => \&_verify_helper);
lib/Mojolicious/Plugin/WebPush.pm view on Meta::CPAN
$r->post($conf->{save_endpoint} => _make_route_handler(
@$conf{qw(subs_session2user_p subs_create_p)},
), 'webpush.save');
push @{ $app->renderer->classes }, __PACKAGE__;
$app->serviceworker->add_event_listener(
push => $conf->{push_handler} || $DEFAULT_PUSH_HANDLER
);
$self;
}
sub validate_subs_info {
my ($info) = @_;
die "Expected object\n" if ref $info ne 'HASH';
my @errors = map "no $_", grep !exists $info->{$_}, qw(keys endpoint);
push @errors, map "no $_", grep !exists $info->{keys}{$_}, qw(auth p256dh);
die "Errors found in subscription info: " . join(", ", @errors) . "\n"
if @errors;
}
1;
$t->post_ok('/login/bob')->status_is(200)->content_is('Hello bob');
};
my @SUBS = (
[ { keys => {} }, qr/no endpoint/ ],
[ { endpoint => '/push/bob/v2' }, qr/no keys/ ],
[ { endpoint => '/push/bob/v2', keys => { p256dh => '' } }, qr/no auth/ ],
[ { endpoint => '/push/bob/v2', keys => { auth => '' } }, qr/no p256dh/ ],
[ { endpoint => '/push/bob/v2', keys => { auth => '', p256dh => '' } }, qr/^$/ ],
);
subtest 'validate' => sub {
for (@SUBS) {
eval { Mojolicious::Plugin::WebPush::validate_subs_info($_->[0]) };
like $@, $_->[1];
}
};
my $bob_data = { endpoint => '/push/bob/v2', keys => { auth => '', p256dh => '' } };
subtest 'save' => sub {
$t->post_ok($ENDPOINT, json => {})
->status_is(500)->json_like('/errors/0/message', qr/no endpoint/)
->or(sub { diag explain $t->tx->res->body })
;
( run in 0.678 second using v1.01-cache-2.11-cpan-39bf76dae61 )