Skip to content

Instantly share code, notes, and snippets.

@Akron
Last active December 15, 2015 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Akron/6351d4f3981ce0b0cdb2 to your computer and use it in GitHub Desktop.
Save Akron/6351d4f3981ce0b0cdb2 to your computer and use it in GitHub Desktop.
Basic Auth
#!/usr/bin/env perl
use Modern::Perl;
use Mojolicious::Lite;
use Mojo::JSON;
use Test::More;
use Test::Mojo;
use Mojo::Util qw/b64_encode/;
plugin 'basic_auth';
my $username = 'testing';
my $password = '123456';
helper auth => sub {
my $self = shift;
return 1 if $self->basic_auth('netmgr-dev' => sub { return 1 if "@_" eq "$username $password" });
return undef;
};
under sub {
my $self = shift;
return 1 if $self->auth;
$self->render(text => "Access Denied",status => 401);
return undef;
};
# Root
get '/' => sub {
my $self = shift;
$self->render ( text => "OK");
};
# GET Testing
get '/login' => sub {
my $self = shift;
# get the username from URL and display back
my $data = $self->req->query_params->param('data') || undef;
if (defined $username ) {
$self->render(json => {data => "$data"});
}
};
# POST Testing
post '/login' => sub {
my $self = shift;
my $data = $self->req->json;
if (defined $data ) {
$self->render(json => {data => $$data{data}},status => 201);
}
};
my $t = Test::Mojo->new;
my $url = Mojo::URL->new('/')->userinfo("$username:$password");
$t->get_ok($url)->status_is(200)->content_like(qr/OK/);
$url->path('/login')->query(data => 'rubens');
# GET With Basic Auth
$t->get_ok($url)
->status_is(200)
->json_content_is({"data" => 'rubens'});
$url->query->remove('data');
# POST with Basic Auth
$t->post_ok($url => json => {"data" => "rubens"})
->status_is(201)
->json_content_is({"data" => 'rubens'});
done_testing;
exit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment