Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attach middleware to specific existing route

Tags:

php

wordpress

Is there a way to attach middleware to a specific route in Wordpress or just in PHP? I'd like to run a middleware function before allowing access to the uploads folder to check if the user has access to the file before allowing them to download it.

I come from a background in node.js/express so if it helps I'd like to do something like this:

app.use('/wp-content/uploads', function(req, res, next) {
    // do stuff with req and call next to continue,
    // or use res to end the request early. 
});
like image 912
chrispytoes Avatar asked Oct 30 '22 04:10

chrispytoes


1 Answers

There are various WordPress plugins for restricting access to content or downloads, mostly based on the logic of been registered or not and what privileges that user has.

Basic logic behind them is like this :

// Redirect guests
function guest_redirect() {
    $guest_routes = array(
        'member-login', 
        'member-account', 
        'member-register', 
        'member-password-lost', 
        'member-password-reset'
    );
    // Force login or registration
    if ( !is_user_logged_in() && !is_page($guest_routes) ) {
      wp_redirect( 'member-login' ); 
      exit;
    }
}
add_action( 'template_redirect', 'guest_redirect' );

Also, WordPress has REST API (official doc here for your need). However, using own custom thing for production site using REST API without properly testing can be risky and complicated to use.

like image 58
hackershake Avatar answered Nov 11 '22 16:11

hackershake