perlmojolicious

How to render a custom template for 403 page


I have a function that checks whether the current user is authorized to access the URL. I attach it to the router via add_condition:

use Mojolicious::Lite;

# Adding a custom condition
app->routes->add_condition(auth => sub {
    my ($route, $c, $captures, $num) = @_;

    $c->res->code(403);
    $c->rendered(403);
    # Here, you could define your condition. For example, check if a parameter is set.
    return 0;  # true/false depending on parameter
});

my $r = app->routes;
$r->get('/block')->requires(auth => 1)->to(cb => sub {
  my $c = shift;
  $c->render(template => 'default');
});

# Route for home
get '/' => sub {
    my $c = shift;
    $c->render(template => 'main');
};

# Default template
app->start;

__DATA__

@@ 403.html.ep
<!DOCTYPE html>
<html>
<head><title>Default Template</title></head>
<body>
<h1>Welcome to the Default Template</h1>
<p>This is the default template.</p>
</body>
</html>

@@ main.html.ep
<!DOCTYPE html>
<html>
<head><title>Main page</title></head>
<body>
<h1>Welcome to the main page</h1>
<p>The main page is here.</p>
</body>
</html>

What should I do to use a custom template for 403 page?


Solution

  • try this out! It renders a custom 403 page when access is denied.

    use Mojolicious::Lite;
    
    # Adding a custom condition
    app->routes->add_condition(auth => sub {
        my ($route, $c, $captures, $num) = @_;
    
        # Check for authorization
        if (0) { # Replace 0 with your actual authorization logic
            return 1; # Authorized
        }
    
        # Unauthorized - Render the custom forbidden page with 403 status
        $c->render(template => 'forbidden', status => 403);
        return 0; # Deny access
    });
    
    my $r = app->routes;
    $r->get('/block')->requires(auth => 1)->to(cb => sub {
        my $c = shift;
        $c->render(template => 'default');
    });
    
    # Route for home
    get '/' => sub {
        my $c = shift;
        $c->render(template => 'main');
    };
    
    # Start the application
    app->start;
    
    __DATA__
    
    @@ forbidden.html.ep
    <!DOCTYPE html>
    <html>
    <head><title>403 Forbidden</title></head>
    <body>
    <h1>403 Forbidden</h1>
    <p>You are not authorized to access this page.</p>
    </body>
    </html>
    
    @@ default.html.ep
    <!DOCTYPE html>
    <html>
    <head><title>Default Template</title></head>
    <body>
    <h1>Welcome to the Default Template</h1>
    <p>This is the default template.</p>
    </body>
    </html>
    
    @@ main.html.ep
    <!DOCTYPE html>
    <html>
    <head><title>Main page</title></head>
    <body>
    <h1>Welcome to the main page</h1>
    <p>The main page is here.</p>
    </body>
    </html>