Last active
June 9, 2022 10:12
-
-
Save skyshab/f0650eaef7a089a53bbdf0d6f676e7b3 to your computer and use it in GitHub Desktop.
Protected download REST endpoint
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_action( 'rest_api_init', function() { | |
register_rest_route( 'protected-url/v1', '/rcp/addon/(?P<slug>.+)', [ | |
'methods' => 'GET', | |
'callback' => 'rcp_protected_url', | |
'permission_callback' => '__return_true', // We will do the permission checking in the rcp_protected_url function so we can redirect. | |
] ); | |
} ); | |
function rcp_protected_url( $data ) { | |
// @WORKNEEDED If user is not authenticated, redirect the user to the login page for the site. | |
$user = wp_get_current_user(); | |
if ( 0 === $user->ID ) { | |
wp_safe_redirect( '/my-account' ); | |
exit; | |
} | |
// @WORKNEEDED If the user does not have an active subscription, redirect to the rcp pricing page. | |
if ( ! wcs_user_has_subscription( $user->ID ) ) { | |
wp_safe_redirect( '/' ); | |
exit; | |
} | |
header( 'Cache-Control: no-store, no-cache, must-revalidate, max-age=0' ); | |
header( 'Cache-Control: post-check=0, pre-check=0', false ); | |
header( 'Pragma: no-cache' ); | |
// @WORKNEEDED download file from public URL into tmp. | |
// * assign the path to file into a variable called $file_and_path | |
// * assign the file name into a variable called $file | |
// Get path to uploads directory | |
$upload_dir = wp_get_upload_dir(); | |
// Define expected filename | |
$file = "{$data->get_param('slug')}.zip"; | |
// Define full path to file | |
$file_and_path = sprintf('%s/addons/%s', $upload_dir['basedir'], $file ); | |
// Create a temp file | |
$tempfile = tempnam( sys_get_temp_dir(), 'addon' ) . '.zip'; | |
// Copy original file to temp | |
file_put_contents( $tempfile, file_get_contents( $file_and_path ) ); | |
header( 'Content-Description: File Transfer' ); | |
header( 'Content-type: application/octet-stream' ); | |
header( 'Content-Disposition: attachment; filename=' . $file ); | |
header( 'Content-Transfer-Encoding: binary' ); | |
header( 'Content-Length: ' . filesize( $tempfile ) ); | |
ob_end_flush(); | |
@readfile( $tempfile ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment