package Plack::Middleware::ApiKey;

use strict;
use warnings;
use Plack::Request;
use AnyEvent::HTTP;
use URI::Escape;
use parent qw(Plack::Middleware);
use Plack::Util::Accessor qw(apikeys);

sub call {
    my ($self, $env) = @_;

    my $req = Plack::Request->new($env);
    my $auth = $req->header('Authorization');

    if (defined $auth && $auth =~ /^Bearer (.*)$/) {
        foreach (@{$self->apikeys}) {
            if ($_ eq $1) {
                my $res = $self->app->($env);
                return $res;
            }
        }
        return [300, ['Content-type', 'text/plain'], ['bad API key']];
    }

    return [300, ['Content-type', 'text/plain'], ['Need API key']];
}

1;

