clemep8 has asked for the wisdom of the Perl Monks concerning the following question:

Following test app displays the problem:
use Test::More; use Plack::Test; use HTTP::Request::Common; use Ref::Util qw<is_coderef>; package AppA { use Dancer2; use Dancer2::Plugin::JWT; hook before_request => \&Util::before_request; get '/' => sub { return; }; }; package AppB { use Dancer2; use Dancer2::Plugin::JWT; hook before_request => \&Util::before_request; get '/' => sub { return; }; }; package Util { # use Dancer2; use Dancer2::Plugin::JWT; sub before_request { my $app = shift; my $jwt = jwt; print "BEFORE REQUEST WORKED: " . $app->name . " " . $ +jwt . "\n"; } }; my $a = AppA->to_app; ok(is_coderef($a), 'Got AppA'); my $b = AppB->to_app; ok(is_coderef($b), 'Got AppB'); my $t1 = Plack::Test->create($a); my $r1 = $t1->request(GET '/'); is($r1->code, 200, 'GET / A'); my $t2 = Plack::Test->create($b); my $r2 = $t2->request(GET '/'); is($r2->code, 200, 'GET / B'); done_testing();

as-is, the above takes jwt as a bareword (I cannot use strict or I get complaints) and it ends up rendered as just a string "jwt":

BEFORE REQUEST WORKED: AppA jwt
So it seems that jwt never gets properly registered.

If I uncomment the # use Dancer2; in package Util, then I get a stack trace due to:

Thu Dec 24 15:40:27 2020 error: AppA Route exception: Exception caught in 'core.app.before_request' filter: Hook error: Can't call method "var" on an undefined value at /root/perl5/lib/perl5/Dancer2/Plugin/JWT.pm line 32.

The use Dancer2 in Util makes jwt reference the "Util" app that gets auto-created and causes the app->request (which var is a member of) to be undefined.

Thoughts?

Also, is there a better forum for asking Dancer2-specific questions and/or JWT-specific questions?

Thanks.

Replies are listed 'Best First'.
Re: Dancer2 JWT with multiple apps isn't working
by alexander_lunev (Pilgrim) on Dec 25, 2020 at 08:31 UTC

    First of all, put use strict; in use.

    I'm not using Dancer, but it seems that you should use jwt() instead of bare jwt. And try to get plugin code from your $app reference, it seems more accurate and safe:

    package Util { use Dancer2; use Dancer2::Plugin::JWT; sub before_request { my $app = shift; my $jwt_plugin = $app->find_plugin('Dancer2::Plugin::JWT') or $app->dsl->send_error('Could not find JWT plugin'); my $jwt = $jwt_plugin->jwt(); print "BEFORE REQUEST WORKED: " . $app->name . " " . $jwt . "\n"; } };

    More of how to use Dancer plugins read in documentation Dancer2::Plugin.

      Thanks, this suggestion was actually already made by the JWT maintainer (ambs) in github:
      my $jwt_plugin = $app->with_plugin('Dancer2::Plugin::JWT'); my $jwt = $jwt_plugin->jwt();
      and, as you suggest, this:
      my $jwt_plugin = $app->find_plugin('Dancer2::Plugin::JWT'); my $jwt = $jwt_plugin->jwt();
      seems to work also.