Summary

This document provides a fundamental overview of web development concepts, including internet protocols (like HTTP), and introduces databases.

Full Transcript

Web Development Fundamentals 01 - Internet & HTTP Request and Response 1) INTERNET Internet is a network of networks It is based on TCP/IP protocols It has a 4-layer model: - Application - Transport (TCP & UDP) - Internet (IP) - LINK (network a...

Web Development Fundamentals 01 - Internet & HTTP Request and Response 1) INTERNET Internet is a network of networks It is based on TCP/IP protocols It has a 4-layer model: - Application - Transport (TCP & UDP) - Internet (IP) - LINK (network access) Internet is based on RFC (Request for comments) Internet doesn’t belong to anyone so it belongs to everyone Every computer has an IP address to exchange data with other computers In IPv4, addresses are four bytes long: - A.B.C.D with AP, B, C, D = {0,..., 255} In IPv6, addresses are eight bytes long: - A.B.C.D.E.F.G.H with A.B.C.D.E.F.G.H = {0,..., 255} Every IP address has possibly 65536 ports to define network services An IP and a port is a network socket Just a small remark on IP addresses: - In general, address finishing by 0s (one or more) are network addresses (referencing a whole set of IP addresses) - In general, address finishing by 255s (one or more) are broadcast addresses (used to send to all the machines on the IP network) - But it depends of the network mask so it is not always true Among these 65536 ports: 0 to 1023 are Well-Known Ports: 20, 21: File Transfer Protocol (FTP) for data and control 22: Secure Shell (SSH) for secure logins, file transfers, and port forwarding 25: Simple Mail Transfer Protocol (SMTP) for email routing 53: Domain Name System (DNS) for translating domain names to IP addresses 80: Hypertext Transfer Protocol (HTTP) for web traffic 443: HTTP Secure (HTTPS) for secure web traffic 1024 to 49151 are Registered Ports: 1234: VLC Media Player 1433: MSSQL database server 3306: MySQL database server 3389: Microsoft Terminal Server (RDP) 3478-3481: Microsoft Teams 6463-6472: Discord 8080: Alternative port for http 49152 to 65535 are Dynamic Ports 2) HTTP HyperText Transfer Protocol is the protocol used to exchange information between a client and a server The information is mainly text The client sends a request (in text format) and gets back a response from the server The port 80 is used by the client to connect to an HTTP server The HTTP protocol is STATELESS! It means that in http, there is no mean to remember the state of a web page, variable, value... Every request and response is independant (it knows only itself) If we want memorization, we will be forced to find another way: - Cookies - Sessions 3) REQUEST & RESPONSE Browsing the web is basically mainly sending GET http requests and getting http responses! 02 - Databases A Short Introduction to Databases 1) DATA & DATABASES “In common usage, data is a collection of discrete or continuous values that convey information, describing the quantity, quality, fact, statistics, other basic units of meaning, or simply sequences of symbols that may be further interpreted formally” Data about me: - First name, Last name, Birth place, Date of birth, Age - Address, Number, Street, Zip code, Country… Data about a car: - Brand, Model, Color, Engine power, Energy, Kilometers, Year... “In computing, a database is an organized collection of data or a type of data store based on the use of a database management system (DBMS), the software that interacts with end users, applications, and the database itself to capture and analyze the data.” There are many DataBase Management Systems (DBMS) There are many models for databases: - Navigational DBMS (1960s) - Relational DBMS on “big” computers (1970s) - Relational DBMS on personal computers (1980s) - Object Databases and Object-relational Databases (1990s) - NoSQL and NewSQL (2000s) The classification of databases is complicated, it depends on many parameters. Difference between Data, Information, and Knowledge Data everywhere… Data creation every minute of the day… If you have the data, you have the power! Data is money! 2) THE RELATIONAL DATABASES “In a relational database, a relation is a set of tuples that have the same attributes. A tuple usually represents an object and information about that object. Objects are typically physical objects or concepts. A relation is usually described as a table, which is organized into rows and columns. All the data referenced by an attribute are in the same domain and conform to the same constraints.” The Relational Databases (RDB) use: - Entities (tables) containing data and organized in rows and columns - Columns are the attributes or fields - Rows are the tuples or records - One special column must be the primary key (PK) and has a unique value for each tuple in the table ENTITY(table) att1 att2 att3 … - - - … - - - … - - - … Primary Key (is unique) Attribute 3) THE ENTITY-RELATIONSHIP(ER) MODEL Problem in the real worlds →Entity relationship model→Database on a computer To create a Relational Database, the traditional way is to use the Entity-Relationship (ER) model which has three levels: - The conceptual model: a diagram representing the entities and their relationships - The logical model: a list of tables - The physical model: the organization of the information on the computer hard drives (files) Allows you to draw the database design Is an easy-to-use graphical tool for modeling data Widely used in database design Often done first with iterations to make perfect Goes from conceptual to logical to physical Contextual data: To set something in context, to further explain, and to give more value: sometimes you need context to a story. Components of the ER diagram: - Entities - Attributes - Relationships - Cardinalities 3.1) THE CONCEPTUAL MODEL Cardinality: It is a key component of every ER diagram. The cardinality defines the numerical attributes (min..max) of the relationship between two entities or entity sets. Recursive relations are allowed Relations with more than one entities are allowed There can have three kinds of relationship in a conceptual model: - One-to-one - One-to-many - Many-to-many To identify them, consider only the MAX values of the cardinalities 3.2) THE LOGICAL MODEL Rules: 1) Any entity becomes a table 2) Look at the cardinalities (max only): a. A one-to-many cardinality makes the PK on the 1 side become a FK into the table on the * side. b. A many-to-many relation becomes a full table with PK being the two FK of the tables in the relation. (That is why cardinalities are SO IMPORTANT!) 3.3) THE PHYSICAL MODEL This model deals with the data organization on your hard drive: it is PHYSICAL How many files do you need? Do you need an index to speed up the search for data? How they will be organized in the same directory, in multiple ones, on the same server, on the cloud?... For SQLite 3, it is easy, ALL the database will be in ONE physical file only! 3) THE ENTITY-RELATIONSHIP (ER) MODEL Once you have done the three (two only with SQLite3) steps: conceptual and logical, Congratulations, you have modelized your real-life problem into a computer database! Now, we need a language to describe our data and interact with our database 4) STRUCTURED QUERY LANGUAGE (SQL) SQL is a language to Create, Read, Update, and Delete data from a relational database. CRUD SQL is a ”standard” language that works (with several syntax changes) with ALL the different relational databases systems In this course, we will focus on the SQLite3 syntax but, it can be adapted easily to other DBMS such as Microsoft SQL Server, MySQL, Oracle, … The SQLite3 SQL syntax is described on the official site 5) SQLITE3 SQLite3 is a simple database management system where the data are stored in a single unique file In SQLite3, you can Create, Read, Update and Delete (CRUD) information Create: - Create a table: CREATE TABLE... - Create new data in a table: INSERT INTO … Read: SELECT * FROM... Update: - Update a table content: ALTER TABLE... (Be careful) - UPDATE... SET... WHERE … Delete: - Delete a table: DROP TABLE... (Be careful) - Delete one or more records (rows) in a table: DELETE FROM... WHERE... Introduction to JavaScript What is JavaScript? The programming language on the web Make things happen on the page Used for front-end development (user/client), back-end development (server), and more Why should you care? Javascript is: The programming language all web browsers use The most important language for front-end web development Used on every single modern website In high demand on the job market What is Javascript used for? HTML to create the structure of a web page CSS to add styling with colors and fonts etc. Javascript to make things happen on the page Javascript can: - Modify HTML elements (change text, color, etc.) - Handle events (when a user clicks a button or scrolls) - Get data from a server (add new content to a page without reloading) - Save data in the browser (like a shopping car or login status) How does Javascript work? Program code (such as Javascript) = instructions for the computer The computer reads and runs the code line by line from top to bottom ○ Unless told otherwise (e.g. loops, functions) When the computer runs the code it just follows the instructions Running Javascript Add Javascript to a page with ○ Works in the or Create the file script.js and add console.log (“Hello, JavaScript!”); Open the HTML file in a browser to see the output in the console Running Javascript with Node.js Node.js is a program that runs Javascript outside of the browser 1. Install node.js from nodejs.org 2. Right-click the script.js file in VS code 3. Select “Open in Integrated Terminal” 4. Run the script with node script.js Variables Store values with variables (name, age, etc.) Use let, or const to declare variables (sometimes var) ○ Let means the variable value can be changed later ○ Const means the variable value can’t be changed Variable names must be unique and can’t ○ Start with a number or contain spaces or special characters (except _ and $) ○ Be a reserved keyword (e.g. var, let, const, function, etc.) Data types Data type: the type of value a variable can hold Some common data types in JavaScript: ○ String: ‘Hello’, “World” - text ○ Number: 42, 3.14 - numbers ○ Boolean: true, false - true or false ○ Array: [1, 2, 3] - a list of values Working with variables Calculations: +, -, *, / ○ (You can also use + to combine strings) Set the value of a variable: =, += ○ Age = 55 ○ Age += 5 (adds 5 to the current value) Increment/decrement operators: ++, -- If statements Use if statement to run code based on if something is true or false if runs the code in its {} if what’s inside the parenthesis is true else if runs the code in its {} if all previous if statements are false and its own condition is true else runs the code in its {} is the if is false Loops Loops are used to run the same code multiple times for loop: repeats a block of code a specified number of times while loop: repeats a block of code while a condition is true Both loops can do the same things but they fit different situations Functions Reusable blocks of code Can take inputs (parameters) and return a value This function takes a name as input and uses + to combine it with a string Function return values Functions can return a value with the return keyword This is used to send a value back to where the function was called DOM (Document Object Model) How JavaScript accesses and changes HTML JavaScript can change the HTML of a page Change texts of images or anything else without reloading the page Getting elements from the web page document : access the DOM getElementById("some-id") : get the element with id="some-id" querySelector("p.introduction") : get the first element that matches the CSS selector, in this case, the first getElementsByClassName("some-class") : get all elements with class="some-class" getElementsByTagName("p") : get all elements of a specific tag, in this case, all elements Most common: querySelectorAll("p.introduction") : get all elements that match the CSS selector, in this case, all Changing elements on the page Change HTML content: myElement.innerHTML Change HTML attributes: myElement.src = 'image.jpg' Change CSS styles: myElement.style.color = 'red' Add or remove HTML elements: myElement.appendChild(newElement) Adding elements to the DOM Create a new element with document.createElement() Set attributes and content with like style and innerText Add the element to the DOM with appendChild() Events and event handling Events: something happens to the HTML elements Some common events: Clicking a button: click Moving the mouse: mousemove Handling events: write code that runs when an event occurs User clicks a button » hide the button To add an event handler, use addEventListener('event', function) Use anonymous functions for simple event handlers Event handling inline Not recommended Hard to read and maintain Harder to write complex code Event handling with addEventListener Easier to read and maintain Better separation of concerns More flexible Allows for multiple event handlers on the one element DOMContentLoaded event Runs when the HTML has been completely loaded and parsed Use this when your code needs to run after the HTML has loaded Not necessary when is placed at the bottom of Development Tools / Frameworks React, Angular, and Vue.js Toolkits for building user interfaces with html, css, and javascript Node.js & Express (server-side JavaScript) Tools Write your code with VS Code Store and whare your code with Github Getting started with Github: link Host your website with Github Pages Use Codepen to experiment with HTML and CSS Introduction to Node.js What is Node.js? JavaScript runtime built on Chrome's V8 JavaScript engine. - Runtime environment: Program that executes code. Execute JavaScript code outside of the browser, as a server. Uses an event-driven, non-blocking I/O model - Event-driven: Executes code in response to events. - Non-blocking: Allows multiple concurrent requests. - I/O model: Handles input/output operations. Why should you care? Node JS is: Fast and Efficient Unified Language for frontend and backend NPM Ecosystem Scalability Client-Server Architecture Brief history of Node.js Created in 2009. Inspired by Google's V8 JavaScript engine (Chrome). Initially used for building web servers. Now used for a wide variety of applications: - Web development - Command-line tools - Internet of Things (IoT) - Real-time applications Updated regularly with new features and improvements - Current version: 22.8.0 (as of 2024-09-03) What is NPM? NPM: Node Package Manager Default package manager for Node.js. Package: A collection of code. Package Manager: Tool for installing and managing packages. Installing Node.js Verify installation: node -v Verify NPM installation: npm -v Using the terminal / PowerShell Terminal: Command-line interface for executing commands. PowerShell: Command-line shell for Windows. Command-line: Text-based interface for interacting with the computer. Basic commands When you open a terminal, you see a prompt where you can type commands and where on the computer you are. In VS Code: open it by selecting View -> Terminal - Another option: Right-click in a file or folder and select Open in Integrated Terminal. Commands: Instructions to the computer. - ls : List files and directories. - cd : Change directory (navigate to a different folder). - mkdir : Create a new directory. - node : Run Node.js scripts. - clear : Clear the terminal screen. - pwd : Print where you are in the file system. - exit : Close the terminal Running JavaScript with Node.js Create a new JavaScript file: app.js. Add JavaScript code to the file. Run the command: node app.js Managing dependencies with NPM NPM is used to install and manage packages (dependencies). Packages are installed in node_modules. package.json : metadata about the project - See and manage the dependencies of your project. In package-lock.json you can see all installed packages and their dependencies (you should not edit this file manually). Using NPM Initializing a new Node.js project: npm init Installing packages: npm install package-name Installing packages globally: npm install -g package-name Running scripts defined in package.json: npm run script-name package.json Project name: my-project Application version: 1.0.0 Start script: node app.js - Run with npm start Dependencies: express version 4.17.1 Some useful NPM packages Express.js: Web framework for Node.js. - Install: npm install express Nodemon: Automatically restarts Node.js applications. - Install globally: npm install -g nodemon Axios: Promise-based HTTP client for JavaScript. - Use this to make HTTP requests. Updating or removing packages Updating packages: npm update package-name Removing packages: npm uninstall package-name Updating all packages: npm update Common Node.js Core Modules Core modules: Built-in modules that come with Node.js. fs : File system module. http : HTTP module. path : Path module. os : Operating system module. events : Events module. Using the os module The os module provides information about the operating system. Examples: Platform, architecture, CPU information. This module is useful for system-related tasks. The following code snippet logs information about the operating system. Asynchronous Programming Allows multiple tasks to be executed at the same time. Callbacks Function that is called by another function. Passed as arguments to functions and can be anonymous or named functions. Promises Used for asynchronous operations to wait for a result or error. Can be resolved or rejected. - Resolved: Operation completed successfully. - Rejected: Operation failed. - Pending: Operation is still in progress. Can be chained together using.then() or async/await. Async/Await async and await : used for asynchronous code. Simplifies working with promises. async : marks a function as asynchronous. await : waits for a promise to be resolved or rejected. 03 - Creating a World Wide Web 1) The Web The World Wide Web is a network of web servers delivering web pages through the http protocol. It has been created by Tim Bernes-Lee, Robert Cailliau et al. in 1989 at CERN, Geneva, Switzerland. The web is only part of the Internet. Web pages are written in the HTML language. HTML5 is the latest version of HTML. In a web page, a anchor link can be redirected to another web page everywhere on the web. 2) Developing static web pages HTML is a description language where you use tags to organize information To develop static web pages, you only need a text editor and a browser to see the result The main problem with static pages is you need to reload all the page each time there is a change in the information In order to increase performance, it is preferable to load only a small part of the page (the one that changes) 3) Developing dynamic web pages Dynamic web pages: more complicated pages (with data coming from databases) We want to load only the information that changes Dynamic web pages: data comes from databases, load only the information that changes! 4) Front-end / Back-end development In web development, there are three “types” of developers: - Front-end developers - Back-end developers - Full-stack developers Front-end is the part of the web site the user sees: HTML, CSS, Javascript (client-side) Back-end is the part of the web site the user doesn’t see: Javascript (server-side), PHP, Ruby On Rails, Python (Django), Java Server Pages (JSP), Microsoft DotNet… Full-stack is the development in both client-side and server-side Client-side (runs in the browser) Server-side (runs on the server) 5) Why node.js? Why JavaScript? Node.js is a full-stack development tool It runs on the server-side However it can use frontend(client-side) libraries, CSS frameworks, access to databases directly on the server-side Javascript is a very important programming language both on the client and the server side It is an asynchronous eventdriven, object-oriented, dynamic typing language Node.js (Javascript on the server-side) is a full-stack programming language (both on the client and the server side) Many companies are looking for Node.js/Express programmers! 04 - Node.js Javascript on the server side Outline 1) Node.js 2) Installation 3) Terminal commands 4) Path 5) Hello World! 1) Node.js Node.js is a back-end Javascript runtime environment It is based on the V8 Javascript Engine It executes Javascript code outside a web browser It can create running servers with only several lines of code 2) Installation Two versions: - LTS (Long Term Support): The support lasts for a longer period - Current: Latest features and improvements but support limited in time We will use the same version: 20.17.0 LTS (Long Term Support) On Windows: - Download the installer - Run the installer (generally in your “Downloads” folder) - Click on ”Next” several times… - Then ”Finish”: it’s installed! To check installation, you have to use the terminal, Node.js is a ”command line” based tool! On Windows, type on ”the Window” key then type in ”terminal” or ”cmd”, the terminal window opens Type ”node -v” or ”node --version” at the prompt to get the version of node, if you obtain v18.17.1, it is OK! You can also check the installation of npm (node package manager) This tool will install all the needed libraries and will verify the dependencies for you! Type ”npm –v” to get the version of npm 3) Terminal Commands “cd” or “pwd”: tells you where you are in the file tree “mkdir directoryName”: creates a directory in the current directory “cd directoryName”: goes into your directoryName directory “cd..”: goes one level up in the file tree “dir” or “ls”: list the files in the current directory 4) Path On a filesystem, you have directories (folders) and files The filesystem is organised as a tree with a root (/ on MacOS/Linux and \ on Windows) In this tree structure, you can specify the path of a file or a folder. It is the path to follow to reach the file or folder There are two means to specify a path: - Absolute (you start from the root of the filesystem and you go down in folders to reach the target) - Relative (you start from the current directory and you can go up and/or down to the target) The operating system has a default PATH variable that will find automatically your commands That is why the command node is known by the system From the terminal, you can specify commands and path in the absolute or relative way, you choose! To run a node program, you have to run the node command on the file code On the prompt, you type ”node” then ”space” and you give the path of the file to run An absolute path starts with the root (/ or \) A relative path doesn’t start with the root (/ or \) With paths, you can run commands from any directory 05 - Express Application framework for Node.js 1) Express.js Express is a back-end application framework for Node.js It simplifies code development with Node.js 2) Installation In a project folder (where there is a “package.json” file) Run the command ”npm install express” It will create a ”node_modules” folder with many directories/files in it One of them being express and the others dependencies necessary to run express 3) Middleware Architecture Express uses a middleware architecture in which the request passes through possibly many middlewares (functions) before building and sending the response to the client 4) Comparing Node and Express 5) Routes In the code, app.get(”/”, … ) app is your web server (application) get is the method the server will receive onto ”/” is the route Your routes will define your REST API (it is the CRUD in your database) - post: create new information (Create) - get: get information (Read) - put: update information (Update) - delete: delete information (Delete) 06 - JSON A simple notation to describe complicated data 1) JSON JSON (JavaScript Object Notation) is a way to write objects in Javascript JSON is now used by MANY programming languages because of its power and simplicity “JSON (JavaScript Object Notation) is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays (or other serializable values). It is a common data format with diverse uses in electronic data interchange, including that of web applications with servers.” 2) Notation All JSON is on this slide! { and } mean ”object” [ and ] mean ”array” ”key”: ”value” is a pair consisting of a key associated to a value , is the separator between objects AND between pairs In JSON, you ONLY need these characters: { } object [ ] array “key”: “value” pair , separator 07 - MVC & Handlebars MVC design pattern and views made with handlebars 1) MVC Model-View-Controller is a design pattern used to develop GUIs using three independant parts: - Model: the data to be processed - View: the way the data is shown on the screen - Controller: the head of the program that controls everythings and links/sends the model to the view The Model (the data) is typically stored in a database The View generates HTML code The Controller: - Receives incoming HTTP requests - Fetches the Model from the database (the data) - Asks the View to generate the HTML code for the fetched Model - Sends back an HTTP response with the HTML code generated (the View) 2) Handlebars Handlebars is a page template generator You can ask to render a static web page (no data given to the page): app.render(‘page_name’) You can ask to render a dynamic page (data given to the template): app.render(‘page_name’, data) In this case, the data is given to the page and can be processed using helpers on the final generated web page Data is called the context, you pass the context to the template and handlebars generates Express, Handlebars, and SQLite3 HTTP request and response Request and Response Cycle Requests: Client sends a request to the server ○ Headers: Information about the request ○ Body: Data sent to the server Response: The server sends a response to the client ○ Headers: Information about the response ○ Body: Data sent to the client Request Method: GET, POST + (PUT, DELETE, PATCH) Host & path: The path to the resource Other headers: Content-type, Accept, Authorization, etc. Response contents Status code: 200, 404, 500, etc. Headers: Content-Type, Content-Length, etc. Body: Data sent to the client Request methods GET: Get a web page or resource ○ Default method for web browsers POST: Send data to the server ○ Adding or updating a resource ○ Login form, contact form, etc. Response status codes 200: Success - everything is OK 400: Bad request - invalid data sent 401: Unauthorized - user not logged in 404: Not found - resource not found 500: Server error - something went wrong Express JS Express JS: A web framework for Node JS Web framework: A library that makes it easier to create web applications Install Express JS: npm install express Routes Route: The path to a resource on the server ○ Example: / , /about , /contact Route handler: A function that is called when a route is matched Routes parameters Route parameters: Variables in the URL Purpose: Show different content based on the URL Use: Use the same route handler for different URLs Example: /dogs/:id -> /dogs/123 -> id = 123 Handling different HTTP status codes 200: res.send('OK') ○ The default status code 404: res.status(404).send('Not found') 500: res.status(500).send('Server error') Works for all status codes Also works with res.render() , res.json() , etc. Handlebars Handlebars: A templating engine for Node JS Templating engine: Generates HTML from templates Purpose: Use the same HTML with different data Use: Create dynamic web pages with Express JS Install: npm install express-handlebars Layout and view Layout: The same HTML code for all pages View: The unique content for each page Store data with SQLite What is SQLite? SQLite: A database for storing information Database: A collection of related data Purpose: Store data for web applications Use: Store users, products, etc. SQLite basics Table: A collection of related data (dogs, cars...) Column: A property of the data (id, name, breed...) Row: A single record in a table (1, Aiko, Canaan Dog) Primary key: A unique identifier for each row (id) SQLite commands Create a table: Creates a place to store data Insert data: Adds data to a table Select data: Gets data from a table Create a database, table and data Install SQLite: npm install sqlite3 Primary key: A unique identifier for each row 09 - Forms A way to send information from the client to the server 1) Forms Forms are a part of HTML to create user interface to send information from the client to the server But remember, you MUST check the validity of the entries of your forms fields on the client and/or on the server: don’t trust form users! A form has two default attributes: method and action method specifies the method to send information: - GET: the information are sent inside the URL has URL?name1=value1&name2=value2&name2=value3 - POST: the information are sent in the body of the request action specifies the route or path to send the information to A form has one or more fields (text, textarea, radio, checkbox, select/options, date, file, hidden…) A form has a ”submit” button inside it (don’t put the button outside the form) 2) Forms within node & express GET method: GET method: the information is passed in the URL => no password please! POST method: POST method: the information is passed in the request => yes for password! 3) Forms summary A form has two default attributes: method and action method specifies the method to send information: - GET: the information are sent inside the URL has URL?name1=value1&name2=value2&name2=value3 - POST: the information are sent in the body of the request action specifies the route or path to send the information to GET: data is passed into the URL => no password! POST: data is passed in the body of the request: OK for password! 10 - Debugging How to debug your code? 1) Bug It is the same in programming: - To make a program run, you need: Synctatically correct: the code is well-written Semantically correct: the meaning is good, the behavior is the one you want - In Javascript, the code in non-blocking! It means the code will not execute synchronously but asynchronously JS is an event-based language It makes JS very difficult to debug! 2) Read the error messages! When you have a function that provides errors, display the error and read it! The error message gives the error type and the line where it occurs 80% of the time, you have just forgotten a closing ) or } 20% of the time, you need to investigate more… 3) Your best friend: console.log() When you face an error in one of your routes, try to console.log() a message to see if your code is going through this route You can log a string message (character string): console.log(’This is the good route!...’) You can log the content of a variable console.log(’The error is: ’+error) If the content of the variable says ’object’, then try: console.log(’My variable contains: ’+JSON.stringify(myVariable)) (of course, you need to change the name of the variable ”myVariable”) 4) Last solution Go to labs and ASK for HELP! Authentication, Session, and Cookies Authentication: Identifying a user Sessions: Keeping track of a user Cookies: Storing data in the browser Registration and login: How to authenticate a user in our application Authentication Authentication: verifying the identity of a user Strategies and Libraries Local authentication: Username and password OAuth: Third-party authentication ○ Google, Facebook, etc JWT: JSON Web Tokens ○ Typically used in REST APIs Storing Passwords Securely Never store passwords in plain text: password123 Use bcrypt to hash passwords securely This will prevent attackers from accessing the passwords Hashing and salting passwords Hashing: Converts a password into a fixed-length string - The same password always gives the same hash Salting: Adds random data to the password - Prevents attackers from using precomputed hash tables Bcrypt: A popular library for hashing passwords - Uses a salt to protect against rainbow table attacks Middlewares in Express Middlewares: functions that run before the route handlers Use: authentication, logging, parsing, etc Purpose: modify the request or response before the route handlers Middleware for logging requests ​Add this before any routes to log each request to the console This will output the request method and URL to the console for each request Example: GET / or POST /login Session Management Sessions: keep track of a user’s state across multiple requests Logged in or out Shopping cart Form data for multi-step forms Sessions in Express Express-session: A popular middleware for managing sessions in Express Setting session data Add a middleware to pass the session data to Handlebars Show the user’s name in the template Use Handlebars to show the user’s name if they are logged in Show a login link if they are not logged in Cookies Cookies: small pieces of data stored on the user’s browser Use: store data that persists across requests Purpose: store session IDs, user preferences, etc express-session uses cookies to store the session ID. You can see this in the browser's developer tools Cookie name: connect.sid Session middleware Update the session middleware to store the user in the session Summary and end notes Authentication: Identifying a user in our application Sessions: Keeping track of a user across the site Cookies: Storing session data in the browser Password hashing: Securely store passwords Middlewares: Change the request or response Express-session: Manage sessions in Express Joining and updating data + web security Common security vulnerabilities SQL injection: inserting SQL code into a form field Cross-site scripting (XSS): inserting JavaScript code into a form field Cross-site request forgery (CSRF): tricking a user into performing an action on a website SQL injection SQL injection is a code injection technique The attacker inserts SQL code into a form field The SQL code is executed by the database Preventing SQL injection ALWAYS use prepared statements - E.g. sqlite3 with placeholders (?) NEVER trust user input Use ORM (Object-Relational Mapping) library like Sequelize of TypeORM Cross-site scripting (XSS) Cross-site scripting is a code injection technique The attacker inserts JavaScript code into a form field The JavaScript code is executed by the browser If you have a blog or forum where users can post content, you are vulnerable to XSS Example: Samyworm A worm that spread through MySpace in 2005 by injecting JavaScript code into the user’s profile. The worm added the user as a friend and posted a message on the user’s profile. The worm spread to over one million users in less than 20 hours. Preventing cross-site scripting (XSS) Never trust user input Escape user input - This is done for you in handlebars when using {{variable}} Use content security policy (CSP) - A set of rules that tells the browser which content is allowed to load on a page Cross-Site Request Forgery (CSRF) Cross-Site Request Forgery is an attack that tricks a user into performing an action on a website 1. The attacker creates a form on their website (becomerich.com/offer) that submits to the target website (bank.com/transfer) 2. The form is submitted automatically using JavaScript 3. The user is tricked into visiting the attacker’s website (becomerich.com/offer) 4. The user’s browser sends the form data to the target website (bank.com/transfer) Preventing Cross-Site Request Forgery (CSRF) Never trust user input Use a CSRF token: A unique token that is generated for each user session Use the sameSite, httpOnly, secure cookie attribute Relationships in SQLite Relationships in SQL One-to-One: Each record in TABLE 1 is related to one record in TABLE 2 One-to-Many: Each record in TABLE 1 is related to one or more records in TABLE 2 A blog post has many comments, but each comment belongs to one blog post. Foreign keys and primary keys Primary key: A unique identifier for each record in a table (user_id, post_id) Foreign key: A column in a table that references the primary key of another table (user_id in posts table). Creating tables with relationships One user can have many posts Each post belongs to one user Store the user_id in the posts table Example: One-to-Many & Many-to-Many One-to-Many: A university has many courses, but each course belongs to one university. Many-to-Many: A student can enroll in many courses, and a course can have many students. Join table: A table that connects two other tables in a many-to-many relationship. Since a student can enroll in many courses and a course can have many students, we need a join table to represent this relationship. Joining tables Inner join: returns rows when there is a match in both tables. Use case: Get all courses with the university name. This matches rows in the courses table with rows in the universities table based on the university_id AI Tools & Deployment Artificial Intelligence (AI) AI: Artificial Intelligence - Simulation of human intelligence ML: Machine Learning - AI that enables machines to learn from data DL: Deep Learning - Neural networks that model and process data LLM: Large Language Models - AI models that can generate text and code AI Tools ChatGPT: Chat with AI models to get help or generate code GitHub Copilot: AI pair programmer that helps you write code Codeium: AI code editor that helps you write code ChatGPT ChatGPT: Chat with AI models to get help or generate code Use Cases: - Generate code: write javascript that... - Get help with code: explain this code like I'm 5 - Generate documentation: add comments to this code - Generate data: generate a json object with... GitHub Copilot GitHub Copilot: AI pair programmer that helps you write code Use Cases: - Write code faster: Autocompletes code for you - Get help: Use "fix with Copilot" to fix errors - Generate documentation: Use "generate documentation" to add comments Deployment Deployment: Publish your application online Use Cases: - Share your project with others - Get feedback from others - Showcase your skills to potential employers Tools: - GitHub Pages - Free hosting for static websites - Amazon Web Services - Hosting for all types of applications GitHub Pages GitHub Pages: Free hosting for static websites Static Website: Website with only HTML, CSS & JS - No backend Use Cases: - Showcase your projects - Share your portfolio - Host your blog Amazon Web Services (AWS) Amazon Web Services: Hosting for all types of applications Use Cases: Host your full-stack application Host your database Host your AI models Services: EC2: Virtual servers in the cloud S3: Object storage in the cloud RDS: Managed relational database service Next Steps What to learn next to become a great web developer React / NextJS ○ Build modern interactive web applications TypeScript ○ Write safer and more maintainable code MongoDB ○ Scaleable database for your applications React / NextJS React: JavaScript library for building user interfaces NextJS: Framework for building React applications Use Cases: Build modern web applications Build static websites Build server-side rendered websites Resources: React Documentation NextJS Documentation TypeScript TypeScript: Superset of JavaScript that adds types Use Cases: Write safer and more maintainable code Scale your codebase Improve developer experience Resources: TypeScript Documentation TypeScript Handbook MongoDB MongoDB: NoSQL database for modern applications Use Cases: Store and retrieve data for your applications Scale your database Use with Node.js, Python, and other languages Resources: MongoDB Documentation MongoDB University Future What's next in web development? AI & ML: More AI tools to help developers WebAssembly: Run code written in other languages in the browser Serverless: Run code without managing servers Blockchain: Secure and decentralized applications AR & VR: Augmented and Virtual Reality applications Voice & Chatbots: Voice and chat-based applications Quantum Computing: Solve complex problems faster WebAssembly WebAssembly: Run code written in other languages in the browser Use Cases: Run C, C++, Rust, and other languages in the browser Improve performance of web applications Build complex applications in the browser Resources: WebAssembly Documentation Serverless Serverless: Run code without managing servers Use Cases: Build scalable applications Pay only for what you use Focus on writing code instead of managing servers Resources: AWS Lambda Google Cloud Functions Blockchain Blockchain: Secure and decentralized applications Use Cases: Build secure applications Create decentralized applications Use smart contracts for transactions Resources: Ethereum Solana AR & VR AR & VR: Augmented and Virtual Reality applications Use Cases: Build immersive experiences Create training simulations Use in gaming and entertainment Resources: Unity Unreal Engine Voice & Chatbots Voice & Chatbots: Voice and chat-based applications Use Cases: Build voice assistants Create chatbots for customer service Use in healthcare, education, and other industries Resources: Dialogflow Amazon Lex Quantum Computing Quantum Computing: Solve complex problems faster Use Cases: Solve complex optimization problems Simulate quantum systems Use in cryptography and cybersecurity Resources: IBM Quantum Google Quantum AI Microsoft Quantum

Use Quizgecko on...
Browser
Browser