Code Monkey home page Code Monkey logo

Comments (8)

hengnee avatar hengnee commented on August 20, 2024 1

Hi @darkterra, can this issue finally be closed?

from fastify-passport.

mcollina avatar mcollina commented on August 20, 2024

Can you provide a minimal reproducible example?

from fastify-passport.

darkterra avatar darkterra commented on August 20, 2024

Hello @mcollina,

Yes see this piece of code ("./routes/userR" => piece of code on my precedent post) :

'use strict'

const { readFileSync } = require('fs');
const { join } = require('path');

const fastify = require('fastify');

const passport = require('fastify-passport');
const secureSession = require('fastify-secure-session');

function build(opts = {}) {
  const app = fastify(opts);

  // --- plugins (from the Fastify ecosystem) ---
  app.register(secureSession, { key: readFileSync(join(__dirname, '..', 'secret-key')) })
  app.register(passport.initialize());
  app.register(passport.secureSession())

  // --- routes                               ---
  app.register(require('./routes/userR'));

  return app;
}

module.exports = build;

On the Front-End side, it's a simple button in a React WebApp :

  oauthLogin = () => {
    window.location.href = `${process.env.REACT_APP_API_URL}/get-in/google`
  }

  <CardActions className={classes.actions}>
    <Button variant="contained" color="secondary" size="large" onClick={this.oauthLogin}>
      <FontAwesomeIcon icon={faGoogle} className="faButton" /> Log in with Google
    </Button>
  </CardActions>

from fastify-passport.

mcollina avatar mcollina commented on August 20, 2024

The reason of something I can just run (after inserting secrets) is that otherwise it would take me too much effort to debug this.

from fastify-passport.

darkterra avatar darkterra commented on August 20, 2024

Ok.

npm init

npm i fastify fastify-passport fastify-secure-session passport-google-oauth20

./node_modules/.bin/secure-session-gen-key > secret-key

index.html :

<html>
  <head>
    <title>Test Fastify Passport</title>
  </head>

  <body>
    <Button  onClick="oauthLogin()">Login with Google</Button>
    <script>
      function oauthLogin() {
        console.log('oauthLogin fired...');
        window.location.href = 'http://localhost:3001/get-in/google';
      }
    </script>
  </body>
</html>

server.js :

'use strict'

const { readFileSync } = require('fs');
const { join } = require('path');

const fastify = require('fastify')({ logger: true });

const passport = require('fastify-passport');
const secureSession = require('fastify-secure-session');
const { Strategy: GoogleStrategy } = require('passport-google-oauth20');

const PORT = 3001;
const BASE_URL = 'http://localhost';
const CLIENT_ID = 'SET HERE YOUR CLIENT_ID';
const CLIENT_SECRET = 'SET HERE YOUR CLIENT_SECRET';
const CALLBACK = `${BASE_URL}:${PORT}/auth/google/callback`;


// --- plugins (from the Fastify ecosystem) ---
fastify.register(secureSession, { key: readFileSync(join(__dirname, 'secret-key')) })
fastify.register(passport.initialize());
fastify.register(passport.secureSession())


console.log('GoogleStrategy add to Passport');
console.log('CLIENT_ID: ', CLIENT_ID);
console.log('CLIENT_SECRET: ', CLIENT_SECRET);
console.log('CALLBACK: ', CALLBACK);

passport.use('google',
  new GoogleStrategy(
    {
      clientID: CLIENT_ID,
      clientSecret: CLIENT_SECRET,
      callbackURL: CALLBACK
    },
    function(accessToken, refreshToken, profile, done) {
      console.log('Verify Callback of GoogleStrategy Passport fired...');
      console.log('accessToken:', accessToken);
      console.log('refreshToken:', refreshToken);
      console.log('PROFILE:', profile);

      const googleEmail = profile.emails[0].value;

      console.log('GoogleUser LogIn... ', googleEmail);
      done();
      // Never fired -_-
    }
  )
)


function getInGoogleC (req, res, err, user, status) {
  console.log('FastifyPassport Callback of GoogleStrategy Passport fired...');
  console.log('err:', err);
  console.log('user:', user);
  console.log('status:', status);

  console.log('getInGoogle finish...');
}

function getCallbackGoogleC (req, res) {
  res.redirect(`${BASE_URL}:${PORT}/auth/google/callback?u=${encodeURIComponent(JSON.stringify(req.user))}`)
}

// --- routes                               ---
const defRoutes = [
  {
    method: 'GET',
    url: `/get-in/google`,
    preValidation: passport.authenticate('google', { session: true, scope: ['profile', 'email'] }),
    handler: getInGoogleC              // Never fired too -_-
  },
  {
    method: 'GET',
    url: `/auth/google/callback`,
    handler: getCallbackGoogleC  // no data into req.user decorator -_-
  }
]

// Add all routes into Fastify route system
for (const route of defRoutes) {
  fastify.route(route);
}


async function start () {
  try {
    // await connect(MONGO_URL, OPTIONS);

    fastify.listen(PORT, () => {
      console.log(fastify.printRoutes());
    });
    
  }
  catch (e) {
    throw e;
  }
}

start();

Normally this example is equivalent in a simpler version than the original code.

from fastify-passport.

darkterra avatar darkterra commented on August 20, 2024

Hello,

Do you have an idea on the origin of the bug ?

from fastify-passport.

leorossi avatar leorossi commented on August 20, 2024

@darkterra I did some tests, your code gives me a TOO_MANY_REDIRECTS error in chrome, you should user the preValidation hook also in the callback route to check against the passport strategy.

The code below is a simplified version of yours, and it prints the user correctly, can you check and see if it solves your problem?

'use strict'

const { readFileSync } = require('fs');
const { join } = require('path');

const fastify = require('fastify')({ logger: true });

const passport = require('fastify-passport');
const secureSession = require('fastify-secure-session');
const { Strategy: GoogleStrategy } = require('passport-google-oauth20');

const PORT = 3001;
const BASE_URL = 'http://localhost';
const CLIENT_ID = '...';
const CLIENT_SECRET = '...';
const CALLBACK = `${BASE_URL}:${PORT}/auth/google/callback`;


// --- plugins (from the Fastify ecosystem) ---
fastify.register(secureSession, { key: readFileSync(join(__dirname, 'secret-key')) })
fastify.register(passport.initialize());
//fastify.register(passport.secureSession())



console.log('GoogleStrategy add to Passport');
console.log('CLIENT_ID: ', CLIENT_ID);
console.log('CLIENT_SECRET: ', CLIENT_SECRET);
console.log('CALLBACK: ', CALLBACK);

passport.use('google',
  new GoogleStrategy(
    {
      clientID: CLIENT_ID,
      clientSecret: CLIENT_SECRET,
      callbackURL: CALLBACK
    },
    function (accessToken, refreshToken, profile, done) {
      console.log('Verify Callback of GoogleStrategy Passport fired...');
      console.log('accessToken:', accessToken);
      console.log('refreshToken:', refreshToken);
      console.log('PROFILE:', profile);

      const googleEmail = profile.emails[0].value;

      console.log('GoogleUser LogIn... ', googleEmail);

      done(null, profile);
    }
  )
)
passport.registerUserSerializer(async (user) => user.id);
passport.registerUserDeserializer(async (user) => user);

// --- routes                               ---
const defRoutes = [
  {
    method: 'GET',
    url: `/get-in/google`,
    preValidation: passport.authenticate('google', { session: true, scope: ['profile', 'email'] }),
    handler: (req, res, err, user, status) => {
      console.log('FastifyPassport Callback of GoogleStrategy Passport fired...');
      console.log('err:', err);
      console.log('user:', user);
      console.log('status:', status);

      console.log('getInGoogle finish...');
    }
  },
  {
    method: 'GET',
    url: `/auth/google/callback`,
    preValidation: passport.authenticate('google', { session: true }),
    handler: (req, res) => {
      return res.send(req.user);
    }
  }

]

// Add all routes into Fastify route system
for (const route of defRoutes) {
  fastify.route(route);
}


async function start() {
  try {

    fastify.listen(PORT, () => {
      console.log(fastify.printRoutes());

      console.log('Visit: http://localhost:3001/get-in/google');
    });

  }
  catch (e) {
    throw e;
  }
}

start();

from fastify-passport.

darkterra avatar darkterra commented on August 20, 2024

Hello @leorossi, Thank you a lot for your answare, I made a quick test and it's seem to be working !

I just want to do a another test juste to be sure, and then à close this issue ;)

from fastify-passport.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.