Sentry.io JavaScript tunnel on Laravel route? - javascript

The issue:
Because of issues with the JavaScript code loading I am trying to integrate sentry with the tunnel option. This would prevent the blocking, if a user has an ad-blocker enabled.
https://docs.sentry.io/platforms/javascript/troubleshooting/#using-the-tunnel-option
Now they provide an example code for this tunnel in their documentation:
<?php
// Change $host appropriately if you run your own Sentry instance.
$host = "sentry.io";
// Set $known_project_ids to an array with your Sentry project IDs which you
// want to accept through this proxy.
$known_project_ids = array( );
$envelope = stream_get_contents(STDIN);
$pieces = explode("\n", $envelope, 2);
$header = json_decode($pieces[0], true);
if (isset($header["dsn"])) {
$dsn = parse_url($header["dsn"]);
$project_id = intval(trim($dsn["path"], "/"));
if (in_array($project_id, $known_project_ids)) {
$options = array(
'http' => array(
'header' => "Content-type: application/x-sentry-envelope\r\n",
'method' => 'POST',
'content' => $envelope
)
);
echo file_get_contents(
"https://$host/api/$project_id/envelope/",
false,
stream_context_create($options));
}
}
In the app.php, the layout file of my project, I am calling the JavaScript Sentry like this:
<script src="{{ asset('/assets/js/app.js') }}" crossorigin="anonymous"></script>
My question:
What I don't understand is how to integrate this into the web.php as a route. So it gets called everytime an JavaScript error occured.

You should be able to define a route like this:
Route::post('/sentry-tunnel', function (Request $request) {
// Change $host appropriately if you run your own Sentry instance.
$host = "sentry.io";
// Set $known_project_ids to an array with your Sentry project IDs which you
// want to accept through this proxy.
$known_project_ids = [];
$envelope = $request->getContent();
$pieces = explode("\n", $envelope, 2);
$header = json_decode($pieces[0], true);
if (isset($header['dsn'])) {
$dsn = parse_url($header['dsn']);
$project_id = intval(trim($dsn['path'], '/'));
if (in_array($project_id, $known_project_ids)) {
return Http::withBody($envelope, "application/x-sentry-envelope")
->post("https://$host/api/$project_id/envelope/");
}
}
});
And then call the URL '/sentry-tunnel' from your JavaScript. Don't forget to add your project ID and credentials if necessary.

Related

Can we post multiple photos in a single update using Facebook API with JS SDK

I am trying to get multiple images from the user and post it on the Facebook page using Facebook Graph API Javascript SDK. Currently, I am able to post a single image. I searched facebook documentation and got nothing except it may be possible through albums, batch requests, or adding an unpublished post and then publishing it. But I don't know about any of them exactly. Your help will be highly appreciated.
Following is the code used to publish a single image:
function postImage()
{
$uploadDirectory = "uploadedFiles/";
$filename = $_FILES["postImage"]["name"];
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$uniqueName = uniqid("UP-IMG-", true) . "." . $extension;
$destinationPath = $uploadDirectory . $uniqueName;
move_uploaded_file($_FILES["postImage"]["tmp_name"], $destinationPath);
$_GET['imageUrl'] = "https://www.salebazarmzd.com/" . $destinationPath;
//creating variables to store data from Super Global Vars
$url = $_GET['imageUrl'];
$message = $_POST['postDescription'];
$link = $_POST['postLink'];
$message = $message . "\n" . $link;
$page_access_token = $_GET['page_access_token'];
$page_id = $_GET['page_id'];
echo $url;
echo $message;
$script = <<< JS
$(function() {
var form = document.querySelector('#form');
const data = Object.fromEntries(new FormData(form).entries());
console.log(data['postImage']);
var formData = {
"message": `$message`,
"url": "$url",
'access_token': "$page_access_token"
}
console.log(formData);
FB.api(
'/$page_id/photos',
'POST',
formData,
function(response) {
console.log(response);
}
)
});
JS;
return $script;
}
I have used PHP to get the file and store it on the server and then sent the request using FB.api() which is available through Facebook Graph API JavaScript SDK.

XML Parsing Error: no root element found

I am trying to search for all properties in a database that are in one suburb. I have read that it has something to do with the HTML code 204 but I still do not undertand what to do or what it really means. I have not done any JS or PHP in a while so this may be a really silly error but I cannot for the life of me figure it out. Please Help!
Here is my JS code:
function basicSearch(){
//Connect Script to the PHP
var urlLink = "basicSearch.php";
//Get search parameters:
var searchAreaBar = document.getElementById("searchAreaBar").value;
//define the parameters to send to php
var strParameters = "searchAreaBar="+searchAreaBar + "&sid=" + Math.random();
// define the options for the AJAX request
var objOptions = {
// use method post
method: "post",
// use strParameters as the parameters
parameters: strParameters,
// if successfil call fuction(objXHR)
onSuccess: function(objXHR) {
// if objXHR. responseText = yes
if(objXHR.responseText=='Yes'){
alert("Success!");
}
else{
alert("Error! No Properties Found!");
}
}
}
// define the AJAX request object
var objRequest = new Ajax.Request(urlLink,objOptions);
}
Here is my PHP code:
<?php
//Link the username and password:
$connect = mysqli_connect("localhost", "admin", "12345", "realestate") or die ('Connection to database failed: ' . mysql_error());
//Extract variables for request parameters:
extract($_REQUEST);
//Define the query:
$BasicSearch = "SELECT * FROM properties WHERE Suberb='$searchAreaBar'";
//Run the query:
$resDasicSearch = mysqli_query($BasicSearch) or die(mysql_error());
//SET intCount to number of rows in result:
$intCount = mysqli_num_rows($resDasicSearch);
//If intCount is greater than 0:
if($intCount > 0){
//Echo Yes:
echo "Yes";
}
else{
//Echo no:
echo "No";
}
?>
Thanks in advance.
The error was that the browser's compiler was "commenting out" all the php and adding empty HTML tags. It was then getting confused as there was an "empty" document.
This was because the website (including JS, PHP and HTML files) were being stored and run from a local directory. For example:
the URL read:
file:///C:/xampp/htdocs/"Project Name"/Index.html
the correct URL is:
localhost/"Project Name"
IF you are using XAMPP, the folder containing all your project files need to be placed in the htdocs folder in the xampp directory.
As you seem to be using an Ajax function that is not shown it is hard to determine the root cause of the problem because nothing above, as far as I can tell, would yield the error you allude to in the title of the posting - namely "XML Parsing Error: no root element found" - I wonder therefore if there should be a configuration option in Ajax.Request that needs to be set to deal with a basic string response?
That aside you might be able to make use of the following - perhaps even for diagnosis purposes.
<?php
/*
---------------
basicSearch.php
---------------
*/
$dbhost = 'localhost';
$dbuser = 'admin';
$dbpwd = '12345';
$dbname = 'realestate';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$sql='select * from `properties` where `suberb`=?';
$stmt=$db->prepare( $sql );
if( $stmt ){
$searcharea = $_POST['searchAreaBar'];
$stmt->bind_param( 's', $searcharea );
$stmt->execute();
$stmt->store_result();
$stmt->bind_result( $suberbs );
$stmt->fetch();
echo $stmt->num_rows()==0 ? "No" : "Yes";
}
$stmt->close();
$db->close();
?>
<script>
/* reuseable utility ajax function */
function ajax( method, url, params, callback, options ){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 )callback.call( this, xhr.response, options, xhr.getAllResponseHeaders() );
};
var async=params.hasOwnProperty('async') ? params.async : true;
var query=[];
for( var n in params )query.push(n+'='+params[n]);
switch( method.toLowerCase() ){
case 'post': query=query.join('&'); break;
case 'get': url+='?'+query.join('&'); params=null; break;
}
xhr.open( method.toUpperCase(), url, async );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( params );
}
/* function that does the search */
function function basicSearch(){
/* configure the parameters to be used in the ajax request */
var method='post';
var url='basicSearch.php';
var params={
searchAreaBar:document.getElementById('searchAreaBar').value,
sid:Math.random()
};
var callback=function(r,o,h){
alert( r ? 'Success' : 'Error! No Properties Found!' )
}
var options={};
/* call the ajax function */
ajax.call(this,method, url, params, callback, options);
}
</script>
Today I meet this error in Firefox's console, that is so simple, while all my API return JSON, one of my API return text/html and it causes Firefox show up that error!
I have changed my NodeJS Express code:
res.end('');
To
res.json({});
ANd it is okay now! Hope it can help someone!

Is it possible to access the Prestashop's Web service by client (customer) login instead the key?

I'm studying Prestashop's development. And I trying to create a "third part" side application with react.js (React Native for more precision) and catch Json data in the prestashop's webservice. But I want to let the "customer" make login with his own account and only his account. With CRUD also.
in advance; Very thank you for your patience and attention.
Best Regards.
Michel Diz
Prestashop backoffice login give no access to webservices. Webservices must be enabled and a key generated. So, I recommend you that change your "login" way. Customers accounts are not related with webservices and webservices are only used to access stored data un Prestashop (more like Backoffice than Frontoffice).
What exactly do you need to do?
I hope it helps you.
I don't know if you're still searching for a solution but there is a way actually.
DO MAKE SURE IT IS A SECURE LOGIN.
Since you're giving access to all prestashop data do make sure the login is very secure. I've been able to recreate it with PHP I think that with some additions you're able to recreate it the way you want it. See it as a guideline.
To create a login system by using the prestashop webservice you'll need three things
Access through webservice to the customers table
The COOKIE_KEY, defined in app/config -> parameters.php:: 'cookie_key' => '12321test';
Some expierence with PHP
The first thing is to get the customers table from the webservice.
// code placeholder
require_once('./../PSWebServiceLibrary.php');
/**
* get information from PrestaShop
*/
$webService = new PrestaShopWebservice($url, $key, $debug);
$COOKIE_KEY = 'CookieKey';
$email = $_REQUEST['email'];
$password = $_REQUEST['password'];
$optUser = array(
'resource' => 'customers',
'filter[email]' => '[' . $email . ']',
'display' => '[id,email,lastname,firstname,passwd]'
);
$resultUser = ($webService->get($optUser));
$json = json_encode($resultUser);
The second and most important thing is to Check the user input
// code placeholder
foreach ($resultUser->customers->customer as $info) {
// Prestashop uses the cookie_key in combination with a salt key. To check the password use the php function: password_verify();
$salt = substr($info->passwd, strrpos($info->passwd, ':') + 1, 2);
$ZCpassword = md5($COOKIE_KEY . $password) . ':' . $salt;
// Check if password comparison is true or false
if (password_verify($password, $info->passwd) == true) {
session_start();
$response = array();
$response['status'] = 'succes';
$response['message'] = "You did it!";
setcookie("userId", $info->id);
header('Content-type: application/json');
echo json_encode($response);
} else {
$response = array();
$response['status'] = 'error';
$response['message'] = 'Wrong password';
header('Content-type: application/json');
echo json_encode($response);
}
}
This is how to reproduce the issue to a working example.
Hope this helps!
For those who are still searching for this answer,
<?
if (isset($_GET["email"]) && isset($_GET["password"]) )
{
$email = $_GET["email"];
$password = $_GET["password"];
$COOKIE_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$jsonurl = "https://XXXXXXXXXXXXXXXXXXXX#example.com/api/customers?filter[email]=".$email."&display=[passwd]&output_format=JSON";
$json = file_get_contents($jsonurl);
$json_a = json_decode($json, true);
$loopone = $json_a['customers'];
$looptwo = $loopone[0];
$loopthree = $looptwo['passwd'];
$ZCpassword = md5($COOKIE_KEY . $password);
if (strcmp($loopthree, $ZCpassword) == 0) {
echo "sucess";
} else {
echo "fail";
}
}
else
{
echo "Send something with url dude";
}
?>

Ajax success function isn't called with require instruction

I have really weird problem with AJAX.
This is fragment of file with js code and post method which sends params to php file via AJAX:
var params = $('#add').serializeArray();
$.post('code/bg/adding_c.php', params, function(ret) {
//body of success function
}, 'json');
And this is fragment of php code (adding_c.php):
<?php
require "functions.php";
//irrelevant operations
$return = array(
'status' => $status,
'msg' => $msg,
'id' => $id
);
echo json_encode($return);
?>
Everything works when I comment or delete the line with require instruction but when it's active, success function isn't fired.
JS post method sends correct params.
Php file receives it, does proper operations and returns correct data to js script (I can see it in FireBug).
Success function isn't fired.
Why instruction which isn't related with AJAX, causes this problem?
Edit.
functions.php:
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'dbname';
$conn = new mysqli($host, $user, $pass, $db);
function querySQL($query)
{
global $conn;
$result = $conn->query($query);
return $result;
}
function cleanSQL($conn, $string)
{
return htmlentities(fixSQL($conn, $string), ENT_COMPAT, 'UTF-8');
}
function fixSQL($conn, $string)
{
if(get_magic_quotes_gpc())
$string = stripslashes($string);
return $conn->real_escape_string($string);
}
function fPassword($pass)
{
$salt1 = 'salt1';
$salt2 = 'salt2';
$token = hash('ripemd128', "$salt1$pass$salt2");
return $token;
}
?>
Edit2.
There is no errors and when I paste functions from functions.php to index.php everything works fine. I don't know what to do now. It seems that require word is a problem here. I can't add these functions to every file in which I need them.
It is probably an error within functions.php.
EDIT: If you haven't set display_errors = On in your php.ini file, use these lines in your code:
ini_set("display_errors", "1");
error_reporting(E_ALL);
Also, are you sure it is not a parsing/syntax error? If that is the case, there's a few things you will want to do:
Make sure you are using an IDE that checks syntax (Netbeans, for example).
Separate the file into two, like so:
index.php
<?php
ini_set("display_errors", "1");
error_reporting(E_ALL);
include 'error.php';
error.php
require "functions.php";
//irrelevant operations
$return = array(
'status' => $status,
'msg' => $msg,
'id' => $id
);
echo json_encode($return);
Run this in a browser window and that should give you an idea of what you are dealing with.

Facebook App Issue - Can not obtain Permissions , Keeps on refreshing

I found this Love Calculator app online , It is open source and free to use, I setted it up on my test server, I added all the app Id's and secrets and did all the setting but I am getting this permissions issue when I or Someone else try to use it , There are 3 Important files in this script,
Config.php (i setted it up , it has only 4 fields for the app id,secret,canvas url,app domain)
Index.php
Facebook.php (this is the sdk I figure)
Config.php is loaded in Index.php with the following code
include_once ('lib/facebook.php'); // Facebook client library
include_once ('config.php'); // Config file
// Constants are located in config.php file
$facebook = new Facebook(
array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET_KEY,
'cookie' => true,
'domain' => FACEBOOK_DOMAIN
)
);
Now , When I tried to figure out the problem , I found this code in index.php for obtaining permissions
$session = $facebook->getSession();
if (!$session) {
$url = $facebook->getLoginUrl(array(
'canvas' => 1,
'fbconnect' => 0,
'scope' => 'publish_stream'
));
echo "<script type='text/javascript'>top.location.href = '$url';</script>";
} else {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
$updated = date("l, F j, Y", strtotime($me['updated_time']));
} catch (FacebookApiException $e) {
echo "<script type='text/javascript'>top.location.href = '$url';</script>";
exit;
}
}
The canvas app url is https://apps.facebook.com/fb-love-calculator-f
The domain url is https://apps.mjobz.com/love/
You are using and out dated version of facebook sdk, Facebook sdk has updated a couple of times after this one

Categories

Resources