Skip to content

Instantly share code, notes, and snippets.

@jhthorsen
Last active September 18, 2017 15:06
Show Gist options
  • Save jhthorsen/f6a2df9f4d2cf3a211bb022a492357a8 to your computer and use it in GitHub Desktop.
Save jhthorsen/f6a2df9f4d2cf3a211bb022a492357a8 to your computer and use it in GitHub Desktop.
diff --git a/lib/Mojo/JWT.pm b/lib/Mojo/JWT.pm
index 11fdb2b..0281ff1 100644
--- a/lib/Mojo/JWT.pm
+++ b/lib/Mojo/JWT.pm
@@ -5,6 +5,9 @@ use Mojo::Base -base;
our $VERSION = '0.05';
$VERSION = eval $VERSION;
+our @EXPORT_OK = qw/decode_jwt encode_jwt/;
+
+use Exporter 'import';
use Mojo::JSON qw/encode_json decode_json/;
use MIME::Base64 qw/encode_base64url decode_base64url/;
@@ -125,6 +128,18 @@ sub verify_rsa {
return $crypt->verify($payload, $signature);
}
+sub decode_jwt {
+ my $token = shift;
+ my $attrs = ref $_[0] ? shift : @_ == 1 ? {secret => $_[0]} : {@_};
+ return Mojo::JWT->new($attrs)->decode($token);
+}
+
+sub encode_jwt {
+ my $claims = shift;
+ my $attrs = ref $_[0] ? shift : @_ == 1 ? {secret => $_[0]} : {@_};
+ return Mojo::JWT->new({%$attrs, claims => $claims})->encode;
+}
+
1;
=head1 NAME
diff --git a/t/basic.t b/t/basic.t
index f6ed8e7..5264600 100644
--- a/t/basic.t
+++ b/t/basic.t
@@ -3,7 +3,7 @@
use Mojo::Base -strict;
use Test::More;
-use Mojo::JWT;
+use Mojo::JWT qw/decode_jwt encode_jwt/;
my $has_rsa = eval { require Crypt::OpenSSL::RSA; 1 };
@@ -18,6 +18,33 @@ my $has_rsa = eval { require Crypt::OpenSSL::RSA; 1 };
}
{
+ my $name = 'encodes and decodes with functions';
+ my $secret = 'secret';
+ my $payload = {foo => 'bar'};
+ my $jwt = encode_jwt $payload, $secret;
+ my $decoded_payload = decode_jwt $jwt, $secret;
+ is_deeply $decoded_payload, $payload, $name;
+}
+
+{
+ my $name = 'encodes and decodes with functions and attribute list';
+ my $secret = 'secret';
+ my $payload = {foo => 'bar'};
+ my $jwt = encode_jwt $payload, secret => $secret;
+ my $decoded_payload = decode_jwt $jwt, secret => $secret;
+ is_deeply $decoded_payload, $payload, $name;
+}
+
+{
+ my $name = 'encodes and decodes with functions and attributes';
+ my $secret = 'secret';
+ my $payload = {foo => 'bar'};
+ my $jwt = encode_jwt $payload, {secret => $secret};
+ my $decoded_payload = decode_jwt $jwt, {secret => $secret};
+ is_deeply $decoded_payload, $payload, $name;
+}
+
+{
no warnings 'once';
no warnings 'redefine';
my $now = time;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment