Why should I use node.js?

http://www.toptal.com/nodejs/why-the-hell-would-i-use-node-js

  • real-time websites with push capability
  • unifies the language and data format (JSON) across the stack
  • web applications with real-time, two-way connections, where both the client and server can initiate communication, allowing them to exchange data freely
  • non-blocking, event-driven I/O to remain lightweight and efficient in the face of data-intensive real-time applications that run across distributed devices.
  • You definitely don’t want to use Node.js for CPU-intensive operations
  • Node.js operates on a single-thread, using non-blocking I/O calls, allowing it to support support tens of thousands of concurrent connections
  • Although Node.js really shines with real-time applications, it’s quite a natural fit for exposing the data from object DBs (e.g. MongoDB). JSON stored data allow Node.js to function without the impedance mismatch and data conversion
  • Typical examples include: the logging or writing of user-tracking data, processed in batches and not used until a later time; as well as operations that don’t need to be reflected instantly (like updating a ‘Likes’ count on Facebook) where eventual consistency (so often used in NoSQL world) is acceptable.

htmlentities, htmlspecialchars, html_entity_decode

htmlspecialchars : converts only some characters to their html equivalents. This is preferred over htmlentities.

htmlentities: converts all characters to their html equivalents. This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.
htmlentities is only necessary if your pages use encodings such as ASCII or LATIN-1 instead of UTF-8.

html_entity_decode: Convert all HTML entities to their applicable characters. html_entity_decode() is the opposite of htmlentities()

Input Validation

1) Use in built functions
filter_input, filter_var, filter_input_array

$search_html = filter_input(INPUT_GET, ‘search’, FILTER_SANITIZE_SPECIAL_CHARS);

$args = array(
‘product_id’ => FILTER_SANITIZE_ENCODED,
‘component’ => array(‘filter’ => FILTER_VALIDATE_INT,
‘flags’ => FILTER_REQUIRE_ARRAY,
‘options’ => array(‘min_range’ => 1, ‘max_range’ => 10)
),
‘versions’ => FILTER_SANITIZE_ENCODED,
‘doesnotexist’ => FILTER_VALIDATE_INT,
‘testscalar’ => array(
‘filter’ => FILTER_VALIDATE_INT,
‘flags’ => FILTER_REQUIRE_SCALAR,
),
‘testarray’ => array(
‘filter’ => FILTER_VALIDATE_INT,
‘flags’ => FILTER_REQUIRE_ARRAY,
)

);
$myinputs = filter_input_array(INPUT_POST, $args);

2) htmlspecialchars()
The htmlspecialchars() function converts special characters to HTML entities. This means that it will replace HTML characters like < and > with < and >. This prevents attackers from exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.

3) stripslashes($data)

4) Use PHP Data Objects (PDO) for binding query parameters and prepared statements to avoid sql injection: PDO provides a data-access abstraction layer, which means that, regardless of which database you’re using, you use the same functions to issue queries and fetch data.

Cross Site Scripting (XSS), CSRF and SQL Injection

SQL Injection:
It is the type of attack that takes advantage of improper coding of your web applications that allows hacker to inject SQL commands into say a login form to allow them to gain access to the data held within your database.

In essence, SQL Injection arises because the fields available for user input allow SQL statements to pass through and query the database directly.

Example:

<?php
	      // We didn't check $_POST['password'], it could be anything the user wanted! For example:
	      $_POST['username'] = 'aidan';
	      $_POST['password'] = "' OR ''='";

	      // Query database to check if there are any matching users
	      $query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
	      mysql_query($query);

	      // This means the query sent to MySQL would be:
	      echo $query;
	      ?>

The query sent to MySQL will be:

SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''

Cross Site Scripting:

In general, cross-site scripting refers to that hacking technique that leverages vulnerabilities in the code of a web application to allow an attacker to send malicious content from an end-user and collect some type of data from the victim. Always validate user input to avoid cross site scripting.

Cross Site Scripting allows an attacker to embed malicious JavaScript, VBScript, ActiveX, HTML, or Flash into a vulnerable dynamic page to fool the user, executing the script on his machine in order to gather data. The use of XSS might compromise private information, manipulate or steal cookies, create requests that can be mistaken for those of a valid user, or execute malicious code on the end-user systems. The data is usually formatted as a hyperlink containing malicious content and which is distributed over any possible means on the internet.

Examples:

SCRIPT SRC=https://hacker-site.com/xss.js
BODY ONLOAD=alert("XSS")
BODY BACK GROUND="javascript:alert('XSS')
IMG S R C="javascript:alert('XSS');
IFRAME S R C=”https://hacker-site.com/xss.html

Simplified View:
XSS is when the user trusts the server too much, CSRF is when the server trusts the user too much

Take these two URL examples that an attacker might send to a victim, the XSS example would abuse a vulnerability on the page and inject javascript into the page and cause the user’s browser to execute the malicious code, the CSRF example causes the server to except malicious input from the user and process it as if the user intended to submit password change:

XSS: http://example.com?variable=a'< script >alert(1)
CSRF: http://example.com/changePassword?userID=1&newPassword=foobar

In simple terms XSS is when you can execute arbitrary Javascript in the victim’s browser typically because input wasn’t sanitised correctly. From there you can do whatever Javascript can, send their cookies to a malicious person, rewrite the DOM to make it seem like the page has been vandalised, redirect them to a malicious page / phishing website, etc.
CSRF is when you trick a user into performing actions with the authority the browser believes they have. Let’s say to change a password you need to submit a form along with being logged in under your account. The server would check you’re logged in via a session token. If I can get this user (‘the victim’) to click on a link which tells the browser to submit the form, the browser will submit it, along with the victim’s logged in session ID (which is always sent when visiting the site). Because as far as the website is concerned the user is logged it and submitting the form it will quite happily complete the action and change the password. An attacker could now log in with the (known) password themselves.

Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they’re currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request. With a little help of social engineering (such as sending a link via email or chat), an attacker may trick the users of a web application into executing actions of the attacker’s choosing. If the victim is a normal user, a successful CSRF attack can force the user to perform state changing requests like transferring funds, changing their email address, and so forth. If the victim is an administrative account, CSRF can compromise the entire web application.

Global Variables – Superglobals

Several predefined variables in PHP are “superglobals”, which means that they are always accessible, regardless of scope – and you can access them from any function, class or file without having to do anything special.

The PHP superglobal variables are:

$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION

$GLOBALS: $GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index].

$_SERVER: $_SERVER is a PHP super global variable which holds information about headers, paths, and script locations.
example: $_SERVER[‘PHP_SELF’], $_SERVER[‘SERVER_NAME’], $_SERVER[‘HTTP_HOST’], $_SERVER[‘HTTP_REFERER’], $_SERVER[‘HTTP_USER_AGENT’];

$_REQUEST: $_REQUEST, by default, contains the contents of $_GET, $_POST and $_COOKIE

$_POST: PHP $_POST is widely used to collect form data after submitting an HTML form with method=”post”.

$_GET: PHP $_GET can also be used to collect form data after submitting an HTML form with method=”get”.

$_FILES is a super global variable which can be used to upload files.

$_ENV is used to return the environment variables form the web server.
Example: $_ENV[“HOSTNAME”], $_ENV[“USER”], $_ENV[“COMPUTERNAME”]

Features of NoSql Databases

1) Elastic Scaling: Because of the distributed nature of non-relational databases, to scale NoSQL all you need to do is add machines to the cluster to meet demand. The new breed of NoSQL databases are designed to expand transparently to take advantage of new nodes, and they’re usually designed with low-cost commodity hardware in mind.

2) Big Data: They handle much bigger data volumes with relative ease.

3) Economics: NoSQL databases typically use clusters of cheap commodity servers to manage the exploding data and transaction volumes, while RDBMS tends to rely on expensive proprietary servers and storage systems.

4) Flexible Data Models: Even minor changes to the data model of an RDBMS have to be carefully managed and may necessitate downtime or reduced service levels. NoSQL databases have far more relaxed — or even nonexistent — data model restrictions. NoSQL Databases usually have “Eventual Consistency”.

5) Little Downtime: Because of their distributed nature, NoSQL databases can be pretty much always on. This is a huge advantage for web- and mobile-based businesses that can’t afford to be down for a single moment.

6) Auto-Sharding: NoSQL databases, on the other hand, usually support auto-sharding, meaning that they natively and automatically spread data across an arbitrary number of servers, without requiring the application to even be aware of the composition of the server pool. Data and query load are automatically balanced across servers, and when a server goes down, it can be quickly and transparently replaced with no application disruption.

Closure and Lexical Scoping in Javascript

A closure is the combination of a function and the lexical environment within which that function was declared. Note that Merely accessing a variable outside of the immediate scope (no return statement is necessary) will create something called a closure. A function accessing a global variable will also create a closure as can be seen by console.dir(function).

A closure is a function having access to the parent scope, even after the parent function has closed.

One example of A closure is a function that returns a function. The function that is returned (the inner function) is created inside the called function (the outer) so – due to the scoping rules we’ve seen – the inner has access to the variables and arguments of the outer.

JavaScript variables can belong to the local or global scope. Global variables can be made local (private) with closures.

Mozilla Development Network(MDN) gives a great definition:
“A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created.”

JavaScript has lexical scoping with function scope. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.

http://www.htmldog.com/guides/javascript/advanced/closures/

http://howtonode.org/why-use-closure

https://spin.atomicobject.com/2014/10/20/javascript-scope-closures/

Uses:
1) Most useful for events and callbacks
2) Used to simulate private variables i.e, encapsulation. Read more on Private members in javascript and privileged methods here : http://www.crockford.com/javascript/private.html
3) Used to create function factories
https://medium.com/written-in-code/practical-uses-for-closures-c65640ae7304