0% found this document useful (0 votes)
18 views

Node Express Mongo Notes

The document provides a comprehensive overview of Node.js, including its definition as a JavaScript runtime environment, its features such as non-blocking I/O and server-side capabilities, and its applications in web development. It also covers installation instructions for different operating systems, the importance of IDEs, and the creation of a basic Node server. Additionally, it discusses the request and response lifecycle in Node.js, including handling user input and routing requests.

Uploaded by

jay800440
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Node Express Mongo Notes

The document provides a comprehensive overview of Node.js, including its definition as a JavaScript runtime environment, its features such as non-blocking I/O and server-side capabilities, and its applications in web development. It also covers installation instructions for different operating systems, the importance of IDEs, and the creation of a basic Node server. Additionally, it discusses the request and response lifecycle in Node.js, including handling user input and routing requests.

Uploaded by

jay800440
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 406

Playlist Link

NodeJS
Complete Course
Introduction to NodeJS
1. Pre-requisites
2. What is NodeJS
3. NodeJs Features
4. JavaScript on Client
5. JavaScript on Server
6. Client Code vs Server Code
7. Other uses of NodeJs
8. Server architecture with NodeJs
JS is required for NodeJS
React is recommended before NodeJS
2.What is NodeJS

1. JavaScript Runtime: Node.js is an open-source,


cross-platform runtime environment for executing
JavaScript code outside of a browser.
2. NodeJs is a JavaScript in a different environment means
Running JS on the server or any computer.
3. Built on Chrome's V8 Engine: It runs on the V8 engine,
which compiles JavaScript directly to native machine
code, enhancing performance.
4. V8 is written in C++ for speed.
5. V8 + Backend Features = NodeJs
2.What is NodeJS
1. Design: Features an event-driven,
non-blocking I/O model for efficiency.
2. Full-Stack JavaScript: Allows using
JavaScript on both server and client
sides.
3. Scalability: Ideal for scalable network
applications due to its architecture.
4. Versatility: Suitable for web, real-time
chat, and REST API servers.
3. NodeJs Features
(Added)

1. Non-blocking I/O: Designed to perform non-blocking operations


by default, making it suitable for I/O-heavy operations.
2. Networking Support: Supports TCP/UDP sockets, which are
crucial for building lower-level network applications that
browsers can’t handle.
3. NodeJs Features
(Added)

1. File System Access: Provides APIs to read and write files directly,
which is not possible in browser environments for security
reasons.
2. Server-Side Capabilities: Node.js enables JavaScript to run on the
server, handling HTTP requests, file operations, and other
server-side functionalities.
3. Modules: Organize code into reusable modules using require().
3. NodeJs Features
(Removed)

1. Window Object: The global window object, which is part of web


browsers, is absent in Node.js.
2. DOM Manipulation: Node.js does not have a built-in Document Object
Model (DOM), as it is not intended to interact with a webpage's
content.
3. BOM (Browser Object Model): No direct interaction with things like
navigator or screen which are part of BOM in browsers.
3. NodeJs Features
(Removed)

Web-Specific APIs: APIs like localStorage, sessionStorage,


and browser-based fetch are not available in Node.js.
4. JavaScript on Client

1. Displays Web Page: Turns HTML code into what you


see on screen.
2. User Clicks: Helps you interact with the web page.
3. Updates Content: Allows changes to the page using
JavaScript.
4. Loads Files: Gets HTML, images, etc., from the
server.
5. JavaScript on Server
1. Database Management: Stores, retrieves, and manages
data efficiently through operations like CRUD (Create,
Read, Update, Delete).
2. Authentication: Verifies user identities to control access to
the system, ensuring that users are who they claim to be.
3. Authorization: Determines what authenticated users are
allowed to do by managing permissions and access
controls.
4. Input Validation: Checks incoming data for correctness,
completeness, and security to prevent malicious data entry
and errors.
5. Session Management: Tracks user activity across various
requests to maintain state and manage user-specific
settings.
5. JavaScript on Server
6. API Management: Provides and handles interfaces for
applications to interact, ensuring smooth data exchange and
integration.
7. Error Handling: Manages and responds to errors effectively to
maintain system stability and provide useful error messages.
8. Security Measures: Implements protocols to protect data from
unauthorized access and attacks, such as SQL injection and
cross-site scripting (XSS).
9. Data Encryption: Secures sensitive information by encrypting
data stored in databases and during transmission.
10. Logging and Monitoring: Keeps records of system activity to
diagnose issues and monitor system health and security.
6. Client Code vs Server Code
1. User/client can’t access server code directly.
2. Client must raise requests for particular APIs to
access certain features or data.
3. Environment Access: Server-side JavaScript
accesses server features like file systems and
databases.
4. Security: Server-side code can handle sensitive
operations securely, while client-side code is
exposed and must manage security risks.
5. Performance: Heavy computations are better
performed on the server to avoid slowing down
the client.
6. Client Code vs Server Code
6. Resource Utilization: Servers generally offer more
powerful processing capabilities than client
devices.
7. Data Handling: Server-side can directly manage
large data sets and database interactions, unlike
client-side JavaScript.
8. Asynchronous Operations: Server-side JavaScript is
optimized for non-blocking I/O to efficiently
manage multiple requests.
9. Session Management: Servers handle sessions and
user states more comprehensively.
10. Scalability: Server-side code is designed to scale
and handle requests from multiple clients
7. Other uses of NodeJs
1. Local Utility Scripts: Automates tasks and
processes files locally, like using shell scripts
but with JavaScript.
2. Internet of Things (IoT): Develops server-side
applications for IoT devices, managing
communications and data processing.
3. Scripting for Automation: Automates
repetitive tasks in software development
processes, such as testing and deployment.
7. Other uses of NodeJs

Real-Time Applications: Efficiently manages real-time data


applications, such as chat apps and live updates, using
WebSockets.
7. Other uses of NodeJs

Desktop Applications: Creates cross-platform desktop


applications using frameworks like Electron.
7. Other uses of NodeJs
Build Tools: Powers build processes
for front-end technologies using
tools like:
• Webpack
• Grunt
• Gulp
• Browserify
• Brunch
• Yeoman
8. Server architecture with NodeJs

Nodejs server will:


1. Create server and listen to incoming requests
2. Business logic: validation, connect to db, actual processing of data
3. Return response HTML, JSON, CSS, JS
Revision
• Click to edit Master text styles
1. Pre-requisites
• Second level
• Third level
2. What is NodeJS
• Fourth level
• Fifth level

3. NodeJs Features
4. JavaScript on Client
5. JavaScript on Server
6. Client Code vs Server Code
7. Other uses of NodeJs
8. Server architecture with NodeJs
2. Installation of NodeJS
1. What is IDE
2. Need of IDE
3. MAC Setup
• Install latest Node & VsCode
4. Windows Setup
• Install latest Node & VsCode
5. Linux Setup
• Install latest Node & VsCode
6. VsCode (Extensions and Settings)
7. Executing first .js file
8. What is REPL
9. Executing Code via REPL
2.1 What is IDE
1. IDE stands for Integrated
Development Environment.
2. Software suite that
consolidates basic tools
required for software
development.
3. Central hub for coding,
finding problems, and testing.
4. Designed to improve
developer efficiency.
2.2 Need of IDE
1. Streamlines development.
2. Increases productivity.
3. Simplifies complex tasks.
4. Offers a unified
workspace.
5. IDE Features
1. Code Autocomplete
2. Syntax Highlighting
3. Version Control
4. Error Checking
2.3 MAC Setup
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
2.3 MAC Setup
(Install latest Node)
Search Download NodeJS
2.3 MAC Setup
(Install VsCode)
• Click to edit Master text styles
Search VS Code on Google
• Second level
• Third level
• Fourth level
• Fifth level
2.4 Windows Setup
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
2.4 Windows Setup
(Install latest Node)
Search Download NodeJS
2.4 Windows Setup
(Install VsCode)
Search
• Click toVS
editCode
Master on
text Google
styles
• Second level
• Third level
• Fourth level
• Fifth level
2.5 Linux Setup
2.5 Linux Setup
(Install latest Node)
Search Download NodeJS
2.5 Linux Setup
(Install VsCode)
Search
• Click toVS
editCode
Master on
text Google
styles
• Second level
• Third level
• Fourth level
• Fifth level
2.6 VsCode
(Extensions and Settings)

1. Prettier (Format on Save)


2. Line Wrap
3. Tab Size from 4 to 2
2.7 Executing first .js file
1. Streamlines Node Command: Use node filename.js to
execute a JavaScript file in the Node.js environment.
2. Require Syntax: Use require('module') to include built-in
or external modules, or other JavaScript files in your
code.
3. Modular Code: require helps organize code into reusable
modules, separating concerns and improving
maintainability.
4. Caching: Modules loaded with require are cached,
meaning the file is executed only once even if included
multiple times.
2.8 What is REPL
1. Streamlines Interactive Shell: Executes
JavaScript code interactively.
2. Quick Testing: Ideal for testing and
debugging code snippets on the fly.
3. Built-in Help: Offers help commands via
.help.
4. Session Management: Supports saving
(.save) and loading (.load) code sessions.
5. Node.js API Access: Provides direct access
to Node.js APIs for experimentation.
6. Customizable: Allows customization of
prompt and behaviour settings.
2.9 Executing Code via REPL
Revision

1. • Click toisedit
What IDE Master text styles
• Second level
2. Need• Third
of level
IDE
• Fourth level
3. MAC Setup • Fifth level
• Install latest Node & VsCode
4. Windows Setup
• Install latest Node & VsCode
5. Linux Setup
• Install latest Node & VsCode
6. VsCode (Extensions and Settings)
7. Executing first .js file
8. What is REPL
9. Executing Code via REPL
3. First Node Server
1. How DNS Works?
2. How Web Works?
3. What are Protocols?
4. Node Core Modules
5. Require Keyword
6. Creating first Node Server
3.1 How DNS Works?
1. Domain Name Entry: User types a domain (e.g.,
www.example.com) into the browser.
2. DNS Query: The browser sends a DNS query to resolve
the domain into an IP address.
3. DNS Server: Provides the correct IP address for the
domain.
4. Browser Connects: The browser uses the IP to connect
to the web server and loads the website.
3.1 How DNS Actually Works?
1. Root DNS: Acts as the starting point for DNS resolution. It
directs queries to the correct TLD server (e.g., .com, .org).
2. TLD (Top-Level Domain) DNS: Handles queries for specific
top-level domains (e.g., .com, .net) and directs them to the
authoritative DNS server (e.g., Verisign for .com, PIR for .org)
3. Authoritative DNS: Contains the actual IP address of the
domain and answers DNS queries with this information.(e.g.,
Cloudflare, Google DNS).
3.2 How Web Works?
1. Client Request Initiation: The client (browser) initiates a
network call by entering a URL.
2. DNS Resolution: The browser contacts a DNS server to
get the IP address of the domain.
3. TCP Connection: The browser establishes a TCP
connection with the server's IP address.
4. HTTP Request: The browser sends an HTTP request to
the server.
5. Server Processing: The server processes the request and
prepares a response.
6. HTTP Response: The server sends an HTTP response back
to the client.
7. Network Transmission: The response travels back to the
client over the network.
8. Client Receives Response: The browser receives and
interprets the response.
9. Rendering: The browser renders the content of the
response and displays it to the user.
3.3 What are Protocols?
Http (HyperText Transfer Protocol):
● Facilitates communication between a web browser and a server to
transfer web pages.
● Sends data in plain text (no encryption).
● Used for basic website browsing without security.
HTTPS (HyperText Transfer Protocol Secure):
● Secure version of HTTP, encrypts data for secure communication.
● Uses SSL/TLS to encrypt data.
● Used in online banking, e-commerce.
TCP (Transmission Control Protocol):
● Ensures reliable, ordered, and error-checked data delivery over the
internet.
● Establishes a connection before data is transferred.
3.4 Node Core Modules
1. Built-in: Core modules are included
with Node.js installation.
2. No Installation Needed: Directly
available for use without npm
install.
3. Performance: Highly optimized for
performance.
3.4 Node Core Modules
1. fs (File System): Handles file operations like reading and
writing files.
2. http: Creates HTTP servers and makes HTTP requests.
3. https: Launch a SSL Server.
4. path: Provides utilities for handling and transforming file
5. paths.os: Provides operating system-related utility methods
and properties.
6. events: Handles events and event-driven programming.
7. crypto: Provides cryptographic functionalities like hashing and
encryption.
8. url: Parses and formats URL strings.
3.5 Require Keyword
1. Purpose: Imports modules in Node.js. Syntax:
2. Caching: Modules are cached after the const moduleName = require('module’);
first require call.
3. .js is added automatically and is not
needed to at the end of module name.
4. Path Resolution: Node.js searches for
modules in core, node_modules, and file
paths.
3.6 Creating first Node Server
3.6 Creating first Node Server
3.6 Creating first Node Server

Run the code with:

node app.js
3.6 Creating first Node Server
3.6 Creating first Node Server
Revision
• Click to edit Master text styles
1. How
• SecondDNSlevel
• Third level
Works?
2. How Web Works?
• Fourth level
• Fifth level

3. What are Protocols?


4. Node Core Modules
5. Require Keyword
6. Creating first Node Server
4. Request & Response

1. Node Lifecycle & Event Loop


2. How to exit Event Loop
3. Understand Request Object
4. Sending Response
5. Routing Requests
6. Taking User Input
7. Redirecting Requests
4.1 Node Lifecycle & Event Loop
4.2 How to exit Event Loop
4.3 Understand Request Object

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers
4.3 Understand Request Object

Use the browser to access:


http://localhost:3000/
http://localhost:3000/products
4.4 Sending Response
4.4 Sending Response
4.5 Routing Requests
4.5 Routing Requests
4.5 Routing Requests
4.6 Taking User Input
4.7 Redirecting Requests
Practise Set
Create a page that shows a navigation bar of
Myntra with the following links:
A. Home
B. Men
C. Women
D. Kids
E. Cart
Clicking on each link page should navigate to that
page and a welcome to section text is shown
there.
Revision
• Click to edit Master text styles
1. Node Lifecycle & Event Loop
• Second level
• Third level

2. How to exit Event Loop


• Fourth level
• Fifth level

3. Understand Request Object


4. Sending Response
5. Routing Requests
6. Taking User Input
7. Redirecting Requests
5. Parsing Request

1. Streams
2. Chunks
3. Buffers
4. Reading Chunk
5. Buffering Chunks
6. Parsing Request
7. Using Modules
5.1 Streams
5.1 Streams
5.2 Chunks
5.2 Chunks
5.3 Buffers
5.4 Reading Chunk
5.5 Buffering Chunks
5.6 Parsing Request
5.6 Parsing Request
5.7 Using Modules
5.7 Using Modules
Practise Set
Create a Calculator
1. Create a new Node.js project named “Calculator”.
2. On the home page (route “/”), show a welcome message and a
link to the calculator page.
3. On the “/calculator” page, display a form with two input fields
and a “Sum” button.
4. When the user clicks the “Sum” button, they should be taken to
the “/calculate-result” page, which shows the sum of the two
numbers.
○ Make sure the request goes to the server.
○ Create a separate module for the addition function.
○ Create another module to handle incoming requests.
○ On the “/calculate-result” page, parse the user input, use
the addition module to calculate the sum, and display the
result on a new HTML page.
Revision
• Click to edit Master text styles
1. Streams
• Second level
• Third level

2. Chunks • Fourth level


• Fifth level

3. Buffers
4. Reading Chunk
5. Buffering Chunks
6. Parsing Request
7. Using Modules
6. Event Loop
1. Event Driven
2. Single Threaded
3. V8 vs libuv
4. Node Runtime
5. Event Loop
6. Async Code
7. Blocking Code
6.1 Event Driven
6.2 Single Threaded
6.3 V8 vs libuv
V8:
1. Open-source JavaScript engine by Google.
2. Used in Chrome and Node.js.
3. Compiles JavaScript to native machine
code.
4. Ensures high-performance JavaScript
execution.

libuv:
1. Multi-platform support library for Node.js.
2. Handles asynchronous I/O operations.
3. Provides event-driven architecture.
4. Manages file system, networking, and
timers non-blockingly across platforms.
6.4 Node Runtime
6.4 Node Runtime
6.4 Node Runtime
6.4 Node Runtime
6.5 Event Loop
● timers: this phase executes callbacks
scheduled by setTimeout() and
setInterval().
● pending callbacks: executes I/O callbacks
deferred to the next loop iteration.
● idle, prepare: only used internally.
● poll: retrieve new I/O events; execute I/O
related callbacks (almost all with the exception
of close callbacks, the ones scheduled by
timers, and setImmediate()); node will
block here when appropriate.
● check: setImmediate() callbacks are
invoked here.
● close callbacks: some close callbacks, e.g.
socket.on('close', ...).
6.5 Event Loop
6.6 Async Code
6.6 Async Code
6.7 Blocking Code
6.7 Blocking Code
Run & Observe
Blocking vs Async
const fs = require('fs');

console.log('1. Start of script' );

// Synchronous (blocking) operation


console.log('2. Reading file synchronously' );
const dataSync = fs.readFileSync ('user-details.txt' , 'utf8');
console.log('3. Synchronous read complete' );

// Asynchronous (non-blocking) operation


console.log('4. Reading file asynchronously' );
fs.readFile('user-details.txt' , 'utf8', (err, dataAsync ) => {
if (err) throw err;
console.log('6. Asynchronous read complete' );
});

console.log('5. End of script' );


Run & Observe
Event Loop Sequence
console.log('1. Start of script');

// Microtask queue (Promise)


Promise.resolve().then(() => console.log('2. Microtask 1'));

// Timer queue
setTimeout(() => console.log('3. Timer 1'), 0);

// I/O queue
const fs = require('fs');
fs.readFile('user-details.txt', () => console.log('4. I/O operation'));

// Check queue
setImmediate(() => console.log('5. Immediate 1'));

// Close queue
process.on('exit', (code) => {
console.log('6. Exit event');
});

console.log('7. End of script');


Revision

1. • Click
Event to edit Master text styles
• Second levelDriven
• Third level
2. Single Threaded
• Fourth level
• Fifth level

3. V8 vs libuv
4. Node Runtime
5. Event Loop
6. Async Code
7. Blocking Code
7. NPM & Tools

1. Install Material Icons


2. npm init
3. npm Scripts
4. npm Packages
5. Installing Packages
6. Installing nodemon
7. Using nodemon
7.1 Install Material Icons
7.2 npm init
npm init
7.3 npm Scripts
npm start
npm run khul-ja-sim-sim
7.4 npm Packages

1. npm: Node.js package manager for code sharing.


2. Package: Reusable code or library.
3. package.json: Defines package metadata and
dependencies.
4. Versioning: Manages different package versions.
5. Local/Global: Install packages locally or globally.
6. Registry: Public storage for open-source packages.
7. Examples: Express, React, Lodash.
7.5 Installing Packages
npm install <package-name>

1. –save: Adds the package to the project’s dependencies in


package.json.
2. –save-dev: Adds the package to the project’s devDependencies
(used only in development) in package.json.
3. -g: Installs the package globally, making it available
system-wide, not just in a specific project.
4. –save-exact: Installs the exact version specified without
updating for newer versions.
5. –force: Forces npm to fetch and install packages even if they
are already installed.
7.6 Installing nodemon
npm install nodemon --save-dev

npm install
Recreates node_modules
7.7 Using nodemon

npm install nodemon -g


Revision
• Click to edit Master text styles
• Second level
1. Install
• Third levelMaterial Icons
• Fourth level

2. npm init • Fifth level

3. npm Scripts
4. npm Packages
5. Installing Packages
6. Installing nodemon
7. Using nodemon
8. Errors & Debugging

1. Types of Errors
2. Syntax Errors
3. Runtime Errors
4. Logical Errors
5. Using the Debugger
6. Debugger with Async Code
7. Restart Debug with nodemon
8.1 Types of Errors

1. Syntax Error: An error in the code’s structure, causing it to


not compile or run (e.g., missing semicolon).
2. Logical Error: The code runs but produces incorrect results
due to faulty logic (e.g., wrong formula).
3. Runtime Error: An error that occurs while the program is
running, often due to invalid operations
8.2 Syntax Errors
8.3 Runtime Errors
8.4 Logical Errors
8.5 Using the Debugger
Step 1 Step 3: Put a breakpoint

Step 2
8.5 Using the Debugger
Step 4: Use the tools Step 6: Debug Panel

Step 5: Hover
8.5 Using the Debugger
Step 7: Using Debug Console
8.6 Debugger with Async Code
8.7 Restart Debug with nodemon
Practise Set
Debug and fix Syntax, Runtime and Logical Errors
function calculateArea(width, height {
return width + height;
}

let width = 10 height = 5;

if (area > 100) {


console.log("The area is large.");
} else {
console.log("The area is small.");
}

if (width + height > 100) {


console.log("Area is greater than or equal to 100");
}
Revision
• Click to edit Master text styles
1. Types of Errors
• Second level
• Third level
• Fourth level

2. Syntax Errors
• Fifth level

3. Runtime Errors
4. Logical Errors
5. Using the Debugger
6. Debugger with Async Code
7. Restart Debug with nodemon
9. Starting with Express.js

1. What is Express.js
2. Need of Express.js
3. Installing Express.js
4. Adding Middleware
5. Sending Response
6. Express DeepDive
7. Handling Routes
9.1 What is Express.js
1. Express.js is a minimal and flexible
web application framework for
Node.js.
2. It provides a robust set of features
for building single-page,
multi-page, and hybrid web
applications.
3. Express.js simplifies server-side
coding by providing a layer of
fundamental web application
features.
9.2 Need of Express.js
1. Express.js Simplifies Server Creation: Helps in quickly
setting up and running a web server without the need
for complex coding.
2. Routing Management: Provides a powerful routing
mechanism to handle URLs and HTTP methods
effectively.
3. Middleware Support: Allows the use of middleware to
handle requests, responses, and any middle operations,
making code modular and maintainable.
4. API Development: Facilitates easy and efficient
creation of RESTful APIs.
5. Community and Plugins: Has a large ecosystem with
numerous plugins and extensions, accelerating
development time.
9.3 Installing Express.js
9.3 Installing Express.js
9.4 Adding Middleware
9.4 Adding Middleware
9.4 Adding Middleware
9.5 Sending Response
9.6 Express DeepDive
9.6 Express DeepDive
9.6 Express DeepDive
9.7 Handling Routes
9.7 Handling Routes
1. Order matters
2. Can not call next() after
send()
3. “/” matches everything
4. Calling res.send implicitly
calls res.end()
9.7 Handling Routes
9.7 Handling Routes
Practise Set

Create a new project.


1. Install nodemon and express.
2. Add two dummy middleware that logs request path
and request method respectively.
3. Add a third middleware that returns a response.
4. Now add handling using two more middleware that
handle path /, a request to /contact-us page.
5. Contact us should return a form with name and email
as input fields that submits to /contact-us page also.
6. Also handle POST incoming request to /contact-us
path using a separate middleware.
Revision
• Click to edit Master text styles
1. What
• Second levelis Express.js
• Third level

2. Need of Express.js
• Fourth level
• Fifth level

3. Installing Express.js
4. Adding Middleware
5. Sending Response
6. Express DeepDive
7. Handling Routes
10. Express.js DeepDive

1. Parsing Requests
2. Express Router
3. Adding 404
4. Common Paths
5. Adding HTML Files
6. Serving HTML Files
7. Using File Helper
10.1 Parsing Requests
10.2 Express Router
10.2 Express Router
10.2 Express Router
10.3 Adding 404
10.4 Common Paths

or
10.5 Adding HTML Files
10.6 Serving HTML Files
10.7 Using File Helper
Practise Set

Reuse the app from the last assignment


1. Parse the body of the contact-us request and log it to
console.
2. Move the code to separate local modules and use the
Express router to import and use them in app.js
3. Move all the html code to html files and serve them
using the file helper.
4. Also add a 404 page for this app.
Revision
• Click to edit Master text styles
1. Parsing
• Second level Requests
• Third level

2. Express Router
• Fourth level
• Fifth level

3. Adding 404
4. Common Paths
5. Adding HTML Files
6. Serving HTML Files
7. Using File Helper
11. Styling using

1. Serving Static Files


2. Introduction to Tailwind CSS
3. Utility Classes
4. Installing Extension
5. Including Tailwind CSS
6. Installing Tailwind CSS
7. Using Tailwind CSS
8. Building Tailwind Automatically
11.1 Serving Static Files
11.1 Serving Static Files
11.2 Introduction to Tailwind CSS
1. Responsive: Mobile-first design for all device sizes.
2. Utility-First: Provides low-level utility classes for
building custom designs.
3. Highly Customizable: Easily extendable through a
config file.
4. Responsive Design: Built-in responsive utilities (e.g.,
sm:, md:).
5. No Predefined Components: Focuses on building
custom components.
6. Purge CSS: Removes unused styles in production for
smaller files.
7. Fast Development: Style elements directly in markup
for speed.
11.3 Utility Classes
11.4 Installing Extension
11.4 Installing Extension
11.5 Including Tailwind CSS
11.6 Installing Tailwind CSS

1. Install:
npm init -y
npm install -D tailwindcss postcss autoprefixer
2. Initialize Tailwind CSS Config
npx tailwindcss init
11.6 Installing Tailwind CSS
Configure Tailwind in the Configuration Files (tailwind.config.js)
11.6 Installing Tailwind CSS

Add Tailwind Directives to views/input.css


11.6 Installing Tailwind CSS

5. Include public/output.css into your index.html


6. Run Command
npx tailwindcss -i ./views/input.css -o ./public/output.css --watch
7. Declare Shortcut:

8. Run Command
npm run tailwind
11.7 Using Tailwind CSS
11.8 Building Tailwind Automatically
Practise Set

Style other page using


Tailwind.
Revision
• Click to edit Master text styles
1. Serving
• Second level Static Files
• Third level

2. Introduction to Tailwind CSS


• Fourth level
• Fifth level

3. Utility Classes
4. Installing Extension
5. Including Tailwind CSS
6. Installing Tailwind CSS
7. Using Tailwind CSS
12. Dynamic UI using EJS

1. Need of Dynamic UI
2. Sharing using Global Variables
3. What is EJS
4. Installing EJS
5. Using EJS Templates
6. Working with Partials
12.1 Need of Dynamic UI
● Personalized Content: Tailors responses based on user
profiles, preferences, or behaviors to enhance user
experience.
● Dynamic Data Delivery: Provides real-time information
that updates with each request, such as live scores or
stock prices.
● Security and Access Control: Delivers different content
based on user authentication and authorization levels.
● Localization and Internationalization: Adjusts
responses to accommodate different languages, cultures,
or regional settings.
● API Versatility: Supports multiple client types (web,
mobile, IoT) by providing appropriate data formats and
structures.
12.2 Sharing using Global Variables

Variables are shared across


users
12.3 What is EJS
● HTML with JS: EJS lets you embed JavaScript
code within HTML.
● Simple Syntax: Uses <% %> for control flow and
<%= %> for output.
● Easy to Learn: Familiar to those who know
HTML and JavaScript.
● Template Reuse: Supports partials for reusing
code snippets.
● Flexible Logic: Allows full JavaScript expressions
in templates.
12.4 Installing EJS
12.4 Installing EJS
12.5 Using EJS Templates
12.6 Working with Partials
12.6 Working with Partials
12.6 Working with Partials
12.6 Working with Partials
Practise Set

Reuse the app from the last assignment


1. Add more fields in the add home page like price per
night, location, rating, photo.
2. Design the home card to show all of this information
3. Make the selected tab active on top.
Revision
• Click to edit Master text styles
1. Need
• Second levelof Dynamic UI
• Third level

2. Sharing using Global Variables


• Fourth level
• Fifth level

3. What is EJS
4. Installing EJS
5. Using EJS Templates
6. Working with Partials
13. Model View Controller
1. Separation of Concerns
2. Adding First Controller
3. Adding All Controllers
4. Adding 404 Controller
5. Adding Models
6. Writing data to Files
7. Nodemon causing problems
8. Reading data from Files
13.1 Separation of Concerns
● MVC stands for Model-View-Controller: A
software architectural pattern for developing
user interfaces.
● Model: Manages the data and business logic
of the application.
● View: Handles the display and presentation
of data to the user.
● Controller: Processes user input, interacts
with the Model, and updates the View
accordingly.
● Routes are a part of Controllers.
● Purpose: MVC separates concerns within an
application, making it easier to manage and
scale.
13.2 Adding First Controller
13.3 Adding All Controllers
13.3 Adding All Controllers
13.3 Adding All Controllers
13.4 Adding 404 Controller
13.5 Adding Models
13.5 Adding Models
13.6 Writing data to Files
13.6 Writing data to Files
13.7 Nodemon causing problems
13.8 Reading data from Files
13.8 Reading data from Files
Practise Milestone

Take your airbnb forward:


1. Structure the views folder into host & store and move the
respective view files there.
2. Add more views to store like: home-list, home-detail,
favourite-list, reserve, bookings. And to host view:
edit-home, host-home-list
3. Improve the header with navigation to all pages.
4. Register all the new routes and add dummy views there.
5. Change controllers to store and host setup.
6. Add Edit and Delete buttons to the host-home-list view.
7. Keep the logic for Edit, Delete, Favourite pending.
Revision

1. • Separation
Click to edit Master textof
• Second level
stylesConcerns

2. Adding First Controller


• Third level
• Fourth level
• Fifth level

3. Adding All Controllers


4. Adding 404 Controller
5. Adding Models
6. Writing data to Files
7. Nodemon causing problems
8. Reading data from Files
14. Dynamic Path & Model deep-dive

1. What are dynamic paths


2. Adding Home Details Page
3. Showing Real Home Data
4. Adding Favourites Feature
5. Adding Favourites Model
6. Edit-Home: Adding Feature Skeleton
7. Edit-Home: Showing Existing Data
8. Edit-Home: Handing Edit Request
9. Adding Delete Feature
10. Removing Home from Favourites
14.1 What are dynamic paths

● Path parameters are variables embedded directly in the URL


path to capture dynamic values, like /users/:userId where :userId
is replaced with a specific user ID.
● Query parameters are key-value pairs appended to the URL after
a ?, used to send additional data, like /search?query=nodejs
where query=nodejs specifies the search term.
14.2 Adding Home Details Page
1. Add a details button in /homes-list to go to link path /homes/:home-id
2. Add a random id to each home in the data file.
3. Add a random id on home object before saving in the home model.
4. Add a route in the store router for /homes/:home-id
5. Add a method in store controller to get the home-id using req.params
and log it, before sending out a dummy response with home id.
14.2 Adding Home Details Page
1.

2.

3.
14.2 Adding Home Details Page
4.

5.
14.3 Showing Real Home Data
1. Add a static findById method in Home model that takes a callback.
2. Use this findById method in the controller to load home details and log
them.
3. Now change the controller:
a. Redirect to /homes in case the home is not found, logging an error.
b. Rendering the /home-detail page with home data.
4. Create a home-detail page to use the entire page to show all home data.
5. Download from Github:
a. The styled home-detail file.
b. 10 image of homes that you can put locally and use.
14.3 Showing Real Home Data
1.

2.
14.3 Showing Real Home Data
3.
14.3 Showing Real Home Data
4. 5.
14.4 Adding Favourites Feature
1. Create a partial with a form and a button that submits to /favourites path
with a hidden input having home-id value.
2. Add this partial to home-detail page
3. Add this partial to home-list page.
4. Add router for handling POST request to /favourites path.
5. Add a method in store controller to add a home id as favourites, logging
the id for now, before redirecting to /favourites path.
14.4 Adding Favourites Feature
1.

2.
14.4 Adding Favourites Feature
3.
14.4 Adding Favourites Feature
4.

5.
14.5 Adding Favourites Model
1. Create a new Model to handle Favourites:
a. A static method getFavourites that reads the favourites.json file and
return the ids of all homes marked favourite.
b. A static method addFavourites that adds the home-id to favourites-id
array if not already there, then updates the file.
2. Use this model in addFavourites controller.
3. Use this model in getFavourites controller while also fetching details of
all homes from Homes Model.
4. Change the UI of favourites page to show new content.
14.5 Adding Favourites Model
1.
14.5 Adding Favourites Model
2.
14.5 Adding Favourites Model
3.
14.5 Adding Favourites Model
4.
14.6 Edit-Home:
Adding Feature Skeleton

1. Rename the add-home.ejs to edit-home.ejs


2. Fix it’s usage in the add-home controller.
3. Change the path of edit button everywhere.
4. Add a new router for GET /edit-home/:home-id
5. Add a new controller method in host controller, optionally logging
query param of editing=true, while passing editing flag to view.
14.6 Edit-Home: Adding Feature Skeleton

1.

2.
14.7 Edit-Home: Showing Existing Data

3.
14.6 Edit-Home: Adding Feature Skeleton

4.

5.
14.7 Edit-Home:
Showing Existing Data
1. Change the controller to now fetch the home details, if not found
redirect to /host/host-home-list otherwise passing the data to view.
2. Change the edit-home.ejs to show dynamic content based on values:
a. Different submit path.
b. Different button text.
c. Pre-filled values if present.
14.7 Edit-Home: Showing Existing Data

1.
14.7 Edit-Home: Showing Existing Data
2.
14.8 Edit-Home:
Handing Edit Request
1. Add a router for POST /edit-home
2. Add a controller for /edit-home, which creates a home model object
and saves it, before redirecting to /host/host-home-list
3. Add hidden id input field in the edit-home.ejs to get the id as part of
POST request.
4. Change the save method in Model to handle creation of new as well
as updation of existing Home.
14.8 Edit-Home: Handing Edit Request
1.

2.

3.
14.8 Edit-Home: Handing Edit Request
4.
14.9 Adding Delete Feature
1. Surround the delete button with a form that submits to path
/host/delete-home/:homeId
2. Add a route in the host routes.
3. Add a static delete method to the Home model that takes an id and deletes
the home.
4. Add a method in host controller to handle the request, delete the home and
redirect to /host/host-homes-list page.
5. Pending: deleted homes might still be in favourites list.
14.9 Adding Delete Feature
1.

2.

3.
14.9 Adding Delete Feature
4.
14.10 Removing Home from Favourites
1. Add a static method to the favourites model to delete the home.
2. Add a form to the favourites-list in each home to path
/favourites/delete/:homeId
3. Add a route for POST delete-favourites in the store routes.
4. Add a method in store controller to use the model’s static method and then
redirect to favourites-list.
5. Use this model method in home-delete to make sure any deleted home is
also removed from favourites.
14.10 Removing Home from Favourites
1.

2.

3.
14.10 Removing Home from Favourites
4.

5.
Revision
1. • What areMaster
Click to edit dynamic paths
text styles
• Second level
2. Adding Home Details Page
• Third level

3. Showing Real Home Data


• Fourth level
• Fifth level

4. Adding Favourites Feature


5. Adding Favourites Model
6. Edit-Home: Adding Feature Skeleton
7. Edit-Home: Showing Existing Data
8. Edit-Home: Handing Edit Request
9. Adding Delete Feature
10. Removing Home from Favourites
15. Introduction to SQL

1. What is a DB (Database)
2. Introduction to SQL DB
3. Introduction to NoSQL DB
4. SQL vs NoSQL
5. Installing MySQL
6. Connecting App to DB
7. Creating homes Table
8. Querying homes in App
9. Adding DB in Models
10. Adding Home in Model
11. Implementing Model using Where
15.1 What is a DB (Database)
1. Store Data: Keep large amounts of data in a structured format.
2. Enable Data Management: Allow for adding, updating, and deleting
data easily.
3. Facilitate Quick Access: Provide fast retrieval of data through
queries.
4. Ensure Data Integrity: Maintain accuracy and consistency of data
over time.
5. Support Multiple Users: Handle concurrent access by many users
simultaneously.
6. Secure Data: Protect information through access controls and
authentication.
15.2 Introduction to SQL DB
● Vertical Scalability: Typically scaled
by increasing the resources of a single
server (scaling up).
● Relationships: Tables can have
multiple types of relationships.

● Relational Model: Organize data into tables with rows and


columns.
● Fixed Schema: Require a predefined schema; the structure of
the data must be known in advance.
15.2 Introduction to SQL DB
● Relational Model Use of SQL: Utilize SQL for
querying and managing data, which is a
standardized and widely-used language.
● ACID Compliance: Support transactions that are
Atomic, Consistent, Isolated, and Durable.
● Complex Queries: Excel at handling complex
queries and relationships between data.
15.3 Introduction to NoSQL DB
● Flexible Schema: Allow for dynamic schemas,
accommodating unstructured or
semi-structured data without predefined
structures.
● Duplicacy over Relations: Duplicates data
across records (denormalization) to enhance
performance and scalability, rather than
relying on complex relationships and joins as in
relational databases.
● Horizontal Scalability: Designed to scale out by
adding more servers, handling large volumes of
data efficiently.
● Performance: Optimized for high throughput
and low latency, suitable for real-time
applications.
15.4 SQL vs NoSQL
15.4 SQL vs NoSQL
15.5 Installing MySQL
15.5 Installing MySQL
15.5 Installing MySQL
15.5 Installing MySQL
15.5 Installing MySQL
15.6 Connecting App to DB
15.7 Creating homes Table
15.7 Creating homes Table
15.7 Creating homes Table
15.8 Querying homes in App
15.9 Adding DB in Models
1. Remove the test code from app.js
2. Change the Home.js model file to remove all code related to file operations.
3. Import the DB from the utils.
4. Change photoUrl to imageUrl and houseName to name in the entire project.
5. Implement fetchAll:
a. Using the query we used while testing.
b. fetchAll will not take a callback but return a promise.
6. Go to StoreController and use the promise to get the data here.
7. Fix all the usages of fetchAll.
15.9 Adding DB in Models
2,3.
15.9 Adding DB in Models
5.

6.
15.9 Adding DB in Models
7.
15.10 Adding Home in Model
1. Add the description field in home. Change constructor and usage.
2. Make changes in UI to input and show it everywhere.
3. Implement the save method using the insert query.
4. Change the usages of save method to use the promise.
15.10 Adding Home in Model
1.
15.10 Adding Home in Model
2.
15.10 Adding Home in Model
3.

4.
15.11 Implementing Model using Where
Practise Milestone

Take your airbnb forward:


● Change the save method to support both edit and insert
functionality.
Practise Milestone (Solution)
Practise Milestone (Solution)
Revision

1. Click to edit
•What is aMaster text styles
DB (Database)
• Second level
2. Introduction
• Third level to SQL DB
• Fourth level
3. Introduction• Fifth level to NoSQL DB

4. SQL vs NoSQL
5. Installing MySQL
6. Connecting App to DB
7. Creating homes Table
8. Querying homes in App
9. Adding DB in Models
10. Adding Home in Model
11. Implementing Model using Where
16. Introduction to MongoDB
1. What is MongoDB
2. Setting up MongoDB
3. Installing MongoDB Driver
4. Creating MongoDB Connection
5. Saving a Home
6. Install MongoDB Compass
7. Install MongoDB for VSCode
8. Fetching all Homes
9. Fetching one Home
10. Supporting Edit & Delete
11. Adding MongoDB to Favourite
16.1 What is MongoDB
1. MongoDB is the product and the company that builds it.
2. The name comes from the work Humongous.
3. NoSQL Document Database: Stores data in flexible, JSON-like
documents.
4. Dynamic Schema: Allows fields to vary across documents without
predefined schemas.
5. High Performance: Optimized for fast read and write operations.
6. Scalability: Supports horizontal scaling through sharding.
7. High Availability: Provides replication with automatic failover.
8. Rich Query Capabilities: Offers powerful querying, indexing, and
aggregation.
9. Geospatial and Text Search: Includes support for location-based
and full-text queries.
10. Cross-Platform Compatibility: Works with various operating
systems and programming languages.
11. Easy Integration: Integrates smoothly with modern development
stacks.
16.2 Setting up MongoDB

VS
16.2 Setting up MongoDB
16.2 Setting up MongoDB
16.2 Setting up MongoDB
16.2 Setting up MongoDB
16.3 Installing MongoDB Driver
16.3 Installing MongoDB Driver
16.3 Installing MongoDB Driver
16.3 Installing MongoDB Driver
16.4 Creating MongoDB Connection
16.5 Saving a Home
16.6 Install MongoDB Compass
16.6 Install MongoDB Compass
16.6 Install MongoDB Compass
16.6 Install MongoDB Compass
16.6 Install MongoDB Compass
16.6 Install MongoDB Compass
16.7 Install MongoDB for VSCode
16.7 Install MongoDB for VSCode
16.7 Install MongoDB for VSCode
16.7 Install MongoDB for VSCode
16.7 Install MongoDB for VSCode
16.8 Fetching all Homes
1. Basic Usage: collection.find(query) retrieves
documents matching the query criteria.
2. Returns a Cursor: The method returns a
cursor, an iterator over the result set.
16.8 Fetching all Homes
16.9 Fetching one Home
16.9 Fetching one Home
16.9 Fetching one Home
16.9 Fetching one Home
16.10 Supporting Edit & Delete
16.11 Adding MongoDB to Favourite
1. Remove all the file handling related code from Favourite Model.
2. Delete the data folder.
3. Change the following methods in Favourite model to use mongo:
a. fetchAll
b. Change addToFavourites to save method
c. deleteById
4. Change the usages of Favourite model in StoreController to use the promise syntax
a. getFavourites
b. postAddFavourites
c. postRemoveFavourite
16.11 Adding MongoDB to Favourite

1. 2.
16.11 Adding MongoDB to Favourite

3.
16.11 Adding MongoDB to Favourite
4.a.
16.11 Adding MongoDB to Favourite
4.b.
16.11 Adding MongoDB to Favourite
4.c.
Practise Milestone

Take your airbnb forward:


● Change the favourite model to fix the problem of having
duplicate favourite records.
Practise Milestone (Solution)
Revision
1. •What is MongoDB
Click to edit Master text styles
• Second level
2. Setting
• Third levelup MongoDB
3. Installing
• Fourth level
MongoDB Driver
• Fifth level

4. Creating MongoDB Connection


5. Saving a Home
6. Install MongoDB Compass
7. Install MongoDB for VSCode
8. Fetching all Homes
9. Fetching one Home
10. Supporting Edit & Delete
11. Adding MongoDB to Favourite
17. Introduction to Mongoose

1. What is Mongoose
2. Setting up Mongoose
3. Create Home Schema
4. Saving Home using Mongoose
5. Fetching Homes
6. Fetching one Home
7. Editing a Home
8. Deleting a Home
9. Using Mongoose for Favourite
10. Fetching Relations
17.1 What is Mongoose

1. Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js.
2. Provides a schema-based solution to model application data.
3. Simplifies data validation and type casting in Node.js applications.
4. Enables easy interaction with MongoDB through intuitive methods.
5. Supports middleware for pre and post-processing of data.
6. Helps manage relationships between data with built-in functions.
17.2 Setting up Mongoose
17.2 Setting up Mongoose
1. Install Mongoose package.
2. Import and use mongoose in app.js
3. Delete the database-util file.
4. Remove the usage of db-util from everywhere.

1.
17.2 Setting up Mongoose

2.
17.3 Create Home Schema
1. Delete complete airbnb db from mongo.
2. Delete the existing Home Model code.
3. Create the new Home Schema in the Home Model File.
17.4 Saving Home using Mongoose
17.5 Fetching Homes
17.6 Fetching one Home

It already works !!!


17.7 Editing a Home
17.8 Deleting a Home
17.9 Using Mongoose for Favourite
1. Delete the existing Favourite Model code.
2. Create the new Favourite Schema in the Favourite Model File.
3. Fix the following functionalities:
a. Getting all Favourite
b. Adding A Favourite
c. Deleting a Favourite
4. Removing Favourite while removing home.
17.9 Using Mongoose for Favourite

1, 2.
17.9 Using Mongoose for Favourite

3.a.
17.9 Using Mongoose for Favourite

3.b.
17.9 Using Mongoose for Favourite

3.c.
17.9 Using Mongoose for Favourite

4.
17.10 Fetching Relations
Revision
1. •What is Master
Click to edit Mongoose
text styles
• Second level
2. Setting
• Third levelup Mongoose
• Fourth level
3. Create Home Schema
• Fifth level

4. Saving Home using Mongoose


5. Fetching Homes
6. Fetching one Home
7. Editing a Home
8. Deleting a Home
9. Using Mongoose for Favourite
10. Fetching Relations
18. Cookies & Sessions

1. What are Cookies


2. Adding Login Functionality
3. Checking Login State
4. Using a Cookie
5. Define the Logout Feature
6. Problem with Cookies
7. What are Sessions
8. Installing Session Package
9. Creating a Sessions
10. Saving Session in DB
18.1 What are Cookies

1. Cookies are small pieces of data stored in the user’s browser by


server.
2. They help websites remember user information and preferences
between page loads or visits.
3. Cookies can manage user sessions and store data for personalized
experiences.
18.1 What are Cookies
18.2 Adding Login Functionality
1. Add a login button to the nav bar pointing to /login
2. Create a auth router to handle login related routes, register the
new router in app.js
3. Create a auth controller to handle GET request for /login and
return a UI that does the following:
a. Accepts email and password
b. Has a Login button that submits the form to /login with a
POST request.
4. Add a POST login path in router and handler in controller.
5. Assume the person logged in and redirect them to the home page.
18.2 Adding Login Functionality

1.
18.2 Adding Login Functionality

2.
18.2 Adding Login Functionality

3.
18.2 Adding Login Functionality

3.
18.2 Adding Login Functionality

4, 5.
18.3 Checking Login State
1. Add a isLoggedIn field in the req object and use it everywhere
else.
2. Add a condition in the navigation ejs file that no path other
than home and login should be visible until a user has logged in.
3. Fix all the render calls to send the flag
4. Also add a middleware for host routes that if the user is not
logged in they should be redirected to the login page.
18.3 Checking Login State

1.
18.3 Checking Login State

2.
18.3 Checking Login State

3.
18.3 Checking Login State

4.
18.4 Using a Cookie
1. Understand why a global variable would not work.
2. Set a cookie on successful login. See it in storage, also on the
next request.
3. Read the cookie using syntax and Define a middleware to set
this value to the request object.
console.log(req.get('Cookie').split('=')[1]);

4. Change the Cookie from the browser and see the result.
18.4 Using a Cookie

2.

3.
18.4 Using a Cookie

4.
18.5 Define the Logout Feature
1. Define a logout button in nav bar that should come only when
user is logged in. Button should be a form that submits to link
/logout.
2. Hide the login button in case user is logged in.
3. Handle the logout path and set the isLoggedIn cookie to false.
18.5 Define the Logout Feature

1, 2.
18.5 Define the Logout Feature

3.
18.6 Problem with Cookies
1. Cookies can be intercepted or stolen, posing
security risks.
2. They have limited storage capacity (about
4KB).
3. Users can delete or modify cookies, leading
to data loss or tampering.
4. Data in cookies is not encrypted, making
sensitive information vulnerable.
5. Storing important info in cookies exposes it
to client-side attacks.
18.7 What are Sessions

1. Sessions are server-side storage mechanisms that track user


interactions with a website.
2. They maintain user state and data across multiple requests in a
web application.
3. Sessions enable persistent user experiences by maintaining state
between the client and server over stateless HTTP.
18.8 Installing Session Package
18.8 Installing Session Package
18.9 Creating a Session
1. Sensitive info is stored on server.
2. Same session is valid for all requests from one user, using
cookies.
3. Remove setting the cookie and now save the flag in session.
4. Check the browser for cookie changes.
5. Log Session in some get request.
6. Try to use a different browser and show that session is
different.
7. Sessions are stored in memory so they reset when server
restarts.
18.9 Creating a Sessions

3.

4.
18.9 Creating a Sessions

5.
18.10 Saving Session in DB
18.10 Saving Session in DB
Practise Milestone

Take your airbnb forward:


● Cleanup cookie code to use session everywhere.
● Remove the cookie middleware.
● Destroy the session on logout.
● Cleanup Logs.
● Understand why leaving the cookie on logout is fine.
Practise Milestone (Solution)
Revision
1. • Click
What to editare Cookies
Master text styles
• Second level
2. Adding • Third level Login Functionality
• Fourth level
3. Checking Login State
• Fifth level

4. Using a Cookie
5. Define the Logout Feature
6. Problem with Cookies
7. What are Sessions
8. Installing Session Package
9. Creating a Sessions
10. Saving Session in DB
19. Authentication & Authorization
1. What is Authentication
2. What is Authorization
3. Session based Authentication
4. Authentication vs Authorization
5. Signup UI
6. Using Express Validator
7. Adding User Model
8. Encrypting Password
9. Implementing Login
10. Adding User Functions
19.1 What is Authentication

1. Authentication is the process of verifying the identity of a user or


system accessing an application.
2. It ensures that only authorized users can access protected
resources and features.
3. Authentication is crucial for security, protecting data, and
providing personalized experiences in web applications.
19.2 What is Authorization
1. Authorization is the process of determining
what actions a user is permitted to
perform within an application.
2. It ensures that users can access only the
resources and functionalities they have
permission for.
3. Authorization enhances security by
restricting access to sensitive data and
operations, complementing the
authentication process.
19.3 Session based Authentication
19.4 Authentication vs Authorization
19.4 Authentication vs Authorization
19.5 Signup UI
1. Define a signup button in navigation bar along with sign-in. It should
point to a link /signup
2. Define a auth/signup.ejs file that has the following fields and
submits POST request to /signup:
a. firstName, lastName,
b. email
c. password, confirmPassword
d. userType with possible values ‘guest’, ‘host’
e. Terms and conditions checkbox.
3. Define routes in authRouter and behaviour in authController.
4. Fix the UI of the app to look pretty.
19.5 Signup UI

1.
19.5 Signup UI
2.
19.5 Signup UI

3, 4.
19.6 Using Express Validator
1. Add handling for POST /signup in auth controller and router.
2. Install Express Validator.
3. Use the email and password validations in the post handler.
4. Change the signup.ejs to show the errors. And accept the old
values.
19.6 Using Express Validator
1.

2.
19.6 Using Express Validator
3.
19.6 Using Express Validator
3.
19.6 Using Express Validator
4.
19.7 Adding User Model
1. Define a new User Model with following fields:
a. firstName & lastName (required)
b. email (required, unique)
c. Password (required)
d. userType (possible values ‘guest’, ‘host’)
2. In the POST signup handler, create a new user with the fields
from request and redirect to login after saving the user.
19.7 Adding User Model
1.
19.7 Adding User Model
2.
19.8 Encrypting Password
1. Understand the problem with plain text passwords.
2. Install a package named: bcryptjs
3. Hash the password before saving password.
4. Understand that even server does not have the password.
19.8 Encrypting Password
2.
19.8 Encrypting Password
3.
19.9 Implementing Login
1. Read the email and password from the request body and
find the user with the email from the Users collection.
2. If the user is not found send an error and re-render the
login page, also make changes to the login page to show
errors.
3. If the user is found, then use the bcrypt compare function
to match the entered password, If password does not
match send another error, otherwise create a login session
and redirect user to the home.
19.9 Implementing Login
1.
19.9 Implementing Login
2.
19.9 Implementing Login
3.
19.10 Adding User Functions
1. Make the navigation bar items display only on the basis of userType by
passing the user object to all views.
2. Add a field in User Model names favouriteHomes, which is an array of
home ids.
3. Remove the Favourite Model and the Pre hook from the Home Model.
4. Make the favourite user specific and change the following methods:
a. postAddFavourites
b. getFavourites
c. postRemoveFavourite
19.10 Adding User Functions
1.
19.10 Adding User Functions
2.
19.10 Adding User Functions
4.a.
19.10 Adding User Functions
4.b.
19.10 Adding User Functions
4.c.
Revision
1. •What is Master
Click to edit Authentication
text styles
• Second level
2. What is Authorization
• Third level

3. Session based Authentication


• Fourth level
• Fifth level

4. Authentication vs Authorization
5. Signup UI
6. Using Express Validator
7. Adding User Model
8. Encrypting Password
9. Implementing Login
10. Adding User Functions
Practise Milestone

Take your airbnb forward:


1. Add a field to Home model for a host user id.
2. Change the home creation to pass the current host id.
3. Change the UI of /host-homes to only use homes
belonging to the particular host.
Practise Milestone (Solution)

1.
Practise Milestone (Solution)

2.
Practise Milestone (Solution)

3.

You might also like