| 1 | # | ||
| 2 | # (c) Jan Gehring <jan.gehring@gmail.com> | ||
| 3 | # | ||
| 4 | # vim: set ts=3 sw=3 tw=0: | ||
| 5 | # vim: set expandtab: | ||
| 6 | |||
| 7 | package Rex::Endpoint::HTTP::Mojolicious::Plugin::Auth; | ||
| 8 | |||
| 9 | |||
| 10 | # | ||
| 11 | # HTTP Header | ||
| 12 | # | ||
| 13 | # Apache: | ||
| 14 | # X-Forwarded-For -> $IP/$NAME | ||
| 15 | |||
| 16 | use strict; | ||
| 17 | use warnings; | ||
| 18 | |||
| 19 | use base qw(Mojolicious::Plugin); | ||
| 20 | use Digest::SHA qw(sha1_hex); | ||
| 21 | use MIME::Base64; | ||
| 22 | |||
| 23 | sub register { | ||
| 24 | my ($plugin, $app) = @_; | ||
| 25 | |||
| 26 | $app->routes->add_condition(authenticated => sub { | ||
| 27 | my ($r, $mojo) = @_; | ||
| 28 | if(! $mojo->is_auth) { | ||
| 29 | return $mojo->auth; | ||
| 30 | } | ||
| 31 | |||
| 32 | return 1; | ||
| 33 | }); | ||
| 34 | |||
| 35 | $app->helper(is_auth => sub { | ||
| 36 | my ($mojo) = @_; | ||
| 37 | my ($auth_type, $auth_header) = split(/ /, $mojo->req->headers->authorization || ""); | ||
| 38 | |||
| 39 | return $mojo->auth unless $auth_type; | ||
| 40 | |||
| 41 | if($auth_type && lc($auth_type) ne "basic") { | ||
| 42 | return $mojo->auth; | ||
| 43 | } | ||
| 44 | |||
| 45 | my ($user, $pass) = split(/:/, decode_base64($auth_header)); | ||
| 46 | |||
| 47 | if($mojo->auth($user, $pass)) { | ||
| 48 | return 1; | ||
| 49 | } | ||
| 50 | return 0; | ||
| 51 | }); | ||
| 52 | |||
| 53 | $app->helper(auth => sub { | ||
| 54 | my ($mojo, $user, $pass) = @_; | ||
| 55 | if($user && $pass) { | ||
| 56 | # do the auth | ||
| 57 | my $file = $mojo->stash('config')->{user_file}; | ||
| 58 | |||
| 59 | my ($f_user, $f_pw) = split( /:/, [ grep { /^$user:/ } eval { local(@ARGV) = ($file); <>; } ]->[0] || "" ); | ||
| 60 | |||
| 61 | if($f_user) { | ||
| 62 | chomp $f_pw; | ||
| 63 | |||
| 64 | $pass = sha1_hex($pass); | ||
| 65 | if($user eq $f_user && $pass eq $f_pw) { | ||
| 66 | return 1; | ||
| 67 | } | ||
| 68 | } | ||
| 69 | } | ||
| 70 | |||
| 71 | $mojo->res->headers->www_authenticate("Basic realm=\"Rex::Endpoint::HTTP\""); | ||
| 72 | $mojo->res->code(401); | ||
| 73 | $mojo->rendered; | ||
| 74 | |||
| 75 | return; | ||
| 76 | }); | ||
| 77 | |||
| 78 | $app->plugins->on(before_dispatch => sub { | ||
| 79 | my ($self, $mojo) = @_; | ||
| 80 | return $self->is_auth; | ||
| 81 | }); | ||
| 82 | } | ||
| 83 | |||
| 84 | 1; |