Skip to content

Instantly share code, notes, and snippets.

@hiba-machfej
Last active May 2, 2024 16:53
Show Gist options
  • Save hiba-machfej/87e0718999b9401808e63ad976d5534f to your computer and use it in GitHub Desktop.
Save hiba-machfej/87e0718999b9401808e63ad976d5534f to your computer and use it in GitHub Desktop.

Awsome Todos questions and answers guide:

Main questions:

1- What is passport-google-oauth20?

2- Why do we use cookieParser and encryptCookieNodeMiddleware ?

3- How do you let Express app use cookie middlewares (cookieParser, encryptCookieNodeMiddleware) with secret key for handling encryption of cookies *(answer might require code snippets)?

4- How to let your Express app use a middleware function that sends 401 (When not authenticated) error response code for auth errors and 500 (other errors) *(answer might require code snippets)?

5- In the auth.js there is four paths: /google, /me, /google/callback, /logout can you guess what does each path refer too?

Questions to answer while coding for later (not part of the discussion, answer individually later):

6- How do you let your Express app use JWT middleware to be used on all routes starting with /api?

a. How to exclude certain paths from the JWT authentication?

b. How to extract the JWT token from the request?

7- How do you Prepare Google Auth handling configuration?

8- How do you connect and configure Google OAuth 2.0 strategy on PassportJS instance?

9- How do you initialize PassportJS middleware?

@HalwestEast
Copy link

HalwestEast commented May 2, 2024

  1. This module lets you authenticate using Google in your Node.js applications.
  2. cookie parser: Parses the cookie data to extract individual values such as the cookie name, value, and expiration date
  3. By importing cookieParser in our express app. unfortunately I don't know how to write the code for it
  4. The 401 status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. further studying is required as to how to implement this feature in an express app.
  5. ???

Halwest.

@RafeefThamer
Copy link

1- passport-google-oauth20 is a part of Passport.js, used for integrating Google OAuth 2.0 authentication into Node.js apps. It simplifies user authentication via Google accounts by handling the authentication process, token exchange, and user profile retrieval.

2- cookieParser is middleware in Node.js to parse cookies from HTTP request headers. It populates req.cookies, easing cookie handling.
encryptCookieNodeMiddleware encrypts cookies for enhanced security, preventing tampering or unauthorized access.

3- To let an Express app use cookie middlewares such as cookieParser and encryptCookieNodeMiddleware with a secret key for handling encryption of cookies, you need to follow these steps:

Install necessary packages: You need to install cookie-parser middleware for parsing cookies and any encryption middleware you're using for encrypting cookies.
Configure middleware: Set up the middleware in your Express app to use cookieParser and any encryption middleware with your secret key.
snippets:
const express = require('express');
const cookieParser = require('cookie-parser');
const encryptCookie = require('cookie-encrypter');

const app = express();

app.use(cookieParser());

const secretKey = 'yourSecretKeyHere';

app.use(encryptCookie(secretKey));

app.get('/', (req, res) => {
// Access cookies
console.log(req.cookies);
res.send('Hello World!');
});

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

4- checkAuth middleware checks authentication. If not authenticated, it sends a 401 response.
Error handling middleware catches any errors and sends a 500 response.
/protected route demonstrates using checkAuth middleware. If authenticated, it sends a success response.

5- /google: Initiates Google OAuth authentication.
/me: Retrieves authenticated user information.
/google/callback: Callback URL for successful Google OAuth authentication.
/logout: Logs the user out and revokes access tokens.

Rafeef Thamer, Aras Yousef, Jwan Kareem

@papula-a
Copy link

papula-a commented May 2, 2024

Papula Azad | Afeaa Khudur | Yousra Yaarob | Hana Abdulla

  1. a module that allows Node.js applications to authenticate with Google using the OAuth 2.0 API. It can be integrated into any application or framework that supports Connect-style middleware, including Express.

  2. cookieParser is used to parse cookies from incoming HTTP requests in Express.js, while encryptCookieNodeMiddleware encrypts cookies for enhanced security. Together, they provide a secure and efficient way to handle cookies in web applications.

  3. const express = require('express');
    const cookieParser = require('cookie-parser');
    const encryptCookieNodeMiddleware = require('encrypt-cookie-node');

const app = express();
const secretKey = 'yourSecretKeyHere'; // Replace this with your actual secret key

// Middleware to parse cookies
app.use(cookieParser());

// Middleware to encrypt cookies
app.use(encryptCookieNodeMiddleware(secretKey));

// Example route to set a cookie
app.get('/set-cookie', (req, res) => {
res.cookie('user', 'john', { signed: true }); // Use signed cookie
res.send('Cookie has been set');
});

// Example route to get a cookie
app.get('/get-cookie', (req, res) => {
console.log('Signed Cookies: ', req.signedCookies); // Access signed cookie
console.log('Cookies: ', req.cookies); // Access regular cookie
res.send('Check the console for cookies');
});

// Start the server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});

  1. /google: Initiates the authentication process using Google OAuth.
    /me: Retrieves the authenticated user's profile information.
    /google/callback: Handles the callback from Google after authentication.
    /logout: Logs the user out of the application.

@Mardin-luqman2001
Copy link

Mardin-luqman2001 commented May 2, 2024

Ibrahim Muhaned, Mardin Luqman, Mawj M.Basheer , Elaf Gardi

1- passport-google-oauth20 is a Node.js module for easily adding Google OAuth 2.0 authentication to your application. It simplifies the process of integrating Google authentication into Node.js apps by handling the OAuth flow and providing a configurable strategy for authentication.

2-cookieParser is a middleware for Express.js that parses cookies attached to the client's request object. It populates req.cookies with an object keyed by the cookie names. encryptCookieNodeMiddleware, as the name suggests, is likely a custom middleware used for encrypting cookies for enhanced security.

3- To let an Express app use cookie middlewares like cookieParser and encryptCookieNodeMiddleware with a secret key for handling encryption of cookies, you need to do the following:
A. Install the necessary middleware packages:
npm install cookie-parser cookie-encrypter

B. Require the middleware packages in your Express app:
const express = require('express');
const cookieParser = require('cookie-parser');
const encryptCookieNodeMiddleware = require('cookie-encrypter');
C. Set up the cookie parser middleware with a secret key:
const app = express();
app.use(cookieParser('your-secret-key'));
D. Set up the cookie encryption middleware with the same secret key:
app.use(encryptCookieNodeMiddleware('your-secret-key'));

4- It will be better to return 401 - Unauthorized if the token is invalid or if missing the header by default. We can also provide a fail callback, so the user can customize like this:
app.use(express.jwt({
fail: function (req, res, next) {
if (!req.headers.authorization) res.send(400, 'missing authorization header');
res.send(401);
}
}));

5-
A. /google: This path is likely the route for initiating the Google OAuth 2.0 authentication process. When a user accesses this route, they are redirected to Google's authentication page where they can sign in with their Google account.

B. /me: This path might be used to retrieve information about the currently authenticated user. Once a user is authenticated through Google OAuth, they might be redirected to this route to display their profile or perform other authenticated actions.

C. /google/callback: This path is typically the callback URL used by the OAuth 2.0 authentication process. After the user has authenticated with Google, Google redirects the user back to this URL along with an authorization code. The server then exchanges this code for an access token.

D. /logout: This path is likely used to log the user out of the application. When a user accesses this route, their session is terminated, and they are redirected to a logged-out state or another page, such as the home page.

@r0deo
Copy link

r0deo commented May 2, 2024

Ali, Aween, Ara, Maram, Sarah, Zainab Al-Najjar, Zainab Mirza

  1. it's basically a middleware that used by the developers inside node.js to provide more authentications to the user info, so instead of making a new account on the specific website the users can use their google accounts to reach the whole website
    2In simple terms, cookieParser helps to read cookies from the incoming HTTP requests, while encryptCookieNodeMiddleware is a custom security measure to encrypt the cookie data, making it more secure and protecting sensitive information stored in cookies.

3.install the package itself with this command : npm install cookie-parser cookie-encrypter
|||B.|||Set up cookieParser middleware:
const express = require('express');
const cookieParser = require('cookie-parser');

const app = express();

app.use(cookieParser('yourSecretKeyHere'));
}

|||C|||Set up encryptCookieNodeMiddleware:

const { encryptCookie, decryptCookie } = require('cookie-encrypter');

app.use((req, res, next) => {
// Encrypt cookie before sending it to the client
res.encryptCookie = encryptCookie.bind(null, 'yourSecretKeyHere');
// Decrypt cookie received from the client
req.decryptCookie = decryptCookie.bind(null, 'yourSecretKeyHere');
next();
});

||D|| Using the encrypted cookies:
app.get('/setcookie', (req, res) => {
const encryptedValue = res.encryptCookie('cookieName', 'cookieValue');
res.cookie('cookieName', encryptedValue);
res.send('Cookie set successfully');
});

||f||Accessing decrypted cookies:
app.get('/getcookie', (req, res) => {
const decryptedValue = req.decryptCookie(req.cookies.cookieName);
res.send('Decrypted cookie value: ' + decryptedValue);
});

  1. Create a middleware function in Express that checks for authentication, and if authentication fails, it sends a 401 status code, and for other errors, it sends a 500 status code.
    // Define your authentication middleware function
    const authenticate = (req, res, next) => {
    // Check if authentication logic fails (you would replace this with your own authentication logic)
    const isAuthenticated = checkAuthentication(req);

    if (!isAuthenticated) {
    // If not authenticated, send 401 error
    return res.status(401).json({ error: "Unauthorized. Authentication required." });
    } else {
    // If authenticated, proceed to the next middleware
    next();
    }
    };

// Define your error handling middleware
const errorHandler = (err, req, res, next) => {
// If the error is not a 401, send a 500 status code
if (err.status !== 401) {
return res.status(500).json({ error: "Internal Server Error" });
}

// If the error is a 401, send the error message
res.status(401).json({ error: err.message });

};

// Register the middleware globally
app.use(authenticate);
app.use(errorHandler);

  1. /google - Initiates the Google login process.
    /google/callback - Handles the response from Google after login.
    /me - Retrieves the logged-in user's profile information.
    /logout - Logs the user out of the application.

@Adamciv
Copy link

Adamciv commented May 2, 2024

1- passport-google-oauth20 is a Node.js authentication middleware for Passport, which is an authentication middleware for Node.js. Specifically, passport-google-oauth20 allows you to authenticate users using Google OAuth 2.0 in your Node.js applications. With this middleware, you can easily integrate Google's OAuth 2.0 authentication mechanism into your application, allowing users to log in with their Google accounts. This is commonly used in web applications to provide users with a convenient and familiar way to sign in without requiring them to create and manage separate login credentials for your application.

2- Using cookieParser and encryptCookieNodeMiddleware together provides a secure and convenient way to work with cookies in Node.js applications, ensuring both ease of use and protection of sensitive data

3- To enable an Express app to handle cookies securely with encryption using cookie-parser and express-encrypt-cookie middlewares:

Install the required packages: cookie-parser and express-encrypt-cookie.
Configure cookie-parser middleware to parse cookies, providing a secret key for cookie encryption.
Configure express-encrypt-cookie middleware to encrypt and decrypt cookies, using the same secret key.
Ensure that these middlewares are added to your Express app before any route handling.
Your app is now set up to handle cookies securely with encryption.

4- To enable your Express app to handle authentication errors with a 401 response code and other errors with a 500 response code, create a custom error handling middleware. This middleware checks the error type and sends the appropriate response code and message accordingly. Then, add this middleware to your Express app after other middleware and route handlers.

5- /google: Initiates Google OAuth 2.0 authentication.
/me: Retrieves user information from the server.
/google/callback: Callback URL for Google OAuth authentication.
/logout: Logs out the user from the application.

Abdulrahman muayid
shvan abdulhakeem
ahmed isam
payam R
ahmed jalal

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment