Server-side validation to prevent illegal POST requests [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
For my webapp (angular + node.js), I'm implementing a gamification system where users gain points for performing actions like answering questions, watching a video, etc. Currently, I simply post to '/api/users/updatepoints' with the user's id and number of points changed to update the database.
This is of course not secure, since a user could easily do an ajax request from the console while logged in, and I was wondering how I can prevent users from illegally sending out ajax requests? What sort of server-side validation could I use to do so?
//front end
$http.post('/api/users/updatepoints', {
kidId: xxx,
pointsChanged: yyy
})
//backend
exports.updatePoints = function(req, res) {
var kidId = req.body.kidId,
pointsChanged = req.body.pointsChanged;
User.findOne({_id: kidId}, function(err, user) {
if (err) return res.send(400);
user.points += pointsChanged;
user.save(function(err) {
if (err) return res.send(400);
return res.send(200)
});
})
}

The simple answer is "you can't".
A sufficiently determined hacker will always be able to take control of anything you are running on their computer. The only way to avoid that is to validate everything server side.
For example the only way to defeat "map hacks" in competitive online play is to never send information to the client unless that information is being displayed to the user.
If it's important, do it server side. Let the client side do its processing and validate and verify everything it sends you.
This is much too big a subject to properly discuss in a format like this though. Try doing some internet searches on preventing client hacks in games.

Related

Webdev, frontend and backend: how know if entity belongs to user? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have users and projects in a web application. Each user can have n projects. Each project can have m users. From a DB point of view, there are three tables: user, project, and user2project (to map the user and project n:m relation).
The backend is a simple crud-rest api (relational). Furthermore I'm using a JWT-token based authentication.
My frontend would show a project via projectId:
localhost:4300/projects/941343/
If the shown project belongs to the currently logged in user, my frontend should show additional buttons, such as "edit project".
But how can I know, that this project belongs to the currently logged in user?
Idea 1:
Have my backend always return the userids when the project is returned.
Sample response:
{
projectid: "941343",
title: "Some Project-Title",
description "Some Project-Description",
user2project: [
{ userid: "902319" },
{ userid: "299322" },
{ userid: "920392" }
]
}
With this approach I would just check if the project-object holds a user2project-object with the same userid as the currently logged in user.
Disadvantage: additional join in backend and bigger payload
Idea 2:
Once a user is logged in, I would persist not only the UserId, but also all ProjectIds of that user.
As such, I could then simply check the ID of the url with the persisted data.
Disadvantage: whenever someone else adds my user to a project, that change is not registered until I log in again.
Question: are these ideas viable for this purpose? Is there a better approach even?
If you know both the user id and the project id, the you could see whether or not this SQL query returns any result:
SELECT * WHERE user_id=X AND project_id=Y
You do the check on the server side. To check the same from the client side, you create an API call for it.
If the shown project belongs to the currently logged in user, my frontend should show additional buttons, such as "edit project".
I originally misread your question, I feel others may have also.
Using the authenticated user, check if the authenticated user === project owner inside your component, this could be as simple as:
<div *ngIf="authenticatedUser.id === project.ownerId">
<!-- SHOW BUTTONS -->
</div>
You would do this inside your ProjectSingleComponent, or whatever it's named inside your app.
If you support multiple users with the option to make changes, then use an .includes instead, checking if the array includes the authenticated user.
This is something RBAC would help with (not the buttons, practice in general). I'd encourage taking a look at what that would entail for future reference (although this is now off-topic to your original question).
EDIT: If you are looking to securely manage who has access to what, then this is the role of authorization and should be implemented using permissions, plus an additonal layer of database isolation (either physically or logically), to truly prevent access. If it's only the buttons you're interested in, the above approach may work.
An example to reflect my comment:
<div *ngIf="project.owners.includes(authenticatedUser.id)">
<!-- SHOW BUTTONS -->
</div>

Permanent change to DIV after data has been saved to DB [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How do I make this permanent and global?
By this I mean the color change of the div!
The data has been stored to DB and the div must remain red for all times for all computers ha-ha and not until the page reloads! How can this be achieved?
var x = document.getElementById("mySelect1").selectedIndex;
var y = document.getElementById("mySelect2").selectedIndex;
var color = "#ff0000";
request.done(function (data) {
if (data != -1) {
if (x==0 && y==0) {
document.getElementById("A9").style.backgroundColor = color;
}
alert("You Have successfully made an appointment");
location.assign("AjanvarausPage.html");
}
Server-side code will be needed to keep track of the change and notify all clients. The former will require some form of persistence, global memory/cache or database perhaps, while the latter is the trickier part. Since a server generally doesn't know if a web client is connected or not it has to be told there is a client needing to be notified.
But there are a number of ways this could be done.
Polling
Each client must poll the server-side code for potential changes. There are in general two different types of polling, short and long.
Short Polling
each client will need to ask the server if there are changes in a loop, usually with a delay to prevent hammering the server. The server responds immediately notifying the client if there are changes or not.
Long Polling
similar to short polling, with the single exception of the server not responding unless there are changes. This keeps the request open until it is either satisfied (there are changes to report) or it times out.
Push Notification
There are technologies, such as SignalR, that has the client register with the server and can then be notified repeatedly without further notification.

How to make Facebook API calls from server? Which token to use? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Could someone please explain the process flow of Facebook API calls from the server side? I understand the general process, but I do not know HOW to do it.
I want my website server to use login credentials (either with user access token or app access token) to periodically send API calls... approx every 15 mins. The purpose of getting the data from the server side is so I can save this data to my own database. For example, the results of the following API call:
`GET/v2.5/2405794352058/feed // get the latest posts from fb group feed`
// returns an array of objects
// [{message:'something interesting', id: '23435jlf8923', updated_at: Date()}]
In order to make these calls, I must use a user access token or app access token, which will exist for a finite amount of time before needing to re-login. If I opt to use a user access token I will be able to use a variety of tokens to get data and thus it is unlikely I will hit any usage limits. However, if I use an app access token I will have direct control of the access token, but all requests will originate with this same token. Which should I use?
I do not know how to do either of these techniques. The important thing I would like to know is HOW TO DO IT.
Here's what my server code currently looks like (returns 500 internal server error):
router.post('/check_posts', function(req, res, next){
var accessToken = req.body.accessToken;
var feed;
FB.api("/142985255268/feed?limit=100",
{access_token: accessToken},
function (response) {
if (response && !response.error) {
console.log(response.data);
feed = response.data;
res.json(feed);
}
}
);
});
I am using NodeJS, AngularJS, MongoDB and ExpressJS (aka Mean Stack).
App Tokens are valid forever. If you use the same User Token for the call, you may just use an App Token - because there are limits per Token. If you store User Tokens from other Users of your App, it´s better to use those - to avoid limits. Extended User Tokens are valid for 60 days.
More information:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
For using the Facebook API on your Node.js Server, either do your own calls or use one of the Third Party SDKs: https://developers.facebook.com/docs/apis-and-sdks#third-party-sdks

Using rails how to synchronize variable in controller to the view where the controller is the initiator of the update [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I tried the long polling in AJAX, where the client calls the server requesting data at a certain interval. - The updating of list in UI was initiated by the client
Below are the code:
server_controller.rb
##x=0
def results
##x++
render :json => ##x
end
index.html.erb
<button id='get_value' class="btn">Run</button>
<ul id="value_variable_from_controller"><ul>
$(document).ready(function() {
var getPoll=function getValue(trigger) {
$.ajax({
type: 'GET',
url: '/server/results/',
success: function(data, status) {
if (data < 50){
$('#value_variable_from_controller').append("<li>"+data+"</li>");
setTimeout(getValue(true), 1000);}},})}
$(document).on("click","#get_value",getPoll);
The Question is how can i do it oppositely where the controller has the power to initiate/send the data and the list on HTML was synchronously updating/appending?
This is more tricky to do, because you need an additional technology. HTTP and its request-respond model can't do this. A client (browser) can't receive requests from a server.
You'll end up with a bidirectional communication, because first the client ask the server things and later the server asks the client to update. A technology for doing this is websockets. Rails don't include this, so you need to add it via gems (websockets-gem) or/and probably an event driven, non-blocking server like node.js is useful as well.
There are different tutorials out there, which give you a start. Here is one example with two nice little graphics, which explain the situation.

Live Streaming and SSE [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to work on a project where i want to set a server which hosts videos, pictures, and texts. The main objective is to push up the media contents update to the client using Sever-Side Event.
It is more or less like digital signage player where i have to set up my own server and the client player. I'm totally new at this thing. Can someone give me any ideas on how i can do it. Just basic ideas would be great and i can search about them.
You might want to check out node-easysse and easysse-client
server
var easysse = require("easysse");
app.get("/chat-stream", easysse);
app.post("/chat", function(req, res) {
easysse.emit("chat", req.body.username, req.body.message);
});
client
<script src="easysse-client.js"></script>
<script>
var client = easysseClient.connect("/chat-stream");
client.on("chat", function(username, message){
console.log(username, "says", message);
});
$.post("/chat", {username: "mjackson", message: "hehe"});
// "mjackson says hehe"
</script>
Api docs
node-easysse API
easysse-client API

Categories