Node.js best way to add 'semi-dynamic' content - javascript

I have database with users (username, password, games (array, storing only ids of games)). From separate module, I fetch data about games. On my webpage, user profile is templated with just user object. I want that info about games to be dynamic - user can add/delete those games dynamically, without reloading the page. Database integration is easy, I'd do this with AJAX, but should I send game data also through it? I haven't worked so far with Angular, but from what I heard, maybe its best way? Or maybe forget about templating, do everything with Angular?
Im using node.js, mangodb, express.

You can "mix" angular with node template engines like ejs or jade based on express and have the main content rendered with the response and the rest of the content can be loaded or altered later using ajax and a REST API interface.
You well gain good performance as well as good SEO optimization since the "static" content is already on the page when it returns from the server
In your case
I'm suggestion you have a node express server with a few endpoints
[GET] /user/:id - will render a static html page with the user details
[GET] /user/games - will give a JSON response with the user games and added to the view using angular

Related

Flask API to provide JSON files to a simple HTML+JS+CSS webapp while keeping it secure

I've made a simple webapp that is going to show some data in a table, which will be updated weekly.
This update it done in the backend with some python code, that scrapes and alters some data, before putting it in a SQLite database.
After doing some reading I learned that to deliver that data to my webapp I should make a API with Flask, that can take that data and deliver it to the JS in my webapp in form of JSON, which then can use the data to populate the table. However, I should secure my API with username and pw. But as its a JS frontend that will retrieve data from the API, there is really no point, as the username and pw will have to be hardcoded into JS, which then can be read by the users. (I think)
Should I expose my API to everyone, or is this not the way to go to be able to use SQLite data as a backend for my webapp? I am fine keeping the API to a GET only.
You are correct, it is pointless for you to secure your API. Securing an API is only needed in certain circumstances.
If you are accessing data that you don't want anybody to see, perhaps through a backend call, then it would make sense to add in some form of security (normally an API key or Authorisation tokens in your request headers).
However, if you are making calls from your front-end (i.e. client side) to a backend API, then there is no point putting additional security there as the user can already see the request and already has access to the data the API is returning - so by securing it you are achieving nothing.
Normally, if the page the user is visiting contains sensitive data that you don't want everyone to see, you would take steps to secure your website instead (for example protecting it with a login for username and password before you can access that page). If you were to take this approach, where the website is protected by username and password, then you can update the API to make sure it does not respond to requests where the user is not authenticated (e.g. by generating a session token or something unique for each logged in user).
If you have a look around on websites that have lots of free data available, you will find they all have front end API calls that are completely unsecured (because it is pointless if the data is already free to access). Some websites do take steps to try to make sure it is their own website that is calling the API, but even then it is a bit pointless as web scrapers can always extract the data from the HTML.
Take a look at this page which outlines authentication headers. This simpler route is to hard code the header info in Flask to make it a little more secure. You could also try the more involved route of reading header info from your db. What's currently working for me to read from postgres db is below so you may modify it slightly for sqlite.
def valid():
headers = request.headers
auth = headers.get("X-Api-Key")
user = User.query.filter_by(apikey=auth).first_or_404()
print('from search of db ',user,'',auth)
return str(user)
As you mentioned, you plan to show a public data - then it can be used even
without authentication. Otherwise I think it can take too much unnecessary time spent on that.
As you have just a simple and single table from database, I believe that you don't need an API. You can just create HTML template and render it with data. Some examples can be found here and few more here.

Dynamic Data in Shopify Blog Page

I want to write an API, i.e. hosted at www.api.mywebsite.com (not affiliated with Shopify) and then have a shopify blog post that queries that API and displays that data using javascript.
I know how to do the API potion, but can I and if so how do I do the second part where I use JS to query and display data?
Simple! Add an App Proxy to your App. With that, you setup an end point to call in your App. On the blog page you can send an Ajax GET with an ID to your App, which can then get dynamic content ready for you to use. You can either format the response as Liquid or as JSON as two examples. Send back Liquid, and Shopify renders it for you. Send back JSON and you can stamp out your data in a template.
And best of all it is a secure callback to your App that you know came from Shopify, so you have no hassles or security problems. Look in your App for Extensions, and enable Online Store, where you can tinker with the Proxy.

How to simply add pages without bogging down routes? (express.js)

I am working on a site with Express.js, and like it very much. I have it operating stably, but would like users to be able to add pages to the site (via a form, where it will have set fields, or via uploading a jade file). Preferably I would also like a moderation queue. Failing this, how can I add pages without having to add an entry to index.js for the route every time? If I add lots of pages, won't this make it slow?
Sorry for the wall of questions, and thanks in advance for any help!
EDIT: It's been requested that I narrow the query, so here goes:
I would like to add a web interface to Express.js that allows users to fill in a form and add a page to the website under a certain path. I would like a sort of "moderation queue" where I approve pages before they go live. I cannot find any sort of information on this use case. How do I do it? Thanks.
First and foremost, you will need to get yourself a database where the moderation queue can sit and wait to be processed. The specific methodology of how to structure this database, and how to integrate this data into pages that can be delivered will depend on your choice of database and view engine.
After you have set up this system, you can use express's route parameters so that you do not have to write out all the possible routes into your scripts. Your express app can take the route parameters, look up the relevant data in your database, integrate this into a page using your view engine, and have express deliver this page to your client.
I would recommend giving express's guide on routing a thorough read as well as doing some more research into databases, and view engines.

Django: Page Refresh

Here's the view that updates the timestamp of a model in database whenever it's called,
def data(request):
new = Data.objects.filter(user=request.user)
new.update(timestamp=timezone.now())
return HttpResponse('')
This view is related to this URL,
url(r'^go/$', views.data, name='data')
Everything is fine, but how can I call this view & update the database without refreshing the page?
This is a great question as its something that may not seem as logical in django as say node or js based server and client interactions. Let me give a generic response then go more detailed.
Django is a web server. It has some newer functionality that allows it to more easily interact with javascript than it could in the past, but it is normally used in conjunction with a javascript framework. I'll normally build a django app w/ django-rest-framework and reactjs. So my workflow is normally to build the datamodel, serve up the page with compiled js as a static asset, and have those two communicate via a rest-api stood up with DRF.
Specifically to your question, you can simply have your django model communicate with the server via ajax posting to endpoint in your app. An example of a jquery/ajax post is available at this link. The only other thing you will want to look into is supporting csrf which Django discusses in the docs.
Let me know if this helps. If it does but requires specific snippets, let me know.

How to properly decouple Django from an AJAX application?

I'm using TastyPie and Django to build out my backend for an application that will have browser and mobile (native iOS) clients.
I have been through the TastyPie and Django docs, can authenticate successfully either using the TastyPie resources I set up, or using Djangos built in views. I see a lot of examples on including the CSRF token on the page and grabbing it with your JavaScript, and that works, but I don't understand now to actually determine whether a user is logged in on initial page load (from JavaScript).
Example:
If I want to serve static HTML from a separate, fast web server, and cache my application JavaScript, and only interact with Django through TastyPie views, how do I determine if the user is logged in (and know to render a login form or the app views using JavaScript), and after logout, is there any session information I need to remove from the client browser?
If I were to serve up HTML through Django's template engine, I could render the login form through there appropriately, but that seems not ideal if I want to truly decouple my JavaScript app from Django (and behave like a mobile client).
Edit: I am using Backbone.js, but I don't think that should matter.
UPDATE:
I think I figured it out reading through Django's CSRF documentation again.
If your view is not rendering a template containing the csrf_token template tag, Django might not set the CSRF token cookie. This is common in cases where forms are dynamically added to the page. To address this case, Django provides a view decorator which forces setting of the cookie: ensure_csrf_cookie().
If I do not want to render Django templates, this reads like I can still use the cookie and pull that into my Backbone or jQuery AJAX methods. I'm not sure if TastyPie ensures the cookie will be sent or how to tie into it.
If I use AJAX to logout, will the cookie automatically be removed or does it become invalid? Are these CSRF tokens unique to each user session? I'll have to test some things tomorrow with it. Is it possible to use Django decorators on TastyPie views?
A mobile client doesn't care if the Javascript comes from Django or any other web server. So go ahead and put all your JavaScript and static HTML on another server.
If you want your mobile app to see if the user is logged in, it should make an AJAX call to your Django backend (where the request is authenticated). The data returned should indicate if the session is active (user is logged in).
Another AJAX call can perform the Django logout function.

Categories

Resources