Access AWS Support Service using ajax - ajax

I'm trying to create a case using "create case" option using the AWS support service. I have a web application from which i want to create AWS support tickets. They only hurdle that is standing in my way is CORS (no surprises there :p) my question is, is there a way that i can create AWS support tickets (create case) by sending an ajax request to the end point? if yes, then how?
Do I need to enable the CORS support at the AWS end? how can i enable it?
what i have tried so far
$(function(){
$.getScript( "https://cdnjs.cloudflare.com/ajax/libs/aws-sdk/2.41.0/aws-sdk.js", function( data, textStatus, jqxhr ) {
console.log( data ); // Data returned
console.log( textStatus ); // Success
console.log( jqxhr.status ); // 200
console.log( "Load was performed." );
alert('loaded');
var support = new AWS.Support(options = {
endpoint :'END_POINT',
accessKeyId :'SOME KEY',
secretAccessKey :'YET ANOTHER KEY'
});
var params = {
communicationBody: 'STRING_VALUE', /* required */
subject: 'STRING_VALUE', /* required */
attachmentSetId: 'STRING_VALUE',
categoryCode: 'STRING_VALUE',
ccEmailAddresses: [
'STRING_VALUE',
/* more items */
],
issueType: 'STRING_VALUE',
language: 'STRING_VALUE',
serviceCode: 'STRING_VALUE',
severityCode: 'STRING_VALUE'
};
support.createCase(params, function(err, data) {
if (err){ // an error occurred
alert('error occured');
console.log(err, err.stack);
}
else {
alert('success');
console.log(data); // successful response
}
});
});//loadScript Ends
});//document ready ends
Any help in this regard is much appreciated.
Regards.

I am working on this also. The issue is that you need to include the build file for aws.support from here: https://sdk.amazonaws.com/builder/js/
At this time, I am able to download the js with the createCase, but not able to link it to the same example that you are doing. If the js is posted out to a web server, I am thinking that you can change the first line of code to point to that js file, but that is what I am working on now.

Related

Ajax request on site in wp-admin directory on wordpress server returns 400 Bad request

Well Thank you in advance for taking the time to read through my question.
The situation is as follows:
I have a Wrodpress server with a singular site in the wp-admin/sites/contactform/index.php
From that site I want to make an Ajax call however I get a '/wp-admin/admin-ajax.php:1  Failed to load resource: the server responded with a status of 400 (Bad Request) ' error upon the initial loading of the site and a
' https://THECORRECTURL/wp-admin/admin-ajax.php 400 (Bad Request)' error when I execute the method.
My suspicion is that the errors are provoked by missing permissions to access the admin-ajax.php file.
I'd like to know what you think.
Here is the Code:
In a js file in the directory of 'contactform/dt/wb.js':
jQuery(document).ready(function($) {
$('#btn-x').click(function() {
$.ajax({
url: '../../admin-ajax.php', // The URL of the WordPress AJAX handler
type: 'POST', // The HTTP method of the request
data: { // The data to be sent with the request
action: 'usystorequest',
},
success: function(response) { // A function to be called if the request is successful
if (response) {$('#mail_sent').show(); //mail got sent
}
else { $('#mail_not_sent').show(); //mail didnt get sent
}
}
});
});
});
In the functions.php File in 'contactform':
add_action('wp_enqueue_scripts', function(){
wp_enqueue_script('wb', get_stylesheet_directory_uri() . '/dt/wb.js',['jquery'], '1.0', false);
wp_enqueue_script('jquery', get_stylesheet_directory_uri() . '/dt/jquery-3.4.1.min.js',[], '1.0', false);
});
//Function executed by ajax call
add_action("wp_ajax_usystorequest", "usystorequest");
add_action("wp_ajax_nopriv_usystorequest", "usystorequest");
function usystorequest(){
echo ':test:';
wp_die();
}
(I am not using a Contactform plugin because i am sending Information that gets calculated in js and the site is seperated from the usual structure with themes and plugins because of conflicts with the Plugins and Themes - its simply easier this way. A prior version of what I currently want to update already runs there just without ajax)
I added a nopriv ajax call so you dont need admin permissions (be logged in) to execute the ajax function.
The usystorequest function is kept as easy as possible to exclude the source of the error is the code.
I tried doing it over a custom ajax handler, here is the code. It got me the same error:
FUNCTIONS.PHP
// Step 1: Add a new endpoint in your functions.php file
add_action( 'init', 'add_my_endpoint' );
function add_my_endpoint() {
add_rewrite_endpoint( 'my-endpoint', EP_ROOT );
}
// Step 2: Add a function to handle the request
add_action( 'template_redirect', 'my_endpoint_handler' );
function my_endpoint_handler() {
global $wp_query;
if ( ! isset( $wp_query->query_vars['my-endpoint'] ) ) {
return;
}
// Handle the request
if ( $_SERVER['REQUEST_METHOD'] == 'GET' && isset( $_GET['action'] ) && $_GET['action'] == 'usystorequest' ) {
usystorequest();
exit;
}
}
JAVASCRIPT WB.JS FILE
// Step 3: Update your AJAX call to use the new endpoint
jQuery(document).ready(function($) {
$('#btn-x').click(function() {
$.ajax({
url: '/?my-endpoint=1', // The URL of the custom AJAX handler
type: 'GET', // The HTTP method of the request
data: { // The data to be sent with the request
action: 'usystorequest', // The name of the action to be triggered in the WordPress backend (functions.php)
},
success: function(response) { // A function to be called if the request is successful
if (response) {$('#mail_sent').show(); //mail got sent
}
else { $('#mail_not_sent').show(); //mail didnt get sent
}
}
});
});
});

Parse Server - How to delete image file from the server using cloud code

How can I delete an image's file from the server using Parse Cloud Code. I am using back4app.com
After Deleting Image Row
I am getting the images urls, then calling a function to delete the image using its url
Parse.Cloud.afterDelete("Image", function(request) {
// get urls
var imageUrl = request.object.get("image").url();
var thumbUrl = request.object.get("thumb").url();
if(imageUrl!=null){
//delete
deleteFile(imageUrl);
}
if(thumbUrl!=null){
//delete
deleteFile(thumbUrl);
}
});
Delete the image file from the server
function deleteFile(url){
Parse.Cloud.httpRequest({
url: url.substring(url.lastIndexOf("/")+1),
method: 'DELETE',
headers: {
'X-Parse-Application-Id': 'xxx',
'X-Parse-Master-Key': 'xxx'
}
}).then(function(httpResponse) {
console.log(httpResponse.text);
}, function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
});
}
for security reasons, not is posible to delete directly the image from Back4App, using DELETE from SDK or REST API. I believe that you can follow the guide below:
https://help.back4app.com/hc/en-us/articles/360002327652-How-to-delete-files-completely-
After struggling with this for a while it seems to be possible through cloud function as mentioned here. One need to use MasterKey in the cloud code:
Parse.Cloud.define('deleteGalleryPicture', async (request) => {
const {image_id} = request.params;
const Gallery = Parse.Object.extend('Gallery');
const query = new Parse.Query(Gallery);
try {
const Image = await query.get(image_id);
const picture = Image.get('picture');
await picture.destroy({useMasterKey: true});
await Image.destroy();
return 'Image removed.';
} catch (error) {
console.log(error);
throw new Error('Error deleting image');
}
});
For me it was first confusing since I could open the link to that file even after I deleted the reference object in the dashboard, but then I found out that the dashboard is not calling Parse.Cloud.beforeDelete() trigger for some reason.
Trying to download the data from the url after deleting the file through the cloud code function returns 0kB data and therefore confirms that they were deleted.

Parse Push's not delivered cloud code only

I'm running parse-server on ubuntu and can't seem to get push notifications working when sent in cloud code.
Push's work when using a REST api call (passing master key) but don't work when cloud code calls them.
What's interesting is that the cloud code Parse.Push() method returns a success and thus no error message.
My hypothesis is that this is a configuration problem, and the Parse.Push() method is referencing somethign I have incorrectly configured on the server.
here is my cloud function. This call works when sent via REST. and the success callback in cloud is always called.
Parse.Push.send(
{
// where: pushQueryClient,
channels: ["user_tkP7gurGzc"],
data:
{
alert: pushTextClient
}
},
{
success:function(){
console.log("push sent");
},
error: function(error){
console.log("push failed");
console.dir(error);
},
useMasterKey: true});
i think you have an issue with the useMasterKey parameter.
Please try to use this code in order to send the push notification:
Parse.Push.send({
where: whereQuery,
data: {
alert: {
title: request.params.title,
body: request.params.body
},
type: request.params.type,
sound: 'default'
}
}, {
useMasterKey: true
}).then(function() {
response.success();
}, function(error) {
response.error("Push failed " + error);
});
In this code i use Promises which is the best practice and also wrap useMasterKey in a separate object

YouTube Data API: add a subscription

I'm using YouTube's V3 Data API to add a subscription to a channel. This occurs on a Wordpress installation.
I added Google APIs (for oauth) on Wordpress theme functions:
wp_enqueue_script( 'googleapi', 'https://apis.google.com/js/client.js?onload=googleApiClientReady', array(), '1.0.0', true );
I added in the same way the oauth javascript file, which is the first one here: https://developers.google.com/youtube/v3/code_samples/javascript.
Following this guide(https://developers.google.com/youtube/v3/docs/subscriptions/insert (Apps Script)), I extended the OAuth js with the addSubscription method.
Google Client API seems to be loaded and working as it calls correctly googleApiClientReady on the oauth javascript.
So, this is how the subscription is being inserted:
OAUTH JAVASCRIPT
... ... ...
// After the API loads
function handleAPILoaded() {
addSubscription();
}
function addSubscription() {
// Replace this channel ID with the channel ID you want to subscribe to
var channelId = 'this is filled with the channel ID';
var resource = {
snippet: {
resourceId: {
kind: 'youtube#channel',
channelId: channelId
}
}
};
try {
var response = YouTube.Subscriptions.insert(resource, 'snippet');
jQuery('#success').show();
} catch (e) {
if(e.message.match('subscriptionDuplicate')) {
jQuery('#success').show();
} else {
jQuery('#fail').show();
alert("Please send us a mail () with the following: ERROR: " + e.message);
}
}
So, the first error comes with
YouTube.Subscriptions.insert(resource, 'snippet')
It says YouTube is not defined. I replaced it with:
gapi.client.youtube.subscriptions.insert(resource, 'snippet');
And that error went away. When checking response, as the subscription isn't completed, this is what I get
{"wc":1,"hg":{"Ph":null,"hg":{"path":"/youtube/v3/subscriptions","method":"POST","params":{},"headers":{},"body":"snippet","root":"https://www.googleapis.com"},"wc":"auto"}}
So, I would like to know what's happening on that POST request and what's the solution to this.
I can post the full OAuth file, but it's just as in the example, plus that addSubscription method at the end.
Okay, I got it working, the problem was on the POST request. Here is the full method working:
// Subscribes the authorized user to the channel specified
function addSubscription(channelSub) {
var resource = {
part: 'id,snippet',
snippet: {
resourceId: {
kind: 'youtube#channel',
channelId: channelSub
}
}
};
var request = gapi.client.youtube.subscriptions.insert(resource);
request.execute(function (response) {
var result = response.result;
if (result) {
// alert("Subscription completed");
}
} else {
// alert("Subscripion failed");
// ...
}
});
}
Also make sure to load Google Apps API (in fact without it the authorize/login button won't work) and jQuery.
Any chance you can post everything that made this work...all the JS entire auth.js save for your private keys, im working on this exact problem.

How to handle authentication errors in socket.io with socketio-jwt

Following the example for https://github.com/auth0/socketio-jwt , I couldn't get the authentication failure to fire.
How are you supposed to handle and configure authentication errors using this library? I see in the source code that it is supposed to throw an UnauthorizedError but I just can't seem to trigger it.
Server side
io
.on('connection', socketioJwt.authorize({
secret: 'test',
timeout: 7000
}))
.on('authenticated', (socket) => {
console.log('connected user: ' + socket.decoded_token.name);
});
Client side
socket.on('connect', function () {
socket.emit('authenticate', {token: 'badtoken'}); //send the jwt
});
socket.on("error", function(error) {
// this never fires
if (error.type == "UnauthorizedError" || error.code == "invalid_token") {
alert("User's token has expired");
}
});
Do I need to add an .on('error, function(error)) on the server code as well?
Looking at the source code for jwt, they are actually emitting "unauthorized", not "error". Change to
socket.on("unauthorized", function(error) {
// this should now fire
if (error.data.type == "UnauthorizedError" || error.data.code == "invalid_token") {
alert("User's token has expired");
}
});
This bug in the doc and examples was also reported here.

Resources