Create a dedicated file for defining the passport strategy and ensure it is utilized consistently throughout the entire application

I've been grappling with this problem for quite some time now, but I just can't seem to wrap my head around how it functions.

There's a file named passport.ts in my project which looks something like this:

passport.serializeUser<any, any>((user, done) => {
    done(undefined, 1);
});

passport.deserializeUser((id, done) => {
    done(null, 1);
});

// Strategy config
const GoogleStrategy = passportGoogle.Strategy
passport.use(new GoogleStrategy({
    clientID: config.get('googleAuth.clientID'),
    clientSecret: config.get('googleAuth.clientSecret'),
    callbackURL: config.get('googleAuth.callbackURL'),
    passReqToCallback: true
}, async (accessToken, refreshToken, profile, done)=> {
    return done
}))

In the root directory of my project, there's an index.ts file that initializes passport in the standard way:

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

I'm setting up controllers using express's Router function in different files, one of them being authenticate.ts, which looks something like this:

import {Router} from 'express';
import passport from 'passport';
import config from 'config';
import * as passportConfig from '../utils/passport' //this is passport.ts mentioned above
const router = Router();

router.get('/google', passport.authenticate('google', {scope: config.get('googleAuth.scope')}));

I realize that I haven't included the callback route, and I've encountered difficulties while trying to make everything work because I'm not sure how to use the passport object defined in passport.ts with the strategy in different files.

Any assistance would be highly appreciated!

Answer №1

From what I gather, your goal is to separate and define your passport strategy in a distinct file for use. To achieve this, consider the following approach:

Create a new file to define your strategy named google-strategy.ts

const googleStrategy = new GoogleStrategy({
    clientID: config.get('googleAuth.clientID'),
    clientSecret: config.get('googleAuth.clientSecret'),
    callbackURL: config.get('googleAuth.callbackURL'),
    passReqToCallback: true
}, async (accessToken, refreshToken, profile, done)=> {
    return done
})
module.exports = googleStrategy;

In your passport.ts file

const googleStrategy = require('./google-strategy');
// Providing a name to the strategy for reference in routes
passport.use('MyGoogleStrategy', googleStrategy);

And in your authenticate.ts file

router.get('/google', passport.authenticate('MyGoogleStrategy', {scope: config.get('googleAuth.scope')}));

I hope this solution proves helpful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using the "OR" operator in regular expressions within express routing

When a user enters either "/" or "/home" path, I want them to be directed to the same page ("/home"). How can I achieve this using regex in express routing? I attempted the following code but it did not work: router.route('/|/home') ...

Utilizing LocalStorage with Angular 6 BehaviorSubject

I'm struggling with retaining data after refreshing a page. My approach involves using a shared service to transfer data between unrelated components. Despite extensive research on LocalStorage implementation and usage, I have not been able to find a ...

Is there a way to capture real-time console output in an ExpressJS application while a script is running?

I'm facing a challenge in integrating the output of a bash script into an ExpressJS application to then send the data to a client. To address this, I have developed a simplified version of my actual script for testing purposes. My goal is to capture a ...

Error setting headers in AMQP and Express communication

Attempting to send a message via the "input" queue on a POST request and then responding with res.json() after processing and receiving results through the "results" queue seems to work initially. However, upon making a second POST request and trying to ha ...

The issue of not being able to bind to 'formGroup' because it is not a recognized property of 'form' persisted despite trying solutions from other sources

I have followed the instructions in the guide but I am encountering issues. An error message stating the following is being displayed: Can't bind to 'formGroup' since it isn't a known property of 'form'. Another error occ ...

Error: The operation performed on the table has violated the foreign key constraint for TelephoneContact

Purpose Make sure that data is inserted into the telephones table when a new client is created. Situation I am working with 3 tables named clients, contacts, and telephones. The relationships between these tables are shown in the diagram. The owner_id ca ...

In order to showcase the data from the second JSON by using the unique identifier

SCENARIO: I currently have two JSON files named contacts and workers: contacts [ { "name": "Jhon Doe", "gender": "Male", "workers": [ "e39f9302-77b3-4c52-a858-adb67651ce86", "38688c41-8fda-41d7-b0f5-c37dce3f5374" ] }, { "name": "Peter ...

Position the text alongside the thumbnail rather than in the center

In the current setup, my username text is positioned in the center of the view. I want to reconfigure it so that it displays directly to the right of the thumbnail. However, removing the alignItems: 'center', property from the item disrupts the e ...

Using JQuery to Send Form Data with an Ajax POST Request

On my web Node/Express app, I have implemented a basic messaging service and am currently attempting to submit the form using Ajax with the FormData object. While the form submission works perfectly without Ajax, all the req.body values are undefined when ...

What is the syntax for assigning a public variable within a TypeScript function?

I am finding it challenging to assign a value to a public variable within another function. I seem to be stuck. export class MyClass{ myVar = false; myFunction(){ Module.anotherFunction(){ this.myVar = true; } } } ...

Creating a distinct folder for every upload in Node.js using multer and shortid

Utilizing shortid for unique IDs for each upload along with multer for the post handler. I am uploading some input data as well as an image and aiming to store each upload inside "upload/XXXXX". The unique ID is generated in the app.post(...) and I am see ...

Create an array containing the data returned from the Observable<{string, number, string}[]> stream

Currently I am working on creating an Angular 9 app, and I need to return an array with my response. Within the service class, I have a method like this: getReport(startDate: string, endDate: string) { return this.http.get<ReportReport>( ...

Refine the category based on a specified key

Currently, I am in the process of developing a React Hook using TypeScript. In this hook, I am passing both a key and a value that will be associated with this key as arguments. My objective is to constrain the type of the value based on the specified key. ...

Error in Angular integrating with Stripe. No definition found for 'Stripe'. Perhaps you meant 'stripe'?

I'm currently in the process of connecting Stripe to my app with redirection, utilizing Angular and typescript. My component contains the following code snippet: var head = document.getElementsByTagName('head')[0]; var script = document.cre ...

The script type `(close: any) => Element` cannot be assigned to type `ReactNode`

Encountering a problem while adding a popup in my TypeScript code Error: Type '(close: any) => Element' is not compatible with type 'ReactNode'. <Popup trigger={ <button className="fixed bott ...

Error Alert: Request missing connection details while trying to connect to Sql server via express.js

I am currently utilizing the most recent versions of node, express, and mssql module. My objective is to establish a connection with the local instance of SQL Server 2014 through express.js. Following the guidelines provided in the official documentation, ...

Guide to customizing the value appearance in tooltip axispointer chart (angular)

Check out the code snippet here: https://stackblitz.com/edit/angular-ngx-echarts-zn8tzx?file=src/app/app.component.ts view image description I am looking to format and add the text "UPLOAD" and "DOWNLOAD" below the date and time. For instance: 2020-02- ...

JavaScript array sorting not functioning for specialized logic

I am facing an issue with sorting arrays. I have a custom logic for displaying the array where each object has a 'code' column with values ('A', 'B', or 'C'). The requirement is to sort the records to display 'B ...

The auth_token in cookies cannot be located by node.js, resulting in a consistent TypeError being raised

I need to ensure that a user has a Json Web Token before they can access a static page. The code I have written checks for the presence of the JWT in the browser's cookies. However, I am encountering a TypeError, as shown at the end of this post. Inte ...

Tips for receiving a response from a function in Node.js

const detectLanguage = function (request) { translate.detect(request.body.phrase, function (error, result) { if (error) throw error; console.log(result); return result; }); router.post('/addPhrases& ...