Search code examples
perlmojolicious

handling route permissions in mojolicious


I'm working with different types of users(admin, regular, guest) and would like to give each type of user permission to access different routes in a mojolicious app. My thought is to build a permission table for each user type to be able to access different routes (either by path or more likely by action name).

I was thinking of handling this on a more global level with a around_dispatch hook and query a database for a lookup on which actions (subroutines) can be accessed for which user type.

This would look a bit like:

$self->hook( around_dispatch => sub ($next,$c) {

    if (logged in user has permissions) {
        $next->();
    } else {
       $c->redirect_to('/permission_error');
    } 
});

where I'm looking to determine the action that is called for a given route. Is there a way to drill down in a Mojolicious::Controller object within this hook to do this?


Solution

  • The following pulls all of the information I need:

    $self->hook(
            around_action => sub {
                my ($next, $c, $action, $last) = @_;
                if (has_permssion($c->current_user,$c->{stash}->{action})) {
                    return $next->();
                } else {
                    $c->redirect_to('/permission_error');
                }
            }
        );
    

    where I am using the Mojolicious::Plugin::Authentication to handle authentication and users and the has_permission subroutine checks if the supplied user has permission to access the requested route/action.