summary refs log tree commit diff
path: root/lib/MooseX/Net/API/Role/Authentication.pm
blob: 6c3864160ae867b63d4095038a5c044fd14b4870 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package MooseX::Net::API::Role::Authentication;

use Moose::Role;

has api_username => (
    is      => 'rw',
    isa     => 'Str',
    predicate => 'has_api_username',
);

has api_password => (
    is      => 'rw',
    isa     => 'Str',
    predicate => 'has_api_password',
);

# ugly :(
after BUILDALL => sub {
    my $self = shift;

    for (qw/api_username api_password/) {
        my $predicate = 'has_' . $_;
        my $value     = $self->meta->get_option($_);
        $self->$_($value) if $value && !$self->$predicate;
    }

    if (my $has_auth = $self->meta->get_option('authentication')) {
        my $auth_method = $self->meta->get_option('authentication_method');
        if ($auth_method) {
            $self->api_useragent->add_handler(
                request_prepare => sub { $self->$auth_method(@_) });
        }
        else {
            if ($self->has_api_username && $self->has_api_password) {
                $self->api_useragent->add_handler(
                    request_prepare => sub {
                        my $req = shift;
                        $req->headers->authorization_basic($self->api_username,
                            $self->api_password);
                    }
                );
            }
        }
    }
};

1;