1) One way to put javascript on the client side is EJS e.g.
<h1> <%= title %> </h1>
where title is a variable.
2) Another way is to use back ticks and insert html or append etc using a library like jQuery
$('h1').html(`{obj.title}`);
3) A third way is to use react js esx, so import all the files on the client side if you are going down that route and add an variable as follows:
<div id="holder1"></diV>
var title = React.createClass({
render: function(){
return(
<h1 className="title1">{this.props.title1}<h1>
)
}
});
ReactDOM.render(<title
title1: "Hello World" />,
document.getElementById("holder1")
);
My question is how does react.js handle security so that the javascript cannot be manipulated such as a password on the client side (Not server side) and for 1-2 how can you enforce data hiding and prevent someone from changing the values. Can this only be done using server side react.js using node.
Let me clarify: How does React.js and other javascript libraries make the front end more secure... not just passwords... that can be handled with bcrypt hashes and https.
It's not entirely clear what you are asking, but as a very general rule, anything in the client can't be trusted.
Input posted to the server from the client can't be trusted, and should not be later displayed without proper precautions.
Web security is a huge topic. So I suggest you break your question down into smaller chunks and really identify what you are trying to ask.
Regarding React - it's not doing anything special around passwords. Its the responsibility of the backend service layer to protect from malicious input - there is a very real chance that a React component would send back crappy/malicious data. (not Reacts fault, nor is it the intent of React)
The only thing React has in this regard is {} vs dangerouslySetInnerHtml, but again, thats not going to protect passwords or the like.
Related
I'm creating a website that scraps with BeautifulSoup4 articles from other website and gives the user the articles as an output.
The articles are being saved in a data base. Each articles gets an id.
Current relevant code part for example:
#scrap.py
id = 0
if 'article' == 'new': #clearly this is just for the example...
id = id+1
I want the user will be able to see in real-time how many articles have been collected. Current relevant HTML code part for example:
<!--index.html-->
<div id="cur_id">{{ cur_id }}</div>
I'm rendering the id with flask to the HTML page. Current relevant code part for example:
#main.py
#app.route('/')
#app.route('/templates/index.html')
def index (name=None):
cur_id = scrap.id
return render_template('index.html', name=name, cur_id=cur_id)
How can i make the <div> in the HTML to get updated in real-time every time id gets updated?
Thanks!
Flask can do nothing to change the content of an already served webpage. As soon as the HTML is created and send to the client, flask is "done". Then the browser does stuff like interpreting the HTML, interpreting javscript (and possible adding interactions to the webpage) and lots of other things. Note that the client doesn't need to do this, there are clients that only download the HTML and are done (e.g. curl/wget).
So changing content on a webpage can only happen clientside, which essentially means javascript. If we have a new value, how do we update the content? Vanillajs is relativly simple:
var new_data = "3";
cur_id = document.getElementById('cur_id');
cur_id.innerHTML = new_data;
There are lots of libraries which help you with updating content. Jquery is an often used general purpose library. There are entire libraries which only focus on how to update the UI with new content, e.g. vue, react, ember and probably lots of others. react and ember also provide a server side if I remember correctly, so if you don't want to do vanillajs vue might be worth a look. But if you only want to update a single value you can't really beat the two lines vanillajs.
In the above snippet the new value is hardcoded which isn't helpful. How do we get new values to the client? If you really want realtime information websockets are the way to go. These are somewhat new and you should check if browser compatibility is acceptable for you.
cur_id = document.getElementById('cur_id');
ws = new WebSocket("wss://echo.websocket.org")
ws.onmessage = function(event) {cur_id.innerHTML = event.data};
simulate_update = function() {ws.send(Number(cur_id.innerHTML) + 1)};
ws.onopen = function(event) {setInterval(simulate_update, 2000)};
This uses an echo websocket server to simulate the server sending new information, but ofcourse it should connect to your websocket server. Flask per default cannot use websockets, but there some plugins like flask-sockets which make this possible. The "protocol" used above is very dumb and depending on your needs you want something smarter.
There are libraries which help with writing websocket code, often with integrated protocols. I think the most often used one is socketio which can fallback to different methods to exchange data (long polling, ajax) and puts a event/RPC/pubsub framework in front as far as I remember. It should also deal with reconnecting, heartbeat and other problems which one may not initially think about. There are lots of different websocket libraries.
I've never used react js and I have only dabbled with node's 'hello world' program.
I'm wondering if react works in such a way that if, say you add an <input type="text" /> tag, when you submit the form will react automatically handle the return of the data or do you need to separately write a client side .js file to handle the ajax data send to server?
Bonus: What is that type of framework called where it creates the two-way interaction automatically?
Apologies for what may be perceived as a basic question, but my beginner level comprehension of javascript hasn't completely got to grips with understanding what the docs actually mean.
Nope -- React is just a framework.
If you want to build a 'consolidated' javascript file that contains everything you need for your website, take a look at tools like webpack (or even better: create-react-app)
Form data is is submitted depending on how you structure your form, and that process is dictated a bit by HTML and a bit by your custom javascript.
To send AJAX based data, take a look at the 'fetch' API.
To manage the interaction between React, the data you're rendering, and other systems (like your server) take a look at Flux or Redux.
It really depend on how you write your application. React framework just render the "View" of your application.
Is you use a basical <form></form> with action the browser will automatically send the data into the "action" url attribute.
But you can just simulate a send of your form into a service/server/fake treatment and manage your return statement.
Well I never used React but, it's a javascript framework that has the same basic structure that Angular and Vue. Well REACT has directives that you can handle the data to send from the view into the component.js. If you want to send data to server you need to use libraries like 'axios' that you can import into you component and use it.
I just have began to study ReactJS and found that it gives you 2 ways to render pages: server-side and client-side. But, I can't understand how to use it together. Is it 2 separate ways to build the application, or can they be used together?
If we can use it together, how to do it - do we need to duplicate the same elements on the server side and client side? Or, can we just build the static parts of our application on the server, and the dynamic parts on the client side, without any connection to the server side that was already pre-rendered?
For a given website / web-application, you can use react either client-side, server-side or both.
Client-Side
Over here, you are completely running ReactJS on the browser. This is the simplest setup and includes most examples (including the ones on http://reactjs.org). The initial HTML rendered by the server is a placeholder and the entire UI is rendered in the browser once all your scripts load.
Server-Side
Think of ReactJS as a server-side templating engine here (like jade, handlebars, etc...). The HTML rendered by the server contains the UI as it should be and you do not wait for any scripts to load. Your page can be indexed by a search engine (if one does not execute any javascript).
Since the UI is rendered on the server, none of your event handlers would work and there's no interactivity (you have a static page).
Both
Here, the initial render is on the server. Hence, the HTML received by the browser has the UI as it should be. Once the scripts are loaded, the virtual DOM is re-rendered once again to set up your components' event handlers.
Over here, you need to make sure that you re-render the exact same virtual DOM (root ReactJS component) with the same props that you used to render on the server. Otherwise, ReactJS will complain that the server-side and client-side virtual DOMs don't match.
Since ReactJS diffs the virtual DOMs between re-renders, the real DOM is not mutated. Only the event handlers are bound to the real DOM elements.
Image source: Walmart Labs Engineering Blog
NB: SSR (Server Side Rendering), CSR (Client Side Rendering).
The main difference being that with SSR, the servers response to the clients browser, includes the HTML of the page to be rendered.
It is also important to note that although, with SSR, the page renders quicker. The page will not be ready for user interaction until JS files have been downloaded and the browser has executed React.
One downside is that the SSR TTFB (Time to First Byte) can be slightly longer. Understandably so, because the server takes some time creating the HTML document, which in turn increases the servers response size.
I was actually wondering the same researching quite a bit and while the answer you are looking for was given in the comments but I feel it should be more prominent hence I'm writing this post (which I will update once I can come up with a better way as I find the solution architecturally at least questionable).
You would need to write your components with both ways in mind thus basically putting if switches everywhere to determine whether you are on the client or the server and then do either as DB query (or whatever appropriate on the server) or a REST call (on the client). Then you would have to write endpoints which generate your data and expose it to the client and there you go.
Again, happy to learn about a cleaner solution.
Is it 2 separate ways to build the application, or can they be used together?
They can be used together.
If we can use it together, how to do it - do we need to duplicate the
same elements on the server side and client side? Or, can we just
build the static parts of our application on the server, and the
dynamic parts on the client side, without any connection to the server
side that was already pre-rendered?
It's better to have the same layout being rendered to avoid reflow and repaint operations, less flicker / blinks, your page will be smoother. However, it's not a limitation. You could very well cache the SSR html (something Electrode does to cut down response time) / send a static html which gets overwritten by the CSR (client side render).
If you're just starting with SSR, I would recommend start simple, SSR can get very complex very quickly. To build html on the server means losing access to objects like window, document (you have these on the client), losing ability to incorporate async operations (out of the box), and generally lots of code edits to get your code SSR compatible (since you'll have to use webpack to pack your bundle.js). Things like CSS imports, require vs import suddenly start biting you (this is not the case in default React app without webpack).
The general pattern of SSR looks like this. An Express server serving requests:
const app = Express();
const port = 8092;
// This is fired every time the server side receives a request
app.use(handleRender);
function handleRender(req, res) {
const fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
console.log('fullUrl: ', fullUrl);
console.log('req.url: ', req.url);
// Create a new Redux store instance
const store = createStore(reducerFn);
const urlToRender = req.url;
// Render the component to a string
const html = renderToString(
<Provider store={store}>
<StaticRouter location={urlToRender} context={{}}>
{routes}
</StaticRouter>
</Provider>
);
const helmet = Helmet.renderStatic();
// Grab the initial state from our Redux store
const preloadedState = store.getState();
// Send the rendered page back to the client
res.send(renderFullPage(helmet, html, preloadedState));
}
My suggestion to folks starting out with SSR would be to serve out static html. You can get the static html by running the CSR SPA app:
document.getElementById('root').innerHTML
Don't forget, the only reasons to use SSR should be:
SEO
Faster loads (I would discount this)
Hack : https://medium.com/#gagan_goku/react-and-server-side-rendering-ssr-444d8c48abfc
I know I can't hide it. But I just want to be sure that I am doing this thing right.
I have a master view where I render a few partial views:
#{
ViewBag.Title = "Index";
}
...
#{Html.RenderAction("Index", "Product");}
#{Html.RenderAction("Index", "Machine");}
In Product & Machine controller I have other actions and view for simple CRUD operations.
And each index has it's JS code to manipulate view when user try to do some actions.
On the image bellow I display what I can see on my site now when I open it and inspect.
This JS code is visible to everyone and my question is am I exposed to some kind of attack?
On production I will obfuscate *.js files.
And on server side I first check if user can make action (based on current userID).
I just want to know is my approach good or bad.
As long as you are validating the request on server side, you shouldn't worry about it. There is no way to hide JavaScript since you have to send it to the client. Obfuscation can be reversed. You should worry about CSRF attacks though. Probably nobody will bother to reverse engineer your JavaScript code. Once an attacker finds a way to make a valid request to your action, they will try to tamper the data or trick other people to make requests they are not aware of.
I consistently come across this code smell where I am duplicating markup, and I'm not really sure how to fix it. Here's a typical use case scenario:
Let's say we'd like to post comments to some kind of article. Underneath the article, we see a bunch of comments. These are added with the original page request and are generated by the templating engine (Freemarker in my case, but it can be PHP or whatever).
Now, whenever a user adds a comment, we want to create a new li element and inject it in the current page's list of comments. Let's say this li contains a bunch of stuff like:
The user's avatar
Their name
A link to click to their profile or send them a private message
The text they wrote
The date they wrote the comment
Some "edit" and "delete" links/buttons if the currently logged in user has permission to do these actions.
Now, all of these things were already written in our template that originally generated the page... so now we have to duplicate it inside of Javascript!
Sure, we can use another templating language - like Jquery's Template plugin - to ease the pain generating and appending this new li block... but we still end up with duplicate html markup that is slightly different because we can't use macros or other conveniences provided to us by the templating language.
So how do we refactor out the duplication? Is it even possible, or do we just put up with it? What are the best practices being used to solve this problem?
This is a common problem and becomes more obvious as the UI complexity increases, and changes have to be done on both the server and client templates. This problem is fixable by using a the same template markup on both the client and server sides. The template processors must be written in both JavaScript and the server side language.
Two other solutions that are cleaner than the above approach, but both have their own problems:
Do everything client side
Do everything server side
If all markup generation is done on the client side, then the server acts more or less like a web service which only sends back data in whatever formats suits the application. JSON, and XML are really popular formats for most web services nowadays. The client always generates the necessary HTML and JS. If going with this approach, the boundary between the client and server must be well defined. Since the client has limited knowledge of what happens on the server, this means that proper error codes must be defined. State management will become harder since most/all server interaction will be happening asynchronously. An example of adding a comment with this approach may look like:
$('#add-comment').click(function() {
var comment = $('#comment-box').text();
$.ajax('http://example.com/add', {
success: function() {
addCommentRow(comment);
},
...
});
});
function addCommentRow(comment) {
var user = currentUser().name;
var html = "<li><b>{user}</b> says {comment}</li>";
html = html.replace("{user}", user).replace("{comment}", comment);
var item = $('<li>').html(html);
$('#comments').append(item);
}
The other approach is to do everything server side. Whenever a change happens, shoot a request to the server, and ask it for the updated view. With a fast backend, response times under a second, and proper indicators of network activity, the application should seem very responsive despite everything happening on the server. The above example would be simplified to:
$('#add-comment').click(function() {
$.ajax('http://example.com/add', {
success: function(response) {
$('#comments').html(response);
},
...
});
});
Although this seems a lot more cleaner on the client side than the previous approach, we have just moved the markup generation up to the server. However, if the application is not very AJAXy like Google Maps, then this approach may be easier to work with. Again, it's a matter of how complicated the application is, and perhaps maintaining state client side is a necessity for you, in which case you may want to go with the previous approach.