CallBackery

 view release on metacpan or  search on metacpan

lib/CallBackery/Controller/RpcService.pm  view on Meta::CPAN

=head2 allow_rpc_access(method)

Decide whether the current request may invoke C<$method>. Returns C<1> when
access is granted and C<0> when it is refused (the dispatcher turns a C<0> into a
code 6 "access denied" reply, which the frontend maps to the login dialog). When
access is refused specifically because a previously valid session has expired,
this instead C<die>s a code 7 (C<RPC_SESSION_EXPIRED>) exception so the frontend
can prompt a reload rather than a fresh login.

The rules are evaluated in order:

=over

=item *

Non-C<POST> requests are refused (C<return 0>).

=item *

Methods not listed in C<%allow> are refused (C<return 0>).

=item *

Public methods (C<%allow> level C<1>) are always allowed.

=item *

Any authenticated user is allowed. Reading C<isUserAuthenticated> forces the
session cookie to be evaluated, which is also what sets C<sessionExpired> on the
user object.

=item *

Level C<3> methods are additionally allowed for an unauthenticated user when the
target plugin opts into anonymous access (C<mayAnonymous>). The plugin
instantiation is wrapped in C<eval>, because instantiating a plugin as an
unauthenticated user commonly dies (plugins read user rights/config); such a
death resolves to "not anonymous" here and must never escape as a generic
code 9999 error.

=item *

Otherwise the method requires authentication the user does not have: if the
user's session has merely expired, C<die> a C<RPC_SESSION_EXPIRED> (code 7)
exception; otherwise C<return 0> for the ordinary login-required path.

=back

=cut

my %allow = (
    getBaseConfig => 1,
    login => 1,
    logout => 1,
    ping => 1,
    getUserConfig => 2,
    getPluginConfig => 3,
    validatePluginData => 3,
    processPluginData => 3,
    getPluginData => 3,
    getSessionCookie => 2
);

has config => sub ($self) {
    $self->app->config;
}, weak => 1;

has user => sub ($self) {
    my $obj = $self->app->userObject->new(app=>$self->app,controller=>$self,log=>$self->log);
    return $obj;
};

has pluginMap => sub ($self) {
    my $map = $self->config->cfgHash->{PLUGIN};
    return $map;
}, weak => 1;


sub allow_rpc_access ($self,$method) {
    if (not $self->req->method eq 'POST') {
        # sorry we do not allow GET requests
        $self->log->error("refused ".$self->req->method." request");
        return 0;
    }
    if (not exists $allow{$method}){
        return 0;
    }
    for ($allow{$method}){
        /1/ && return 1;                                 # public method
        return 1 if ($self->user->isUserAuthenticated); # forces cookieConf (sets sessionExpired)
        /3/ && do {
            # Level-3: allowed only for plugins that opt into anonymous access.
            # Guard the instantiation: for an unauthenticated user it commonly
            # dies (plugins read user rights/config); that death must resolve to
            # "not anonymous" here, never escape as a generic code-9999 popup.
            my $plugin = $self->rpcParams->[0];
            my $anon = eval {
                $self->config->instantiatePlugin($plugin,$self->user)->mayAnonymous
            };
            return 1 if $anon;
        };
        # Method needs auth and the user is not authenticated. If a session was
        # present and merely expired, signal that distinctly (code 7 -> reload);
        # otherwise fall through to code 6 (login dialog).
        die mkerror(RPC_SESSION_EXPIRED,
            trm('Your session has expired. Please reload to log in.'))
            if $self->user->sessionExpired;
        last;
    }
    return 0;
};

has passMatch => sub ($self) {
    qr{(?i)(?:password|_pass)};
};

sub perMethodCleaner ($self,$method=undef) {
    $method or return;
    return {
        login => sub {
            my $data = shift;

lib/CallBackery/Controller/RpcService.pm  view on Meta::CPAN

}

=head2 logRpcCall

Set CALLBACKERY_RPC_LOG for extensive logging messages. Note that all
values with keys matching /password|_pass/ do get replaced with 'xxx'
in the output.

=cut

# our own logging
sub logRpcCall {
    my $self = shift;
    if ($ENV{CALLBACKERY_RPC_LOG}){
        my $method = shift;
        my $data = shift;
        $self->dataCleaner($data,$method);
        my $userId = eval { $self->user->loginName } // '*UNKNOWN*';
        my $remoteAddr = $self->tx->remote_address;
        $self->log->debug("[$userId|$remoteAddr] CALL $method(".encode_json($data).")");
    }
    else {
        $self->SUPER::logRpcCall(@_);
    }
}

=head2 logRpcReturn

Set CALLBACKERY_RPC_LOG for extensive logging messages. Note that all
values with keys matching /password|_pass/ do get replaced with 'xxx'
in the output.

=cut

# our own logging
sub logRpcReturn {
    my $self = shift;
    if ($ENV{CALLBACKERY_RPC_LOG}){
        my $data = shift;
        $self->dataCleaner($data);
        my $userId = eval { $self->user->loginName } // '*UNKNOWN*';
        my $remoteAddr = $self->tx->remote_address;
        $self->log->debug("[$userId|$remoteAddr] RETURN ".encode_json($data).")");
    }
    else {
        $self->SUPER::logRpcReturn(@_);
    }

}

=head2 ping()

check if the server is happy with our authentication state

=cut

sub ping {
    return 'pong';
}

=head2 getSessionCookie()

Return a timeestamped session cookie. For use in the X-Session-Cookie header or as a xsc field
in form submissions. Note that session cookies for form submissions are only valid for 2 seconds.
So you have to get a fresh one from the server before submitting your form.

=cut

sub getSessionCookie {
    shift->user->makeSessionCookie();
}

=head2 getConfig()

get some gloabal configuration information into the interface

=cut

sub getBaseConfig {
    my $self = shift;
    return $self->config->cfgHash->{FRONTEND};
}

=head2 login(user,password)

Check login and provide the user specific interface configuration as a response.

=cut

async sub login { ## no critic (RequireArgUnpacking)
    my $self = shift;
    my $login = shift;
    my $password = shift;
    my $cfg = $self->config->cfgHash->{BACKEND};
    if (my $ok =
        await $self->config->promisify($self->user->login($login,$password))){
        return {
            sessionCookie => $self->user->makeSessionCookie()
        }
    } else {
        return;
    }
}

=head2 logout

Kill the session.

=cut

sub logout {
    my $self = shift;
    $self->session(expires=>1);
    return 'http://youtu.be/KGsTNugVctI';
}



=head2 instantiatePlugin_p

get an instance for the given plugin

=cut

async sub instantiatePlugin_p {
    my $self = shift;
    my $name = shift;
    my $args = shift;
    my $user = $self->user;
    my $plugin =  await $self->config->instantiatePlugin_p($name,$user,$args);
    $plugin->log($self->log);
    return $plugin;
}

sub instantiatePlugin {
    my $self = shift;
    my $name = shift;
    my $args = shift;
    my $user = $self->user;
    my $plugin =  $self->config->instantiatePlugin($name,$user,$args);
    $plugin->log($self->log);
    return $plugin;
}

=head2 processPluginData(plugin,args)

handle form sumissions

=cut

async sub processPluginData {
    my $self = shift;
    my $plugin = shift;
    # "Localizing" required as it seems to be changed somewhere.
    my @args = @_;
    # Creating two statements will make things easier to debug since
    # there is only one thing that can go wrong per line.
    my $instance = await $self->instantiatePlugin_p($plugin);



( run in 0.948 second using v1.01-cache-2.11-cpan-1191d43216d )