mymarkjeff

Password Download

Jun 12th, 2022 (edited)
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. // function.php
  2.  
  3. function custom_api_get_document_callback($request){
  4. $posts_data = array();
  5. $key = $request->get_param('key');
  6. $id = $request->get_param('id');
  7.  
  8.  
  9. $posts = get_posts( array(
  10. 'post_type' => 'documents',
  11. 'status' => 'published',
  12. 'p' => $id
  13. ));
  14.  
  15. foreach($posts as $post){
  16. $id = $post->ID;
  17. $pkey = get_field("password", $id);
  18. $file = get_field("documents_upload", $id);
  19. $filename = $file['filename'];
  20.  
  21. if($pkey == $key){
  22. $posts_data[] = (object)array(
  23. 'message' => 'Success',
  24. 'file' => $file,
  25. 'name' => $filename
  26. );
  27.  
  28. }else{
  29. $posts_data[] = (object)array(
  30. 'message' => 'Failed',
  31. 'file' => ''
  32. );
  33. }
  34.  
  35. }
  36. return $posts_data;
  37. }
  38.  
  39. //JS
  40. $('.verify-key').on('click',function(event){
  41.  
  42. event.preventDefault();
  43.  
  44. let $site = 'https:...';
  45.  
  46. let $key = $('.docu-key').val();
  47. let $id = $(this).attr('data-id');
  48.  
  49. $.getJSON($site+"wp-json/documents/document?page=1&id="+$id+"&key="+$key, function(data){
  50. if(data.length){
  51.  
  52. let items = [];
  53. let $message, $file, $alert, $filename;
  54.  
  55. $.each(data, function(key, val){
  56. const arr = $.map(val, function(el) { return el });
  57. $message = arr[0];
  58. $file = arr[1];
  59. $filename = arr[2];
  60. });
  61. if($message == "Success"){
  62. $alert = "Password correct";
  63. //$('.download-file-here').html('<a href="'+$file+'" download>Download Now</a>');
  64. fetch($file)
  65. .then(resp => resp.blob())
  66. .then(blob => {
  67. const url = window.URL.createObjectURL(blob);
  68. const a = document.createElement('a');
  69. a.style.display = 'none';
  70. a.href = url;
  71. // the filename you want
  72. a.download = $filename;
  73. document.body.appendChild(a);
  74. a.click();
  75. window.URL.revokeObjectURL(url);
  76. alert('Your file has downloaded!'); // or you know, something with better UX...
  77. })
  78. .catch(() => alert('Try again'));
  79. }else{
  80. $alert = "Password Incorrect";
  81. }
  82. $('.message-docu').html($alert);
  83. }
  84. });
  85. });
  86.  
Add Comment
Please, Sign In to add comment