Attach middleware to a specific existing route

Is there a way to bind middleware to a specific route in Wordpress or just in PHP? I would like to run the 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 came from the background in node.js / express, so if this helps, I would 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. }); 
+5
source share
2 answers

There are various WordPress plugins to restrict access to content or downloads, mainly based on the logic of the registered or not, and what privileges the user has.

The basic logic behind them is 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' ); 

WordPress also has a REST API ( white paper here for your needs ). However, using your own custom stuff for a production site using the REST API without proper testing can be risky and difficult to use.

+2
source

From what I get from your use case from your description, you can solve your problem using only one of the already available Wordpress plugins, for example, you can use the “downnload manager” to handle upload and download content: https: // wordpress .org / support / plugin / download-manager or use something like https://wordpress.org/plugins/easy-digital-downloads/

Here you can find more plugins https://wordpress.org/plugins/

If you really want to write something custom, you can add a RewriteRule to send all the requests for the uploads folder through the "protect.php" script, adding something like this to the .htaccess file

 RewriteCond %{REQUEST_FILENAME} -s RewriteRule ^wp-content/uploads/(.*)$ protect.php?filename=$1 [L,QSA] 

In the protect.php script file, you can implement custom logic to allow / deny access to a specific "file name"

To use the WP functions inside the user protect.php file, you must include wp-load.php, more or less as follows:

 require_once(rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/wp-load.php'); 
0
source

Source: https://habr.com/ru/post/1270332/


All Articles