How to make safe PUT DELETE requests? - javascript

I am making backend for my project and I have a question about safety.
As an example my task is handle different "/notes" requests.
/notes => get all notes of authorized user
/notes => create new note
/notes => delete note
So... Reciving data is safe. Noone can get these notes from another URL because of CORS.
If we will use GET params to create or delete notes
/notes?action=delete&note_id=7
bad people can send link to authorized user and he will lose his data by accident.
So next step is making POST requests.
Everything is much better, but there is still a little hole. If someone will add post form with hidden input params it can be dangerous.
So last thing that I'd add is sending extra param, that only authorized user knows.
User ID
Temporary hash
or something like that.
Is there any other solutions?

/notes?action=delete&note_id=7
You need a know id of owner note smt like that:
$note_id = (int)$_GET['note_id'];
$note = 'SELECT * FROM `notes` WHERE `id` = $note_id'; (fetch)
if($user['id'] == $note['user_id']) {
//delete code
} else {
exit('Bye bye');
}

Related

MSGraph API, filter mail by a Custom Value (internetMessageHeader)

Here is my goal :
Send an email through my interface with a custom value (Imagine, orderNumber186) then use it to filter all mails send or received by this value.
for example, I have a mail address with an icon, dans when I click on it I can see all discution with him, concerning the command (or whatever) that I'm on.
Exemple of a popup with mail info
If I'm on the order number 186, il click to the icon next to the mail and I see this popup with all mail received and send concerning this order precisely (Even the name or number is not mentionned, so not just a search query).
I consulted many documents from Microsoft as well as the forum, and this is all tests I carried out, with their advantages and problems :
internetMessageHeaders (example 2 form Microsoft doc, send mail)
With this solution, I can send a mail with my custom var easily, but it's impossible to get filtered mail with it, as it's said in this post.
Despite of it, I managed to filter myself, with foreach like this :
var listMail = [];
try {
//Look in all mails if they has an internetMessageHeaders with a name corresponding to var filterName
Providers.globalProvider.graph.client
.api("/me/mailFolders/SentItems/messages?$select=internetMessageHeaders")
.get((err, res) => {
if(err == null){
//Look if they are parameters
res.value.forEach(parameters => {
if(parameters.internetMessageHeaders != undefined){
//console.log(parameters);
//If Yes, loop for each internetMessageHeaders values to see if they have a corresponding name, then stock it inside a listMail array
parameters.internetMessageHeaders.forEach(element => {
if(element.name == filterName){
Providers.globalProvider.graph.client
.api("/me/messages/"+parameters.id)
.get((err, res) => {
listMail.push(res);
});
}
});
}
});
}
else {
console.log(err);
}
});
console.log('Email List => ', listMail)
}
catch (error) {
throw error;
}
So with this method, I can get all mail that contain internetMessageHeaders values.
Now, the problem :
For optimization, we definitely can't filter all mails to get mails that contain custom var, then fetch again to get the mail and store it in an handmade array, the best way is to do it with one query, to directly have all mails concerned.
For this, I've search about a second solution : singleValueLegacyExtendedProperty
I've found how to send mail with it, and even how to recover it.
When I use it, it work great when I fetch this request :
GET https://graph.microsoft.com/v1.0/me/mailFolders/SentItems/messages?$filter=singleValueExtendedProperties/any(ep:ep/id eq 'String {66f5a359-4659-4830-9070-00047ec6ac6e} Name MyName' and contains(ep/value, 'MyVar'))
My problem with this method, is that I can see all mail send, but if the client respond directly to the mail (By outlook for exemple), my var just disappear.
I think that it's not the case with x-var (internetMessageHeaders), but I'm stuck on it too.
So, my question is simple :
How to set a custom value to a mail, then filter all of it just by is custom value ?
Ideally, internetMessageHeaders is perfect, I just need to filter on it with a microsoft graph query directly.
Thank you for any help

XMPP - How do I delete all messages between two jids, but only for one user?

Problem:
I want to delete all the messages (and thread) from one side of an equation between two users, A and B. I have no idea if this is even possible and if so, how.
I have the:
jid of each user
an XMPP library in JS (custom) that allows me to send IQ or any other type of stanza.
For example, this is how I get my friends (roster) list:
async getFriends() {
const requestId = this.sendStanza(
'iq',
{ type: 'get' },
(stanza) => stanza.c('query', { xmlns: 'jabber:iq:roster' }),
)
const result = await this.once('*', requestId);
const requests = result.children[0].children.map(child => child.attrs.jid);
return requests;
}
Hopefully this is enough for someone to advise me. Thanks.
If you have full access to the client logic, you can implement your own logic, for instance, you can send an IQ stanza with a specific name space (xmlns) along with some elements/attributes, when the receiving side receives that IQ, it will do whatever logic you want (delete messages, thread, etc..)
Check this out:
https://xmpp.org/extensions/xep-0424.html
it is an extension to delete (retract) single message.

Automatically assign a customer to a specific customer group on sign-up - Bigcommerce

I've been told by BC support that this isn't possible, but I would be surprised if there really wasn't a way.
I need to be able to automatically assign a customer to a specific customer group when they create an account. My thought:
I would add an extra field to the sign-up form
Provide a user with a code (a string or number)
User enters code when creating new account
User hits submit
On form submit I would grab the value of the extra field:
var codeInput = document.getElementById('code-input').value;
I would then compare that value to a pre-defined string, and if there is a match, I would assign that customer to groupX (with a group id of 8):
if ( codeInput === "codeIGaveToTheUser" ) {
currentUserGroupID = 8;
}
Is it possible to assign a customer to a specific group on sign-up like this (or any other way)?
Any help is much appreciated.
Although using BigCommerce webhooks would ensure the highest success rate of executing your customer group assignment app, it requires quite a bit of setup on BigCommerce (creating a draft app, getting an oAuth key, jumping jacks, etc), and may be a bit of overkill for your requirements.
Here's an easier way, in my {mostly} humble opinion, that takes advantage of much of what you included in your original question. Any solution though will nonetheless require an external server to handle the customer group assignment through the BigCommerce API.
Within the BigCommerce control panel, add in the extra field to the user sign up form like you mentioned.
So as you can see, this new input field has been added natively to the default registration page:
So now, when a user creates an account on your site, the value for the Signup Code (the custom field created) will be directly accessible through the API for that customer's account. Take a look at what that JSON data looks like:
Okay, so this is nice and all, but how do we automate it?
To do so, we will have to let our external application know that a customer just registered. Furthermore, our external application will need some sort of reference to this newly created customer, so that it knows which customer to update the customer group for. Normally a BigCommerce webhook would notify us of all this, but since we aren't using a BigCommerce webhook, here's the alternative method to triggering the external script.
We will trigger our external application via the BigCommerce Registration Confirmation page - createaccount_thanks.html. This page is loaded immediately after a customer creates an account, so it is the perfect place to insert our trigger script.
Additionally, now that the customer is logged in, we can access the customer's email address via a BigCommerce Global system variable -%%GLOBAL_CurrentCustomerEmail%%.
We should make an HTTP request from this page to our external application along with the customer's email address. Specifically, we can make an XMLHttpRequest via JavaScript, or to be modern, we'll use Ajax via jQuery. This script should be inserted before the closing </body> tag on createaccount_thanks.html.
Example of POST request (although a GET would suffice as well):
<script>
$(function() {
$('.TitleHeading').text('One moment, we are finalizing your account. Please wait.').next().hide(); // Let the customer know they should wait a second before leaving this page.
//** Configure and Execute the HTTP POST Request! **//
$.ajax({
url: 'the_url_to_your_script.com/script.php',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({email:"%%GLOBAL_CurrentCustomerEmail%%"}),
success: function() {
// If the customer group assignment goes well, display page and proceed normally. This callback is only called if your script returns a 200 status code.
$('.TitleHeading').text('%%LNG_CreateAccountThanks%%').next().show();
},
error: function() {
// If the customer group assignment failed, you might want to tell your customer to contact you. This callback is called if your script returns any status except 200.
$('.TitleHeading').text('There was a problem creating your account').after('Please contact us at +1-123-456-7890 so that we can look into the matter. Please feel free to continue shopping in the meantime.');
}
});
});
</script>
Now finally, you just need to create your serverside application responsible for handling the request above, and updating the customer's customer group. You can use any language that you desire, and BigCommerce even offers several SDK's you can use to save mega development time. Just remember that you need to host it somewhere online, and then insert its URL to the JS script above.
PHP Example (quick & dirty):
git clone https://github.com/bigcommerce/bigcommerce-api-php.git
curl -sS https://getcomposer.org/installer | php && php composer.phar install
<?php
/**
* StackOverflow/BigCommerce :: Set Customer Group Example
* http://stackoverflow.com/questions/37201106/
*
* Automatically assigning a customer group.
*/
//--------------MAIN------------------------//
// Load Dependencies:
require ('bigcommerce-api-php/vendor/autoload.php');
use Bigcommerce\Api\Client as bc;
// Define BigCommerce API Credentials:
define('BC_PATH', 'https://store-abc123.mybigcommerce.com');
define('BC_USER', 'user');
define('BC_PASS', 'token');
// Load & Parse the Email From the Request Body;
$email = json_decode(file_get_contents('php://input'))->email;
// Execute Script if API Connection Good & Email Set:
if ($email && setConnection()) {
$customer = bc::getCollection('/customers?email=' .$email)[0]; //Load customer by email
$cgid = determineCustomerGroup($customer->form_fields[0]->value); //Determine the relevant customer group ID, via your own set string comparisons.
bc::updateCustomer($customer->id, array('customer_group_id' => $cgid)) ? http_send_status(200) : http_send_status(500); //Update the customer group.
} else {
http_send_status(500);
exit;
}
//-------------------------------------------------//
/**
* Sets & tests the API connection.
* #return bool true if the connection successful.
*/
function setConnection() {
try {
bc::configure(array(
'store_url' => BC_PATH,
'username' => BC_USER,
'api_key' => BC_PASS
));
} catch (Exception $e) {
return false;
}
return bc::getResource('/time') ? true : false; //Test Connection
}
/**
* Hard define the customer group & signup code associations here.
* #param string The code user used at signup.
* #return int The associated customergroup ID.
*/
function determineCustomerGroup($signupCode) {
switch ($signupCode) {
case 'test123':
return 1;
case 'codeIGaveToTheUser':
return 8;
default:
return 0;
}
}
So then you would do your customer group string comparisons directly in the serverside program. I'd recommend you rewrite your own BC API script as the one above in quality is really something along the lines of functional pseudo-code, but more so present to show the general idea. HTH
You would need to set up a server to listen for webhooks unless you wanted to do a cron job. We have some basic information on the developer portal, but I included more resources below. From there, you'd need to choose your server language of choice to listen for the webhooks once they been created, respond correctly (200 response if received), execute code based on this information, and then take action against the BC API.
So if you were looking for a code, you'd need to listen for the store/customer/created webhook, and have your code look for a custom field that contained the code. If it was present, then take action. Else, do nothing.
https://developer.github.com/webhooks/configuring/
http://coconut.co/how-to-create-webhooks
How do I receive Github Webhooks in Python

Multi-Page Order Form with sessions

For my web dev class we have to create a login page, verify it against encrypted records (Id, password) that we have to enter, then step through an order form (while being able to step forward and backward throughout).. so sessions and all that.. I have no idea where to even start aside from coding the html which I've already done.. Any pushes in the right direction would be helpful.. my instructor is abrasive and refuses to help most people without degrading them first.
This is kinda like a longer question.
First at login form you need to check with MYSQL / SQL / DB / etc if the username and password matches.
It's basically like this:
SELECT * from users WHERE username = 'username' AND pass = 'sha1(password)'
Or use the encryption method which you use (md5,sha1,any other for password)
Then you check out if it's returning a row. IF it's return 1 row,then everything is correct.
Then you put all this data to session. I don't know how much you need,but you can put the whole sql result to data. IT doesn't matter here as you said it's a dev class work.
So basically at every of your php you have to start with
session_start();
Then when you verified the user you put the sql result into SESSION like this:
$_SESSION['userdata'] = $sql_row_array;
With this data you can read the current loggedin user's informations. So it's like:
Get username: $_SESSION['userdata']['username']
So you can use this to identify whom bought / ordered the products and insert it into the database.

Redirect from JavaScript

I'm working on an internal web app and we are using secure query string keys generated server side for some simple security to prevent users from accessing pages they haven't been given access to. The page I am currently working on grabs data via AJAX calls and renders it in a table on the page. Each row has an edit button that will take the user to an edit page with more information, with the id of the row kept in the query string. Since every row id is unique, the key for every edit page will be unique to that row-user combination.
My problem is that I need to be able to get these secure query string keys from the server in some way that allows the JavaScript to redirect the user. I can't move the key generator client side because that opens up the possibility of users generating their own keys for pages they don't have permission to visit. And similarly I can't expose the generator in a web service.
Basically what this boils down to is I am stumped in finding a way to send data from the client to the server in order to generate a secure key and then redirect the user to the new page.
Not exactly sure if I am being 100% clear but I'll edit this as questions come in.
Your question is a little unclear, but PageMethods might work for this:
[WebMethod]
public static string GetSecureID()
{
return "Secure";
}
clientRedirectSecure = function() {
PageMethods.GetSecureID(onSuccess, onFailure);
}
onSuccess = function(result) {
window.location.href = "somepage.aspx?id=" + result;
}
onFailure = function(error) {
alert(error);
}
Here's an article that discusses PageMethods:
http://blogs.microsoft.co.il/blogs/gilf/archive/2008/10/04/asp-net-ajax-pagemethods.aspx

Categories