Podcast
Questions and Answers
Which of the following is a key difference between sessions and cookies?
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.
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?
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.
The express-session
middleware stores session data in ______ by default, which is not suitable for production environments.
Match the session data storage method with its characteristic:
Match the session data storage method with its characteristic:
Which of the following is a potential drawback of using cookies for storing session data?
Which of the following is a potential drawback of using cookies for storing session data?
Using npm install express-session
command installs the necessary plugin to use sessions in a Node.js application.
Using npm install express-session
command installs the necessary plugin to use sessions in a Node.js application.
In Node.js with Express, what middleware is commonly used to enable session management?
In Node.js with Express, what middleware is commonly used to enable session management?
When using the express-session
middleware, the secret
option is used for ______ the session ID cookie.
When using the express-session
middleware, the secret
option is used for ______ the session ID cookie.
Match each express-session
option with its description:
Match each express-session
option with its description:
In the provided code snippets, what is the purpose of req.session.destroy()
?
In the provided code snippets, what is the purpose of req.session.destroy()
?
If a user logs in and the session is correctly established, accessing the login page again should still require entering credentials.
If a user logs in and the session is correctly established, accessing the login page again should still require entering credentials.
What does the maxAge
property within the cookie
object in the express-session
configuration specify?
What does the maxAge
property within the cookie
object in the express-session
configuration specify?
The memorystore
package is used to prevent ______ by storing session data in memory in a more efficient way.
The memorystore
package is used to prevent ______ by storing session data in memory in a more efficient way.
Match each action to the piece of code that performs it:
Match each action to the piece of code that performs it:
In the context of session management, what is a 'session store'?
In the context of session management, what is a 'session store'?
Using a session store like MemoryStore completely eliminates the risk of session data loss.
Using a session store like MemoryStore completely eliminates the risk of session data loss.
What is a typical use case for storing session data in a database instead of in-memory?
What is a typical use case for storing session data in a database instead of in-memory?
To ensure that session data is not lost when the server restarts, it is recommended to store sessions in a ______.
To ensure that session data is not lost when the server restarts, it is recommended to store sessions in a ______.
Match the code snippet with its description.
Match the code snippet with its description.
According to the provided code, what is the purpose of the /user
route?
According to the provided code, what is the purpose of the /user
route?
The code snippet res.status(401).send("No user info")
indicates a successful retrieval of user information.
The code snippet res.status(401).send("No user info")
indicates a successful retrieval of user information.
What HTTP status code is used to indicate 'Login failed'?
What HTTP status code is used to indicate 'Login failed'?
The express.static
middleware is used to serve ______ files such as CSS, images, and JavaScript.
The express.static
middleware is used to serve ______ files such as CSS, images, and JavaScript.
Match each code snippet with its function.
Match each code snippet with its function.
What does the following line of code accomplish: const username = formLogin ['txtUsername'].value;
?
What does the following line of code accomplish: const username = formLogin ['txtUsername'].value;
?
It is safe to store passwords directly in a database without encryption.
It is safe to store passwords directly in a database without encryption.
What library is used to encrypt passwords?
What library is used to encrypt passwords?
When bcrypt's compare
function returns true
, it means that entered password ______ password in database.
When bcrypt's compare
function returns true
, it means that entered password ______ password in database.
Match the action performed in the code snippets with the user type that is allowed to perform that action.
Match the action performed in the code snippets with the user type that is allowed to perform that action.
What middleware helps with serving static files?
What middleware helps with serving static files?
If a user has an active session, accessing the root route ('/') will always redirect them to the login page.
If a user has an active session, accessing the root route ('/') will always redirect them to the login page.
What does location.replace(data)
do?
What does location.replace(data)
do?
HTTP is a ______ protocol.
HTTP is a ______ protocol.
Match the definition with its description.
Match the definition with its description.
Which of the following is likely the least secure storage for session data?
Which of the following is likely the least secure storage for session data?
The term web system
has only one member.
The term web system
has only one member.
According to the texts, why can sessions increase web security?
According to the texts, why can sessions increase web security?
The term web application refers to a ______ system.
The term web application refers to a ______ system.
Match the following code with the file where it is likely to be found:
Match the following code with the file where it is likely to be found:
Flashcards
Session
Session
A technique to keep user's state and data for the server to remember.
Application memory for sessions
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
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
Creating sessions
Signup and view all the flashcards
'express-session'
'express-session'
Signup and view all the flashcards
req.session.destroy()
req.session.destroy()
Signup and view all the flashcards
Default session storage
Default session storage
Signup and view all the flashcards
MemoryStore
MemoryStore
Signup and view all the flashcards
Session
Session
Signup and view all the flashcards
Protect Backend Routes
Protect Backend Routes
Signup and view all the flashcards
Session's Usage for the Front End
Session's Usage for the Front End
Signup and view all the flashcards
Session and 'memory leak'
Session and 'memory leak'
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.