Authorization Using Sessions

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

Which of the following is a key difference between sessions and cookies?

  • Sessions can only store small amounts of data, while cookies can store large amounts.
  • Sessions are specific to a single route, while cookies are accessible across all routes.
  • Sessions are stored on the client-side, while cookies are stored on the server-side.
  • Sessions are stored on the server-side, while cookies are stored on the client-side. (correct)

Sessions, by default, are designed to persist indefinitely, ensuring data is retained even if the server restarts.

False (B)

What is the primary purpose of using sessions in web applications?

store user state and data

The express-session middleware stores session data in ______ by default, which is not suitable for production environments.

<p>server memory</p>
Signup and view all the answers

Match the session data storage method with its characteristic:

<p>Application memory = Simplest method, consumes server memory, data lost on crash, mostly for development Memory cache = Fast access, volatile, suitable for non-critical data Cookies = Popular, bandwidth intensive, limited size (around 4KB), security concerns File or Database = Persistent storage, suitable for production, less complex than memory cache</p>
Signup and view all the answers

Which of the following is a potential drawback of using cookies for storing session data?

<p>Cookies are limited in size, typically around 4KB. (B)</p>
Signup and view all the answers

Using npm install express-session command installs the necessary plugin to use sessions in a Node.js application.

<p>True (A)</p>
Signup and view all the answers

In Node.js with Express, what middleware is commonly used to enable session management?

<p>express-session</p>
Signup and view all the answers

When using the express-session middleware, the secret option is used for ______ the session ID cookie.

<p>signing</p>
Signup and view all the answers

Match each express-session option with its description:

<p><code>secret</code> = String used to sign the session ID cookie <code>resave</code> = Forces the session to be saved back to the session store, even if it wasn't modified during the request <code>saveUninitialized</code> = Forces a session that is 'uninitialized' to be saved to the store <code>cookie</code> = Settings object for the session cookie (e.g., maxAge, secure)</p>
Signup and view all the answers

In the provided code snippets, what is the purpose of req.session.destroy()?

<p>It clears the current session data. (B)</p>
Signup and view all the answers

If a user logs in and the session is correctly established, accessing the login page again should still require entering credentials.

<p>False (B)</p>
Signup and view all the answers

What does the maxAge property within the cookie object in the express-session configuration specify?

<p>session duration</p>
Signup and view all the answers

The memorystore package is used to prevent ______ by storing session data in memory in a more efficient way.

<p>memory leaks</p>
Signup and view all the answers

Match each action to the piece of code that performs it:

<p>Install express-session = <code>npm install express-session</code> Install memorystore = <code>npm install memorystore</code> Redirect to homepage = <code>res.redirect(&quot;/&quot;);</code> Set cookie max age = <code>cookie: { maxAge: 24 * 60 * 60 * 1000 }</code></p>
Signup and view all the answers

In the context of session management, what is a 'session store'?

<p>A mechanism to persist session data beyond the default server memory. (B)</p>
Signup and view all the answers

Using a session store like MemoryStore completely eliminates the risk of session data loss.

<p>False (B)</p>
Signup and view all the answers

What is a typical use case for storing session data in a database instead of in-memory?

<p>scalability and performance</p>
Signup and view all the answers

To ensure that session data is not lost when the server restarts, it is recommended to store sessions in a ______.

<p>database</p>
Signup and view all the answers

Match the code snippet with its description.

<p>app.get('/logout', function (req, res) = Configures a route to handle user logout and clear the session. req.session.destroy (function (err) = Destroys the session, clearing all associated data. res.redirect('/'); = Redirects the user to the homepage app.use(session({ = Initializes session middleware with specified configuration options.</p>
Signup and view all the answers

According to the provided code, what is the purpose of the /user route?

<p>To retrieve the current user's session information. (A)</p>
Signup and view all the answers

The code snippet res.status(401).send("No user info") indicates a successful retrieval of user information.

<p>False (B)</p>
Signup and view all the answers

What HTTP status code is used to indicate 'Login failed'?

<p>401</p>
Signup and view all the answers

The express.static middleware is used to serve ______ files such as CSS, images, and JavaScript.

<p>static</p>
Signup and view all the answers

Match each code snippet with its function.

<p><code>express.json()</code> = Parses incoming requests with JSON payloads. <code>express.urlencoded({ extended: true })</code> = Parses incoming requests with URL-encoded payloads. <code>bcrypt.hash(password, 10, function (err, hash)</code> = Hashes a password using bcrypt <code>res.sendFile(path.join(__dirname, 'views/login.html'))</code> = Sends a file as an HTTP response</p>
Signup and view all the answers

What does the following line of code accomplish: const username = formLogin ['txtUsername'].value;?

<p>Retrieves the value entered in a form field with the name 'txtUsername'. (C)</p>
Signup and view all the answers

It is safe to store passwords directly in a database without encryption.

<p>False (B)</p>
Signup and view all the answers

What library is used to encrypt passwords?

<p>bcrypt</p>
Signup and view all the answers

When bcrypt's compare function returns true, it means that entered password ______ password in database.

<p>matches</p>
Signup and view all the answers

Match the action performed in the code snippets with the user type that is allowed to perform that action.

<p>Access the '/dashboard' route = Admin users (role == 1) Access the '/shop' route = User users (role == 2) Perform login = All users of the system Add product = Only admin can.</p>
Signup and view all the answers

What middleware helps with serving static files?

<p>express.static (D)</p>
Signup and view all the answers

If a user has an active session, accessing the root route ('/') will always redirect them to the login page.

<p>False (B)</p>
Signup and view all the answers

What does location.replace(data) do?

<p>forward to another page</p>
Signup and view all the answers

HTTP is a ______ protocol.

<p>stateless</p>
Signup and view all the answers

Match the definition with its description.

<p>cookie = a small piece of data that a server sends to the user's web browser. The browser may store it and send it back with later requests. session = a way to store information about the user across multiple pages of your website. localhost = a hostname that refers to the computer that it is running on. port = a virtual point where network connections start and end.</p>
Signup and view all the answers

Which of the following is likely the least secure storage for session data?

<p>application/server memory (A)</p>
Signup and view all the answers

The term web system has only one member.

<p>False (B)</p>
Signup and view all the answers

According to the texts, why can sessions increase web security?

<p>help prevent unauthorized access</p>
Signup and view all the answers

The term web application refers to a ______ system.

<p>real</p>
Signup and view all the answers

Match the following code with the file where it is likely to be found:

<p><code>const express = require(&quot;express&quot;);</code> = <code>app.js</code> <code>&lt;link rel=&quot;stylesheet&quot; href=&quot;/public/css/bootstrap.min.css&quot;&gt;</code> = <code>index-login.html</code> <code>const con = mysql.createConnection({</code> = <code>db.js</code> <code>&lt;button class=&quot;btn btn-danger&quot;&gt;Sign out&lt;/button&gt;</code> = <code>dashboard.html</code></p>
Signup and view all the answers

Flashcards

Session

A technique to keep user's state and data for the server to remember.

Application memory for sessions

Storing session data in application memory consumes server's memory and data is lost if the server crashes. Not recommended for production.

Cookie for sessions

A session data storage method; bandwidth is taken every time exchanging data occurs. Limited by cookie size and should pay concern to security.

Creating sessions

Sessions are created server-side and can store values shared across all back-end services.

Signup and view all the flashcards

'express-session'

A Node.js plugin used to manage sessions in a simple way.

Signup and view all the flashcards

req.session.destroy()

Clears the session variable, which redirects the user to the login page.

Signup and view all the flashcards

Default session storage

Stores sessions in the server's memory, which can lead to memory leaks in production.

Signup and view all the flashcards

MemoryStore

An effective technique for session storage that avoids memory leaks.

Signup and view all the flashcards

Session

A technique to remember something at the server side and is necessary for real web applications because a web system usually has several uses and it needs to keep track of each user.

Signup and view all the flashcards

Protect Backend Routes

Help prevent unauthorized people from calling the protected API services.

Signup and view all the flashcards

Session's Usage for the Front End

Allow accessing only permitted pages and remember the users until the session expires.

Signup and view all the flashcards

Session and 'memory leak'

It must handle 'memory leak' possibility and one technique to lessen that chance is to use 'session store'.

Signup and view all the flashcards

Study Notes

Authorization Using Sessions

  • Sessions are a technique to store user state and data on the server, similar to cookies, but server-side.
  • Sessions act like server variables, accessible across all routes in the server after creation.

Data Storage Options for Sessions

  • Application Memory
    • This is the simplest method.
    • It consumes server memory.
    • Data is lost if the server crashes.
    • It's primarily for development, not production.
  • Memory Cache
  • Cookie
    • This is a popular method.
    • It consumes bandwidth with every data exchange with the server.
    • It's limited by cookie size (around 4 KB).
    • Security should be a concern.
  • File or Database

Implementation

  • Sessions with application memory and files are preferred for their simplicity and practicality.
  • In Node.js, express-session is a plugin to simplify session use.
  • Installation is done via npm install express-session.

Session Usage

  • Sessions are created server-side.
  • They store values shared across all back-end services.
  • Example: remembering user info after login for use on another page.

Login/Welcome Page Example

  • Correct credentials ("admin"/"1111" or "user"/"2222") redirect to a welcome page.
  • The welcome page uses session data to display the user's ID and username.
  • Already logged-in users bypass the login page, redirecting to the welcome page.

app.js Configuration

  • Express, path, and express-session are required
  • The "public" folder is set as a static folder for direct user access.
  • Express.json() and express.urlencoded() are used for JSON exchange.
  • Session middleware configures session settings like cookie max age, secret code, resave, and saveUninitialized.

Login Route

  • Handles user login by checking username and password.
  • On successful login, keeps the username and userID in the session.
  • Redirects to the "/welcome" route.
  • Sends "Login failed" with a 401 status for incorrect credentials.

Logout Route

  • Clears the session variable using req.session.destroy().
  • Handles errors during session clearing, sending a 500 status if it fails.
  • Redirects to the homepage ("/") upon successful logout.

Get Username Route

  • Retrieves user information (userID and username) from the session.
  • Returns user data as JSON if a session exists.
  • Sends "No user info" with a 401 status if no session exists

Welcome Route

  • Checks for a session
  • Sends the "welcome.html" file
  • Otherwise redirects to "/"

Root Route

  • Checks if a user is already logged in via session.
  • Redirects logged-in users to "/welcome".
  • Serves "index.html" (login page) for non-logged-in users.

Client-Side Login Script

  • The login form prevents default submission
  • It retrieves username and password from input fields.
  • It sends a POST request via fetch with the user credentials.
  • It redirects to the welcome page upon successful login.
  • It displays an error message using SweetAlert2 for login failure or connection errors.

Logout Implementation

  • The logout button calls the /logout route which clears the session
  • This redirects to the login page

Session Stores

  • Default sessions are stored in server memory and are lost when the server is closed.
  • This creates memory leak
  • This can be solved with a session store (e.g. MemoryStore)
  • MemoryStore can be installed via npm install memorystore

Session Store Setup

  • After installation, require memorystore inside app.js
  • When calling app.use(session({...}) add store: new MemoryStore({...}) inside the object
  • Also add a checkPeriod with appropriate prune timings

Session with Database Example

  • Create a database called 'webpro' with two tables called 'user' and 'product'
  • 'user' will contain user information such as ID, username, password, and role
  • 'product' will contain product information such as ID, product name, price, amount, and image
  • Passwords in the database should me hashed with 'bcrypt'
  • When using the login functionality, the password in the database should be compared with the username from the user input
  • The database and table structure must be setup properly

Summary

  • Sessions are server-side
  • Sessions are necessary for keeping track of users
  • Sessions help increase web-security
  • Sessions can help prevent unauthorized users from calling APIs
  • Using sessions must handle the 'memory leak' possibility
  • It's possible to store sessions in databases, and configure roles

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Express
15 questions
Express Routing and Performance Quiz
17 questions
Preguntas sobre Node.js y Express
16 questions
Express Sessions and Authentication
10 questions
Use Quizgecko on...
Browser
Browser