Advanced Node and Express Flashcards

1
Q

What is a template engine?

A

software tool that simplifies the process of generating dynamic content for web applications. It allows developers to create templates, which are essentially static HTML files with embedded placeholders for dynamic content. These placeholders can be replaced with actual data during runtime, enabling the creation of web pages that can adapt to different data sources or user inputs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What the first step in setting up a template engine?

A

npm install ‘template package’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

After installing the template engine, in your Express application, how would you configure it to use the template engine as the view engine?

A

// Set EJS as the view engine
app.set(‘view engine’, ‘ejs’);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

After setting the view engine, how do you set the directory for your views?

A

app.set(‘views’, ‘views’);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Where do you create template engine files?

A

in the directory specified by ‘app.set(‘views’, ‘views’), depending where you’ve set it to look in ex. views, create a file it that directory.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

After creating the views, where and how do you render the views?

A

-inside the route handlers
-by using the res.render()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is res.render()

A

method in Express is used to render a view/template and send the rendered HTML to the client in response to an HTTP request.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the syntax for res.render()?
and explain what each part does:

A

res.render(view, locals, callback)
-views= name of the view/template file to render
-locals= object containing local variables that will be passed to the view for rendering
-callback= callback function that will be called ionce the view rendering is complete

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Show an ex. on using res.render() for a ‘hello.ejs’ view, and also containing local variable ‘name’ being ‘John’:

A

app.get(‘/hello’, (req, res) => {
// Render the ‘hello.ejs’ view
res.render(‘hello’, { name: ‘John’ });
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is passport.js?

A

is a popular authentication middleware for Node.js applications ,that supports various authentication strategies, such as username and password, OAuth, and OpenID.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What various authentication strategies does passport.js support?

A

username and password, OAuth, and OpenID.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the main passport.js module?

A

passport

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is passport.js strategy for authenticating with a username and password?

A

passport-local

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is express middleware formanaging sessions?

A

express-session

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is library for hashing passwords securely?

A

bcrypt

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is passport?

A

an authentication middleware for Node.js. It is designed to serve a singular purpose—authenticate requests—and it does so in a modular way that allows you to apply different authentication mechanisms, known as strategies.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is passport-local?

A

a module that implements a local authentication strategy for Passport. The “local” part means that it uses a username (or email) and password for authentication.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is express-session?

A

middleware for Express that handles sessions. It provides session management capabilities and is essential for maintaining a persistent state across multiple pages, which is useful for keeping a user logged in as they navigate your application.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is bcrypt?

A

a library used to hash passwords. bcrypt provides a way to safely store and compare hashed passwords.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How do you configure express-session middleware?

A

app.use(session({
secret: process.env.SESSION_SECRET, // Change this to a random string
resave: false,
saveUninitialized: false
}));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How do you inialize passportand session support?

A

app.use(passport.initialize());
app.use(passport.session());

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Show a middleware for parsing incoming bodies:

A

app.use(express.urlencoded({ extended: true }));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is serialization of a user object?

A

is an essential aspect of authentication systems, particularly in web applications. It involves converting a user object into a format suitable for storage or transmission, typically for the purpose of session management.

24
Q

What is often used to store user information in a session after successful authentication and retrieves it on a subsequent requests to identify the authenticated user?

A

serialization

25
Q

Explain how serialization typically works in such systems:

A

After a user is authenticated, their user object is serialized. This typically involves extracting a unique identifier (such as the user’s ID) from the user object and storing it in the session. The serialized user object is then stored in the session store (e.g., memory, database).

26
Q

Explain how deserialization typically wrks in such systems:

A

On subsequent requests, the session middleware retrieves the serialized user object from the session store using the unique identifier stored during serialization. This serialized user object is then deserialized, typically by fetching the complete user object from the database based on the unique identifier.

27
Q

What happens to the complete user object once it is deserialized?

A

its attached to the request object (often as req.user)

28
Q

Show an example on how you would serialize the user object:

A

passport.serializeUser((user, done) => {
done(null, user.id); // Serialize by user ID
});

29
Q

Show an exaple on how you would deserialize the user object:

A

passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user); // Deserialize by fetching user from database
});
});

30
Q

What does passport.serializeUser do?

A

serializes the user object by extracting and storing its ID.

31
Q

What does passport.deserializeUser do?

A

deserializes the user object by fetching the complete user object from the database using the stored ID.

32
Q

What methods do you need to ensure that your model contains, when using the serialization and deserialization process?

A

methods for finding users by ID (findById) and validating passwords (validPassword)

33
Q

To ensure that your ‘Model’ contains methods for finding users by ID and validating passwords, whats one thing you can do?

A

define these methods within your “Model”

34
Q

To ensure that your ‘Model’ contains methods for finding users by ID and validating passwords, show an example on how it would look like using mongoose:

A

const mongoose = require(‘mongoose’);
const bcrypt = require(‘bcrypt’);
const Schema = mongoose.Schema;

// Define the user schema
const userSchema = new Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true }
});

// Method to validate a password
userSchema.methods.validPassword = function (password) {
return bcrypt.compareSync(password, this.password);
};

// Export the User model
const User = mongoose.model(‘User’, userSchema);

module.exports = User;

35
Q

What is a way for authenticating a user?

A

strategies

36
Q

Set up local strategy for passport by requiring the strategy and defining a new instance of local strateghy where you specify the authentication logic:

A

const passport = require(‘passport’);
const LocalStrategy = require(‘passport-local’).Strategy;

passport.use(new LocalStrategy(
(username, password, done) => {
myDataBase.findOne({ username: username }, (err, user) => {
console.log(User ${username} attempted to log in.);
if (err) {
return done(err);
}
if (!user) {
return done(null, false, { message: ‘Incorrect username.’ });
}
// Use the validPassword method we defined in the userSchema to check the password
if (!user.validPassword(password)) {
return done(null, false, { message: ‘Incorrect password.’ });
}
return done(null, user);
});
}
));

37
Q

To set up routes that will use the Passport strategy to authenticate users, create an endpoint that handle login requests and utilize Passports’s authenticate method:

A

const express = require(‘express’);
const router = express.Router();

// Assuming you’re using express
router.post(‘/login’, passport.authenticate(‘local’, {
successRedirect: ‘/dashboard’, // redirect to the secure dashboard section
failureRedirect: ‘/login’, // redirect back to the login page if there is an error
failureFlash: true // allow flash messages
}));

module.exports = router;

38
Q

After setting up routes using Passport Strategies to authenticate users, show how you would use that route in your app.js/server.js:

A

const express = require(‘express’);
const session = require(‘express-session’);
const passport = require(‘passport’);
const authRoutes = require(‘./routes/authRoutes’); // Assuming your authentication routes are defined in a separate file
const app = express();

// Initialize session and passport middleware
app.use(session({ secret: ‘someSecret’, resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());

// Mount the authentication routes at a specific path
app.use(‘/auth’, authRoutes);

// Other middleware and route handlers…
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(Server listening on port ${PORT});
});

39
Q

Create a middleware that checks if a user is authenticated before allowing access to certain routes:

A

function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { //checks if current user session is authenticated
return next();
}
res.redirect(‘/login’); //redirection occurs if not authenticated
}

40
Q

After creating a secure route middleware that checks if user is authentcated, show how you can use that on routes you want to protect:

A

app.get(‘/dashboard’, ensureAuthenticated, (req, res) => {
res.render(‘dashboard’, { user: req.user });
});

41
Q

Show how to render the profile view with the user’s username in the route handler for the profile page

A

app.get(‘/profile’, ensureAuthenticated, (req, res) => {
// Render the profile view and pass the user’s username
res.render(‘profile’, { username: req.user.username });
});

42
Q

What do you typically need to implement to log a user out using Passport.js?

A

need to provide a route that handles the logout operation

43
Q

Show how to implement logging a user out using Passport.js:

A

// Route for logging out
app.get(‘/logout’, (req, res) => {
req.logout(); // Passport.js provides a logout() method on the request object to clear the login session
res.redirect(‘/login’); // Redirect to the login page after logout
});

44
Q

What method provided by Passport.js is used to clear the login session and effectively log the user out?

A

req.logout()

45
Q

What redirects the user to the login page after they have been logged out?

A

res.redirect(‘/login)

46
Q

Create a error handler middleware, for missing pages (404), that catches any errors that occur during the request processing pipeline, sets the appropriate status code, and sends a simple ‘error’ message back to the client:

A

// Catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new Error(‘Not Found’);
err.status = 404;
next(err);
});

// Error handler
app.use((err, req, res, next) => {
// Set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get(‘env’) === ‘development’ ? err : {};
// Render the error page
res.status(err.status || 500);
// For simplicity, sending text, but you could render a view
if (err.status === 404) {
res.send(‘404: Page Not Found’);
} else {
res.send(‘error’);
}
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(Server listening on port ${PORT});
});

47
Q

Implement registration of a new user with MongoDB in your express application making sure the folllowing is also included:
1. Set up MongoDB connection
2. Create user schema
3. Handle registration POST request

A

const express = require(‘express’);
const bcrypt = require(‘bcrypt’);
const mongoose = require(‘mongoose’);
const app = express();

// Connect to MongoDB
mongoose.connect(‘mongodb://localhost:27017/myapp’, { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.on(‘error’, console.error.bind(console, ‘MongoDB connection error:’));
db.once(‘open’, () => {
console.log(‘Connected to MongoDB’);
});

// Define User Schema
const userSchema = new mongoose.Schema({
username: { type: String, unique: true, required: true },
email: { type: String, unique: true, required: true },
password: { type: String, required: true }
});
const User = mongoose.model(‘User’, userSchema);

// Set up body parser middleware to parse form data
app.use(express.urlencoded({ extended: true }));

// Registration form route (GET)
app.get(‘/register’, (req, res) => {
res.render(‘register’); // Assuming your EJS file is named register.ejs
});

// Registration route (POST)
app.post(‘/register’, async (req, res) => {
const { username, email, password } = req.body;
try {
// Check if user already exists
const existingUser = await User.findOne({ $or: [{ username }, { email }] });
if (existingUser) {
return res.status(400).send(‘Username or email already exists’);
}
// Hash the password
const hashedPassword = await bcrypt.hash(password, 10);
// Create new user
const newUser = new User({
username,
email,
password: hashedPassword
});
// Save user to the database
await newUser.save();
// Redirect to login page
res.redirect(‘/login’);
} catch (error) {
console.error(error);
res.status(500).send(‘Internal Server Error’);
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(Server listening on port ${PORT});
});

48
Q

What is one thing you can do to enhance security, when working with user authentication?

A

hash passwords

49
Q

What are two key areas you should handle hashing passwords?

A

-registration /saving a new account
-when verifying passwords during login

50
Q

When auser registers and creates a new account, you should hash their password before storing it in the database. Show how you can do this:

A

const bcrypt = require(‘bcrypt’);

// Assume req.body contains username, email, and password from the registration form
// Hash password before saving user data
bcrypt.hash(req.body.password, 10, (err, hashedPassword) => {
if (err) {
// Handle error
} else {
// Save user data to the database, including hashedPassword
User.create({
username: req.body.username,
email: req.body.email,
password: hashedPassword
}, (err, newUser) => {
if (err) {
// Handle error
} else {
// User registered successfully
res.redirect(‘/login’);
}
});
}
});

51
Q

When a user attempts to login, you should compare the provided password stored in the database. Show how you can do this:

A

// Assume req.body contains username/email and password from the login form

User.findOne({ username: req.body.username }, (err, user) => {
if (err) {
// Handle error
} else if (!user) {
// User not found
// Handle accordingly (e.g., show error message)
} else {
// Compare provided password with hashed password in the database
bcrypt.compare(req.body.password, user.password, (err, result) => {
if (err) {
// Handle error
} else if (result === true) {
// Passwords match, user authenticated
// Redirect to authenticated route or set session
res.redirect(‘/dashboard’);
} else {
// Passwords don’t match
// Handle accordingly (e.g., show error message)
}
});
}
});

52
Q

What function can you use to hash passwords before saving it?

A

bcrypt.hash()

53
Q

What function can you use to verify the password during login?

A

bcrypt.compare()

54
Q

To implement password hashing in your authentication straegy, where whould you integrate it into?

A

strategy’s logic

55
Q

Show how you can modify the LocalStrategy authentication strategy to handle password hashing:

A

const LocalStrategy = require(‘passport-local’).Strategy;
const bcrypt = require(‘bcrypt’);

// Assuming User model is imported and available
passport.use(new LocalStrategy(
(username, password, done) => {
User.findOne({ username: username }, (err, user) => {
if (err) { return done(err); }
if (!user) { return done(null, false, { message: ‘Incorrect username.’ }); }
// Compare provided password with hashed password in the database
bcrypt.compare(password, user.password, (err, result) => {
if (err) { return done(err); }
if (result) {
return done(null, user);
} else {
return done(null, false, { message: ‘Incorrect password.’ });
}
});
});
}
));

56
Q
A