Show Menu
Cheatography

Internet Basics

What is the Internet
- Collection of computer networks that use a protocol to exchange data
- IETF (Internet Enforc­ement Task Force): Internet protocol standards
IP (Internet Protocol): Simple protocol for exchanging data between computers
TCP: Adds multip­lexing and reliab­ility on top of IP
- Multip­lexing: Multiple programs using same IP address
- Reliab­ility: Guaran­teed, ordered and error-­checked delivery
DNS (Domain Name Server): Set of servers that map(tr­ans­late) written names to ip addresses
URL (Uniform resource locator): Identifies the path to a document on the web server
HTTP (Hypertext transport protocol): Set of commands understood by a web server and sent from a browser
HTTP Commands:
- GET filename: Download
- POST filename: send a web form response
- PUT filename: upload

Security

Unders­tanding Threats: Deface­ment, Infilt­ration, Phishing (Spoofed site that looks real, retrieve login creden­tials), Pharmi­ng(Like phishing, get user to enter sensitive data into spoofed site, no conscious action required by the victim), DNS Cache Poisoning (Attacker is able to compromise DNS tables so as to redirect legitimate URL to their spoofed site), DNS translates URL to IP Addresses
SQL Injection:Untrusted input inserted into query or command
Solutions: Defence in Depth, Whitel­isting over Blackl­isting, Input validation and Escaping, Use prepared statements and Bind variables
Mitiga­tion: Prevent schema and inform­ation leaks, Limit privileges (defence in depth), Encrypt sensitive data stored in Database, Harden DB server and Host O/S, Apply input validation
Password Protection: Straw man Proposal, Saltin­g(I­nclude additional info in hash), Honeyp­ots­(Simple userna­me/­pas­sword combos as 'honey' to attract attack­ers), Aging passwo­rds­(En­cou­rag­e/r­equire users to change passwords every so often)
HTTP Is stateless: Cookie­s(-­Browser can refuse cookies, -size limit/ expiration policy), Hidden Variables (-Foll­owing hyperlinks causes a loss of state, -Current submitted page represents current state indepe­ndent of what was done previo­usly), URL Rewritting (-Current submitted page represents current state indepe­ndent of what was done previo­usly)
Web Security: Same Origin Policy (A webpage may include some JavaSc­ripts to access its DOM and send AJAX msgs to its backend, try to steal inform­ation from another website), XSSI (Cross­-site script inclusion, making sure scripts aren't dynami­cally created with sensitive data. Do not support GET requests for scripts returning URLS) XSS (Enables attackers to inject scripts into webpages viewed by other users, which can steal cookies, change appear­ances of web sites...Do validation and HTTP only option for cookies), XSRF (Makes a user to submit requests on behalf of the attacker. Protec­tion: Give a secret token to a user and tell the user to submit it along with cookie on following requests)

Web Perfor­mance

HTML Techniques: Lazy load content, Use idle time to pre-load content, Batch DOM updates, Set image sizes before loading, Reduce DOM depth
CSS Techniques: Styles­heets at the top, Remove unused CSS Rules, Avoid universal selectors, Don't abuse border­-radius & transform, Prefer selectors with native JS Support
Network Techniques: Make fewer HTTP requests, Content delivery network, Split resources across servers -load balance, But avoid too many DNS lookups

Perfor­mance

Load Testing: Process of putting demand on a system or device and measuring its response. Performed to determine a system's behaviour under both normal and antici­pated peak load condit­ions.
Locust.io
+: Write simple python code to simulate a user behaviour
+: Handled thousands of users on a single machine
-: Results are downlo­adable in CSV format
Back-end Tips: Increase parall­elism of node.js, Caching, DB Index

Express

OUR ASSIGNMENT
var express  = require('express');
var app      = express();   

 app.get('/newrecipe', function(req, res) {
        var User = require('../app/models/user');
        res.render('newrecipe.ejs', { message: 'loggedin' });
    });

    app.post('/newrecipe', function(req, res) {
          var newRecipe = new Recipe();
          newRecipe.author_id = req.user._id;
         newRecipe.name = req.body.name;
         newRecipe.description = req.body.description;
         res.render('newrecipe.ejs', { message: 'done'});
    });

EXAMPLE OF DEALING WITH A SIMPLE LOGIN FORM
HTML CODE
<form action=”form_submitted.php” method=”GET”>
        <h1>Login Form</h1>
        <label> Login:</label>
		<input type=”text” name=”login”><br>
        <label> Password: </label>
		<input type=”password” name=”password”><br>
        <button type=”submit” >Log In </button>
</form>
SERVER SIDE CODE
var express = require(‘express’);
var router = express.Router();
router.get(‘form_submitted.php*’, function(req, res){
	if (req.query.login == req.query.password){
		res.send(‘Login Successful’);
} else {
	res.send(‘Error: Login Failed’);
}
});
 

Less/Sass

CSS Pre-pr­oce­ssor: Converts code written in a prepro­cessed language in css
Allows us to do:
- Don't repeat yourself principle
- Mainta­ina­bility
- Readab­ility
- Natural extension
Less
- Easier to transition from CSS
- Resembles CSS
- Syntax not as jarring as SASS
- Newer Than SASS, inspired by it
SASS
- Syntax is quite different from CSS
- Symbols used are similar to bash
- More functi­ona­lit­y/c­apa­bility than LESS
- Complex tasks are more pragmatic than LESS

Databases

RDBMS (Relat­ional Database Management System): Has Concurrent access, Fault Tolerance, Data Integrity, Scalab­ility
NoSQL: Flexible Schema, Cheaper to setup, massive scalab­ility (Integ­rated Caching and Auto sharing), relaxed consis­tency BUT no declar­ative query language, and fewer guarantees due to ReCo.

Session and Cookies

HTTP Is stateless
- Simply allows a browser to request a single document from web server
- It remembers nothing between invoca­tions, thus short lived
- When we started using web applic­ations, we started ad hoc states
*Adding state to HTTP
- Client Mechan­isms:
1. Cookies Size limit/ expiration policy, browser can refuse
2. Hidden variables hyperlinks leads to loss of state
3. URL Rewriting Current submitted page represents current state indepe­ndent of what was done previously
4. Local Storage
- Server Mechanisms
1. Sessions (Persi­stent Storage) - In a file or database

Canvas Coding

ASSIGNMENT CODE
var canvas = document.getElementById("game");
var context = canvas.getContext("2d");

    document.getElementById("main").innerHTML = "<canvas id='"game "' width = 400 height = '"600"'>  </canvas> ;
	canvas = document.getElementById("game");
	
	// Add Mouse down listener
	canvas.addEventListener("mousedown", mouseDidPressDown, false);
	canvas.addEventListener("mouseup", mouseDidRelease, false);

	
	context = canvas.getContext("2d");

function mouseDidPressDown(event) {
	var WIDTH = HEIGHT * 0.65;
	var mousePosition = mousePositionInCanvas(event.clientX, event.clientY);
       //DO WHATEVER with mousePosition.x and mousePosition.y
}

EXAM CODE
<body>
    <canvas id='myCanvas' width='500' height='400'> Canvas not supported </canvas>
 </body>
</html>

<script>
  var canvas  = document.getElementById('myCanvas');
  var context = canvas.getContext("2d");

  function getMousePos(canvas, evt) {
      var rect = canvas.getBoundingClientRect();
	  return {
	    x: evt.clientX - rect.left * (canvas.width / rect.width),
	    y: evt.clientY - rect.top * (canvas.height / rect.height)
	  };
  }

 canvas.addEventListener('click', function(evt){
  	   var temp = getMousePos(canvas, evt);
  	   context.translate(temp.x, temp.y);
       drawCoolShape(context);
       context.translate(-temp.x, -temp.y);
  }, false);
</script>

AngularJS

Why
- Lightweight, free
- Modularity
- Reusable components
What we used previously
- Allows for DOM manipulation
- Does not provide structure to your code

<div ng-app=""> 
<p>Input something in the input box:</p>
<p>Name : <input type="text" ng-model="name" placeholder="Enter name here"></p>
<h1>Hello {{name}}</h1>

XML vs JSON

Some Basics
- XML is easy to read and make automation easy, but bulky structure makes files large, can be hard to structure data into good xml format
- Javascript XML has properties and methods to structure well
Something in XML
<menu id="file" value="File">
  <popup>
    <menuitem value="New" onclick="CreateNewDoc()" />
    <menuitem value="Open" onclick="OpenDoc()" />
    <menuitem value="Close" onclick="CloseDoc()" />
  </popup>
</menu>
Same in JSON
{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}
Navigating JSON
var data = JSON.Parse(file)
var fileId = data.menu.id;
var firstMenu = data.menu.popup.menuitem[0];

Mocha

What is it: Testing for Node
Example:
var assert = require('assert');
var calc = require('./calc.js');
describe('Calculator Tests', function() {
	it('returns 1+1=2', function(done) {
		assert.equal(calc.add(1, 1), 2);
		done();
	});
	it('returns 2*2=4', function(done) {
		assert.equal(calc.mul(2, 2), 4);
		done();
	});
});

AJAX

Asynchronous Javascript and XML: Not a programming language, just a way of using Javascript, Downloads data from server in background, Avoids dynamically updating a page without making the user wait
XMLHttprequest (and why it sucks): Javascript includes an XMLHttprequest object that can fetch files from a web server, BUT clunky and browser incompatibilities 
JQuery: Cross browser, simplifies javascript

$(document).ready(function(){
    $("p").click(function(){
        $(this).hide();
    });
});
 

Simple Web Request

Basic Structure:
Request: GET /HTTP/1.1
Reply:­HTT­P/1.1 301 moved perman­ently
Big Picture
- Client­-server model: A client process wants to talk to a server process
- DNS Lookup: Client must find server
- Ports: Clients must find service on server
- Finally establish a connection so they can talk
Types of connection (TCP/UDP)
- Connection oriented model: Use Transm­ission control protocol (TCP)
- Connec­tio­nless Model: Uses user datagram protocol (UDP)

GIT

Difference between CVC and DVC:
- Centra­lized Version Control: Repository goes straight to each working copy/pc
- Distri­buted Version Contol: Each computer has it's own reposi­tory, which can pull and push to server reposi­tory. WHAT GIT USES
Working with remote repository
- git remote abu link Creates a reference called abu to the link
- git clone https:­//b­lah.co­m/c­sc3­09.git clone remote rep and create local one
- git fetch mashiyat Download changes from mashiyat's repository to my local repository
- git pull mashiyat Downloaded changes and merges them to my local repository
- git push origin master
- git push mashiyat master
- git merge blah Merge changes made in blah branch to current branch

HTML5 and CSS3

HTML5: New features
- Semantic elements and markups
- Audio and video support
- Canvas
- Drag and drop
- Local data storage: Unlike cookies, the storage limit is far larger
CSS3
- Allows a lot of new things, such as border­-radius
- Viewport (vary with device size)
Responsive Web Design
@media (max-w­idth: 600px) { .facet­_si­debar { display: none; } }
Example of how to style the media for phones

Web Archit­ectures

Data indepe­ndence in Rel. DBMS
- Logical Indepe­ndence: The Ability to change the logical schema without changing the external schema or applic­ation programs.
- Physical Indepe­ndence: The ability to change the physical schema without changing the logical schema
Signif­icance of Tiers
- N-Tier archit­ectures try to separate the components into different tiers/­layers. Tier: physical separa­tion, Layer: logical separation
- 1-Tier archit­ecture: All 3 layers on the same machine - All code and processing kept on a single machine
- 2-Tier Archit­ecture: Database runs on server
- 3-Tier Archit­ecture: Each layer can potent­ially run on a different machine
MVC Design Pattern: Chang look and feel without changing the core/l­ogic, Maintain multiple views of the same data

MongoDB Schema

var mongoose = require('mongoose');
var bcrypt   = require('bcrypt-nodejs');
var userSchema = mongoose.Schema({

        firstname    : String,
        lastname     : String,
        password     : String,
        phonenumber : Number,
        fav_cuisine  :[String],
        admin        : Boolean
});

// generating a hash
userSchema.methods.generateHash = function(password) {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};

// checking if password is valid
userSchema.methods.validPassword = function(password) {
    return bcrypt.compareSync(password, this.password);
};

module.exports = mongoose.model('User', userSchema);

REST API Code

var requestBody = '';
var http = require("http"),
	url = require("url"),
	path = require("path"),
	fs = require("fs");
PORT = 3000;

function handleRequest(request, response) {
	var rest = url && url.parse(request.url).pathname;
  	var filePath = __dirname + request.url;

	var favs = fs.readFileSync('js/favs.json');

	if (chooseFile()) return;

	//For each of the possible return paths, send the json file
	if (request.url == "/allTweets") {
		returnTweets();
	} else if (request.url == "/allUsers") {
		returnTweets();
	} 

	//Function to return Json
	function returnJson(json) {
		response.writeHead(200);
		response.end(JSON.stringify(json, null, 8));
	}

	//Provide the file in accordance with the 
	function returnFile(path, type) {
	    var file = fs.readFileSync(path, 'utf8');
	    response.writeHead(200, type);
	    response.end(file);
	}

	function chooseFile() {
		if (path.extname(filePath) == '.js') {
			returnFile(filePath, {"Content-Type": "text/javascript"});
			return true;
		}
		if (rest.length <= 1) {
			returnFile('./index.html', {"Content-Type": "text/html"});
			return true;
		}
		return false;
	}
}
http.createServer(handleRequest).listen(PORT);
console.log("Nodejs Server running at http://127.0.0.1:" + PORT + "/");

JQuery Selecting Code

  function change(){
    $("body").find("*").hide();
    var images = $("body").find("img");
    images.parents().show();
    images.show();
  }
           
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          CSS2 Cheat Sheet
          PHP Cheat Sheet
          JavaScript Cheat Sheet