| 1 | # ABSTRACT: Dancer::Plugin::Auth::RBAC authentication via PostgreSQL! | ||
| 2 | |||
| 3 | package Dancer::Plugin::Auth::RBAC::Credentials::PostgreSQL; | ||
| 4 | BEGIN { | ||
| 5 | $Dancer::Plugin::Auth::RBAC::Credentials::PostgreSQL::VERSION = '1.110720'; | ||
| 6 | } | ||
| 7 | |||
| 8 | use strict; | ||
| 9 | use warnings; | ||
| 10 | use base qw/Dancer::Plugin::Auth::RBAC::Credentials/; | ||
| 11 | use Dancer::Plugin::Database; | ||
| 12 | |||
| 13 | |||
| 14 | sub authorize { | ||
| 15 | |||
| 16 | my ($self, $options, @arguments) = @_; | ||
| 17 | my ($login, $password) = @arguments; | ||
| 18 | |||
| 19 | my $settings = $Dancer::Plugin::Auth::RBAC::settings; | ||
| 20 | |||
| 21 | if ($login) { | ||
| 22 | |||
| 23 | # authorize a new account using supplied credentials | ||
| 24 | |||
| 25 | unless ($password) { | ||
| 26 | $self->errors('login and password are required'); | ||
| 27 | return 0; | ||
| 28 | } | ||
| 29 | |||
| 30 | my $sth = database($options->{handle})->prepare( | ||
| 31 | 'SELECT * FROM users WHERE login = ? AND password = ?', | ||
| 32 | ); $sth->execute($login, $password) if $sth; | ||
| 33 | |||
| 34 | my $accounts = $sth->fetchrow_hashref; | ||
| 35 | |||
| 36 | if (defined $accounts) { | ||
| 37 | |||
| 38 | my $session_data = { | ||
| 39 | id => $accounts->{id}, | ||
| 40 | name => $accounts->{name}, | ||
| 41 | login => $accounts->{login}, | ||
| 42 | roles => [ | ||
| 43 | map { $_ =~ s/^\s+|\s+$//; $_ } | ||
| 44 | split /\,/, $accounts->{roles} | ||
| 45 | ], | ||
| 46 | error => [] | ||
| 47 | }; | ||
| 48 | return $self->credentials($session_data); | ||
| 49 | |||
| 50 | } | ||
| 51 | else { | ||
| 52 | $self->errors('login and/or password is invalid'); | ||
| 53 | return 0; | ||
| 54 | } | ||
| 55 | |||
| 56 | } | ||
| 57 | else { | ||
| 58 | |||
| 59 | # check if current user session is authorized | ||
| 60 | |||
| 61 | my $user = $self->credentials; | ||
| 62 | if (($user->{id} || $user->{login}) && !@{$user->{error}}) { | ||
| 63 | |||
| 64 | return $user; | ||
| 65 | |||
| 66 | } | ||
| 67 | else { | ||
| 68 | $self->errors('you are not authorized', 'your session may have ended'); | ||
| 69 | return 0; | ||
| 70 | } | ||
| 71 | |||
| 72 | } | ||
| 73 | |||
| 74 | } | ||
| 75 | |||
| 76 | 1; | ||
| 77 | |||
| 78 | __END__ |